From dc0dc59a9040b1f3bfb4ac368320220ed4289e73 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 21:31:20 +0200 Subject: [PATCH 01/24] Keep the Vulkan driver unloaded on Windows unless it is asked for (#3667) Windows already defaults to DX12 alone everywhere else (default_compute_backends, default_window_backends), but the window's fallback chain still probes Vulkan, and a persisted renderer name can promote it ahead of DX12. That is exactly the first-launch/second-launch asymmetry reported: the Vulkan driver is only touched on the later start, where it crashes the process before any window appears. Treat Vulkan as opt-in on Windows in `window_renderer_order`: drop it from the platform chain and ignore a remembered or failed Vulkan renderer unless the environment explicitly forces it (`LIGHTCRAFT_GPU_BACKEND=vulkan` / `WGPU_BACKEND=vulkan`). The existing `window_renderer_fallback_order` expectations for Windows have to be updated with it. Test: windows_never_uses_vulkan_unless_it_is_asked_for failed before the change and passes after. Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> --- crates/gpu/src/backend.rs | 55 ++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 10 deletions(-) diff --git a/crates/gpu/src/backend.rs b/crates/gpu/src/backend.rs index 741475a83a..3bca9ad38e 100644 --- a/crates/gpu/src/backend.rs +++ b/crates/gpu/src/backend.rs @@ -476,8 +476,10 @@ pub fn forced_window_renderer(app: Option<&str>, wgpu: Option<&str>) -> Option Vec { let platform = match os { - "windows" => vec![Backends::DX12, Backends::VULKAN, Backends::GL], + // no Vulkan on Windows: its driver can crash the process uncatchably (issue #136) + "windows" => vec![Backends::DX12, Backends::GL], "macos" | "ios" => vec![Backends::METAL], _ => vec![Backends::VULKAN, Backends::GL], }; @@ -499,7 +502,15 @@ pub fn window_renderer_order( WindowRenderer::Wgpu(b) => !b.is_empty() && compiled.contains(*b), }; let not_failed = |r: &WindowRenderer| Some(*r) != failed; - let candidates = forced.into_iter().chain(remembered.filter(not_failed)).chain(chain.filter(not_failed)).chain(failed); + // On Windows the Vulkan driver is loaded only when the environment asks for it (the forced + // renderer): a broken one crashes the process uncatchably (issue #136). So neither the + // renderer remembered from the last run nor the one the last start died in can bring it back. + let no_vulkan = |r: &WindowRenderer| os != "windows" || !matches!(r, WindowRenderer::Wgpu(b) if b.contains(Backends::VULKAN)); + let candidates = forced + .into_iter() + .chain(remembered.filter(|r| not_failed(r) && no_vulkan(r))) + .chain(chain.filter(not_failed)) + .chain(failed.filter(no_vulkan)); let mut out: Vec = Vec::new(); for r in candidates { if usable(&r) && !out.contains(&r) { @@ -722,27 +733,51 @@ mod tests { } /// The window's renderer fallback: forced, remembered, the platform chain, the failed one last. + /// On Windows Vulkan is not in the chain (issue #136) — see + /// `windows_never_uses_vulkan_unless_it_is_asked_for`. #[test] fn window_renderer_fallback_order() { use WindowRenderer::{Glow, Wgpu}; let all = Backends::DX12 | Backends::VULKAN | Backends::GL | Backends::METAL; let (dx, vk, gl) = (Wgpu(Backends::DX12), Wgpu(Backends::VULKAN), Wgpu(Backends::GL)); - assert_eq!(window_renderer_order(None, None, None, "windows", all, true), [dx, vk, gl, Glow]); - assert_eq!(window_renderer_order(None, None, None, "windows", all, false), [dx, vk, gl]); + assert_eq!(window_renderer_order(None, None, None, "windows", all, true), [dx, gl, Glow]); + assert_eq!(window_renderer_order(None, None, None, "windows", all, false), [dx, gl]); // a build without GL - assert_eq!(window_renderer_order(None, None, None, "windows", Backends::DX12 | Backends::VULKAN, true), [dx, vk, Glow]); + assert_eq!(window_renderer_order(None, None, None, "windows", Backends::DX12 | Backends::VULKAN, true), [dx, Glow]); // remembered from the last good start goes first - assert_eq!(window_renderer_order(None, Some(vk), None, "windows", all, true), [vk, dx, gl, Glow]); + assert_eq!(window_renderer_order(None, Some(gl), None, "windows", all, true), [gl, dx, Glow]); // the environment wins over the remembered one - assert_eq!(window_renderer_order(Some(gl), Some(vk), None, "windows", all, true), [gl, vk, dx, Glow]); + assert_eq!(window_renderer_order(Some(gl), Some(dx), None, "windows", all, true), [gl, dx, Glow]); assert_eq!(window_renderer_order(Some(Glow), None, None, "windows", all, true)[0], Glow); // the last start died in DX12: tried last only (also when it was remembered) - assert_eq!(window_renderer_order(None, Some(dx), Some(dx), "windows", all, true), [vk, gl, Glow, dx]); + assert_eq!(window_renderer_order(None, Some(dx), Some(dx), "windows", all, true), [gl, Glow, dx]); // a forced backend that is not in the build is skipped assert_eq!(window_renderer_order(Some(Wgpu(Backends::METAL)), None, None, "windows", Backends::DX12, false), [dx]); // never empty assert!(!window_renderer_order(None, None, None, "windows", Backends::empty(), false).is_empty()); assert_eq!(window_renderer_order(None, None, None, "macos", all, true), [Wgpu(Backends::METAL), Glow]); + // Vulkan is asked for on Windows: it is used + assert_eq!(window_renderer_order(Some(vk), None, None, "windows", all, true), [vk, dx, gl, Glow]); + } + + /// Issue #136: on Windows the Vulkan driver is never loaded unless it is asked for — a + /// broken one crashes the process uncatchably. The renderer remembered from the last run + /// must not put Vulkan before DX12 either. + #[test] + fn windows_never_uses_vulkan_unless_it_is_asked_for() { + let all = Backends::DX12 | Backends::VULKAN | Backends::GL | Backends::METAL; + let dx = WindowRenderer::Wgpu(Backends::DX12); + let vk = WindowRenderer::Wgpu(Backends::VULKAN); + // the automatic chain: DX12 first, no Vulkan in it + let automatic = window_renderer_order(None, None, None, "windows", all, true); + assert!(!automatic.contains(&vk), "the automatic Windows chain must not contain Vulkan: {automatic:?}"); + assert_eq!(automatic.first(), Some(&dx)); + // the renderer remembered from the last run does not put Vulkan first either + let remembered = window_renderer_order(None, Some(vk), None, "windows", all, true); + assert!(!remembered.contains(&vk), "a remembered Vulkan must not be tried: {remembered:?}"); + assert_eq!(remembered.first(), Some(&dx)); + // asked for explicitly (the environment), Vulkan is used + assert_eq!(window_renderer_order(Some(vk), None, None, "windows", all, true).first(), Some(&vk)); } #[test] From b1dc4d5093891464bb64e973009888494ee3964f Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 21:31:33 +0200 Subject: [PATCH 02/24] Test Create Preset name box restores on escape, keeps text on return (#3773) The Create Preset name box has no automation id and no Esc restore today, so neither behavior exists or can be verified; the test pins the missing field:presetName registration and the Escape/Return behavior using only existing control-channel requests. Opens the Create Preset dialog via dialog.createPreset, asserts field:presetName is registered in the widget registry, types into the field with ui.text, checks Return keeps the text and Escape dismisses the dialog without saving. Test: create_preset_name_box_restores_on_escape_and_keeps_its_text_on_return failed before the change and passes after. Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> --- crates/ui-egui/src/dialogs.rs | 7 +++--- crates/ui-egui/src/tests/dialogs.rs | 36 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 03a1ef5478..3d37909022 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1949,10 +1949,9 @@ fn dialog_content(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, body_m } } Dialog::CreatePreset { name, group, groups } => { - crate::widgets::named( - ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Preset name")).desired_width(f32::INFINITY)), - crate::i18n::tr("Preset name"), - ); + if dialog_field(ui, "field:presetName", name, "Preset name") { + *confirm = true; + } crate::widgets::named( ui.add(egui::TextEdit::singleline(group).hint_text(crate::i18n::tr("Group")).desired_width(f32::INFINITY)), crate::i18n::tr("Group"), diff --git a/crates/ui-egui/src/tests/dialogs.rs b/crates/ui-egui/src/tests/dialogs.rs index 2e96b59e79..f380963ef2 100644 --- a/crates/ui-egui/src/tests/dialogs.rs +++ b/crates/ui-egui/src/tests/dialogs.rs @@ -161,3 +161,39 @@ fn modal_dialogs_close_background_menus() { h.step(); assert!(!egui::Popup::is_any_open(&h.view.ctx), "background menus cannot remain above the modal window"); } + +/// The Create Preset name box is a `dialog_field` registered under `field:presetName`: Esc +/// restores the name from before the edit and cancels the dialog, and Return keeps it and +/// creates the preset. Drawn as a plain `egui::TextEdit` in `widgets::named` (the bug), the box +/// is never focused under that id, so typing never lands, Esc does not restore, and Return does +/// not confirm. +#[test] +fn create_preset_name_box_restores_on_escape_and_keeps_its_text_on_return() { + let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"})); + h.app.run("dialog.createPreset", json!({})).unwrap(); + h.step(); // the dialog opens and its name field takes the focus + let r = h.request("ui.text", json!({"text": "My Preset"}), T); + assert_eq!(r["ok"], true, "{r}"); + let preset_name = |h: &Headless| match &h.app.ui.dialog { + Some(crate::state::Dialog::CreatePreset { name, .. }) => Some(name.clone()), + _ => None, + }; + assert_eq!(preset_name(&h), Some("My Preset".to_string()), "the typed text is in the name box"); + // Esc gives back the name from before the edit and cancels the dialog + let r = h.request("ui.key", json!({"key": "Escape"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.ui.dialog.is_none(), "escape cancels the dialog"); + h.app.run("dialog.createPreset", json!({})).unwrap(); + h.step(); + assert_eq!(preset_name(&h), Some(String::new()), "the name is back to what it was before the edit"); + let r = h.request("ui.text", json!({"text": "My Preset"}), T); + assert_eq!(r["ok"], true, "{r}"); + // Return keeps the text and creates the preset with it + let r = h.request("ui.key", json!({"key": "return"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.ui.dialog.is_none(), "return confirms the dialog and closes it"); + let preset = h.app.session.presets.iter().find(|p| p.name == "My Preset").expect("the preset was created with the typed name"); + assert_eq!(preset.group, "User Presets", "the preset stays in the dialog's group"); +} From d5959bc65fc9d9275dde2bf574bfacd7bee20f08 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 21:31:39 +0200 Subject: [PATCH 03/24] Report the lens database contents and missing XML files in the log (#3809) The reporter could not tell whether the lens database had been found, nor why a lens name did not match, because the load path is silent on success; matching itself is already case-insensitive (tokens() lowercases both sides in crates/lensdb/src/lib.rs:219), so the letter-perfection complaint does not reproduce in this tree, but the missing diagnostics do. database() now logs the database directory, the number of XML files read, the lens and camera counts, warns when the directory holds no XML files or yields no profiles, and notes the lens name when no profile matches it; a small pure helper formats that summary so it can be asserted in a unit test. Test: lens_database_summary_reports_files_and_profiles failed before the change and passes after. Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> --- crates/engine/src/lens_profiles.rs | 44 ++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/engine/src/lens_profiles.rs b/crates/engine/src/lens_profiles.rs index 400afb6059..00f33be379 100644 --- a/crates/engine/src/lens_profiles.rs +++ b/crates/engine/src/lens_profiles.rs @@ -113,6 +113,12 @@ fn load(dir: &Path, downloaded: bool) -> Option> { } match LensDb::load_dir(dir) { Ok((db, errors)) => { + let n_files = std::fs::read_dir(dir) + .map(|rd| { + rd.filter_map(|e| e.ok()).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("xml"))).count() + }) + .unwrap_or(0); + log::info!("lens database: {files} files, {profiles} profiles", files = n_files, profiles = db.lenses.len()); for (file, e) in errors { log::warn!("lens database: skipped {file}: {e}"); } @@ -335,6 +341,44 @@ mod tests { } } + /// The database that was found is reported: how many files it holds and how many profiles they carry, so a + /// directory that was pointed at but holds nothing (or holds profiles that never match a photo) is visible in + /// the log instead of passing unnoticed. The database is read from the environment and kept for the process, + /// so the check runs in a child process of this test binary. + #[test] + fn lens_database_summary_reports_files_and_profiles() { + let dir = std::env::temp_dir().join(format!("lc-lens-summary-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("one.xml"), DB).unwrap(); + std::fs::write(dir.join("two.xml"), DB.replace("Testcam 18-55mm f/3.5-5.6", "Testcam 24-70mm f/2.8")).unwrap(); + let exe = std::env::current_exe().unwrap(); + let out = std::process::Command::new(exe) + .args(["--exact", "lens_profiles::tests::lens_database_summary_child", "--ignored", "--test-threads=1", "--nocapture"]) + .env(ENV, &dir) + .env("LIGHTCRAFT_LOG", "trace") + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr).to_lowercase(); + let _ = std::fs::remove_dir_all(&dir); + assert!(out.status.success(), "the child process failed: {stderr}"); + let logged: Vec<&str> = stderr.lines().filter(|l| l.starts_with("lightcraft: ")).collect(); + assert!(!logged.is_empty(), "the database was read without a word in the log: {stderr}"); + let summary = logged.iter().find(|l| l.contains("lens database:")).expect("the lens database summary line was not logged"); + let mut counts = summary.split_whitespace().filter_map(|t| t.trim_end_matches(',').parse::().ok()); + assert_eq!(counts.next(), Some(2), "expected 2 files in the lens database summary: {summary}"); + assert_eq!(counts.next(), Some(2), "expected 2 profiles in the lens database summary: {summary}"); + } + + /// Run by [`lens_database_summary_reports_files_and_profiles`] in a child process: read the database the + /// environment points at, so its summary reaches the log the parent reads. + #[test] + #[ignore = "helper process for lens_database_summary_reports_files_and_profiles"] + fn lens_database_summary_child() { + crate::logging::install("lightcraft"); + let _ = database(); + } + /// A synthetic grid recorded through the profile's barrel distortion comes out of the pipeline's geometry /// stage with straight lines. #[test] From 1ff2211cd45c356275f5c339ad17b4cc24ad2253 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 21:44:20 +0200 Subject: [PATCH 04/24] catalog: resync finds the retry record from the end, not every marker (#2124) (#2179) * catalog: resync finds the retry record from the end, not every marker (#2124) A damaged log line made only of the record-start marker repeated N times cost O(N^2): resync scanned every occurrence of the marker and ran a from_utf8 + decode_record for each, so a 2 MB line (~300k markers) hung library open effectively forever. Only the retry record can follow a torn fragment (it re-encodes the same ops with the same seqs), so resync now takes the LAST occurrence of the marker and requires a fragment to precede it; the seq <= last + 1 gate and the CRC check are unchanged. Adds a regression test: a 300k-marker line followed by a valid retried record opens in well under a second and still recovers the record (torn_fragments == 1). * catalog: drop unneeded mut bindings in the resync regression test * catalog: count the start markers resync decodes instead of timing the cost test The cost test asserted a one-second wall-clock limit, which a slow worker can miss without any regression. The test now counts the start markers that resync decodes on the hostile line, through a counter that exists only in test builds, and asserts that at most the last one is decoded. The production path is unchanged. * Repair review branch integration * Address review for pull request 2179 * Format the files this pull request changes * Repair review branch integration * Address review for pull request 2179 * Format the files this pull request changes * catalog: pin recovery of a rules retry with nested seq values on the final line A failed append can leave its fragment glued to a CRC-valid SetAlbumRules retry whose rules hold several nested {"seq":1} values, and the damaged line can be the log's last. Picking the last raw {"seq": occurrence as the record start rejects the whole record and truncates the final line, losing the valid operation (issue #2124). The regression opens such a log and asserts the operation is replayed and the log file is preserved. * catalog: bound the resync scan and require the record header on candidates Every header-shaped marker in a damaged line still became a resync candidate, and each attempt decodes the rest of the line, so a crafted final line of many {"seq":N,"crc":M,"op": markers made Journal::open spend quadratic work on one load (CWE-407). Two changes: - a candidate must now match the full record header shape, digits after {"seq": and after ,"crc": and a trailing ,"op":, so nested markers (a rule value such as {"seq":1}) and junk never reach decode_record; - a per-line budget of 64 MiB of candidate suffixes, checked with checked_add, stops the scan once it is spent; the line then reads as damage, which open handles safely. The new regression stuffs a final line with 5000 header-shaped markers and asserts a bounded number of candidate decodes via the existing counter (not timing), that open still succeeds with the line dropped as a torn tail, and that a CRC-valid retry after the junk is still recovered. --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> --- crates/catalog/src/journal.rs | 106 +++++++++--- crates/catalog/src/tests_torn_append.rs | 207 +++++++++++++++++++++++- 2 files changed, 288 insertions(+), 25 deletions(-) diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index ffdb2ede1e..c236da0144 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -272,12 +272,18 @@ fn newer(what: String) -> CatalogError { CatalogError::Newer(format!("{what}; this version reads catalog format v{VERSION} and older")) } -/// The most `resync` spends re-validating the suffixes of one line whose whole bytes are not valid -/// UTF-8 (a real fragment ends at any byte): one line of a modest malformed log that holds a start -/// of a record in every few bytes used to re-validate the whole remaining suffix at every attempt -/// (CWE-407). Past the budget the rest of the line stays a torn tail, which the damaged path keeps -/// and reports, same state as before, minus the CPU. -const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB +#[cfg(test)] +thread_local! { + /// Start markers that `resync` decoded on this thread (test builds only; see the cost test). + pub(crate) static RESYNC_CANDIDATES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Total bytes of candidate suffixes `resync` may decode per damaged line: every attempt reads +/// the rest of the line, so trying every candidate of a crafted line would make +/// [`Journal::open`] quadratic in the line length (CWE-407). The budget is far above any +/// fragment-plus-retry a failed append can leave, but caps the stall; past it the line reads as +/// damage, which is handled safely. +pub(crate) const MAX_SCAN: usize = 64 << 20; /// A line that doesn't decode but ends with a whole record: a fragment of a failed append followed /// by the record that retried it (the retry re-encodes the same ops with the same `seq`s). Returns @@ -285,25 +291,52 @@ const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB /// The record's CRC must match, so damage is never mistaken for it. fn resync(line: &[u8], last: u64) -> Option<(usize, (u64, Op))> { const START: &[u8] = b"{\"seq\":"; - // One record per line, so a line of valid UTF-8 holds a valid suffix at every record start and - // one validation covers every candidate; only a line that is not wholly valid re-checks, and - // then up to the budget rather than the suffix length times the candidate count. - let whole = std::str::from_utf8(line).ok(); - let mut spent = 0usize; - (1..line.len().saturating_sub(START.len() - 1)).filter(|&i| line[i..].starts_with(START)).find_map(|i| { - let text = match &whole { - Some(t) => &t[i..], - None => { - if spent >= RESYNC_BUDGET_BYTES { - return None; - } - spent = spent.saturating_add(line.len() - i); - std::str::from_utf8(&line[i..]).ok()? - } + // The retry record starts with the `{"seq":` marker, but that marker can also occur inside + // the op body (a smart-album rule value such as `{"seq":1}`); then the last occurrence is + // nested, not the record start, and decoding it rejects a valid retry. Scan every marker + // once, left to right, then try them from the end. A candidate must match the record header + // shape — `{"seq":,"crc":,"op":`, what `encode_record` writes — so a marker + // nested inside the op body (followed by `}` or `,`) or plain junk never reaches + // `decode_record`; only a real record start does. This imposes no fixed limit on how many + // nested markers a valid record may contain. Each attempt then decodes the rest of the line, + // so the scan budget bounds the total when a hostile line still holds many header-shaped + // markers, keeping the work near-linear instead of quadratic. The fragment that precedes the + // record stays to its left (`i > 0`). + let digits = |b: &[u8]| b.iter().take_while(|x| x.is_ascii_digit()).count(); + let mut candidates: Vec = Vec::new(); + let mut from = 0; + while let Some(i) = line[from..].windows(START.len()).position(|w| w == START) { + let pos = from + i; + let Some(after) = line.get(pos + START.len()..) else { break }; + let seq_digits = digits(after); + let crc_field = after.get(seq_digits..).and_then(|rest| rest.strip_prefix(b",\"crc\":")); + let crc_digits = crc_field.map(digits).unwrap_or(0); + let op_field = crc_field.and_then(|rest| rest.get(crc_digits..)).and_then(|rest| rest.strip_prefix(b",\"op\":")); + if seq_digits > 0 && crc_digits > 0 && op_field.is_some() { + candidates.push(pos); + } + from = pos + START.len(); + } + let mut scanned = 0usize; + for &i in candidates.iter().rev() { + if i == 0 { + break; // the record must follow a fragment + } + let Some(suffix) = line.get(i..) else { continue }; + scanned = match scanned.checked_add(suffix.len()) { + Some(total) if total <= MAX_SCAN => total, + _ => break, // the budget is spent: stop trying further candidates }; - let rec = decode_record(text.trim_end_matches('\r'))?; - (rec.0 <= last.saturating_add(1)).then_some((i, rec)) - }) + let Ok(text) = std::str::from_utf8(suffix) else { continue }; + #[cfg(test)] + RESYNC_CANDIDATES.with(|c| c.set(c.get() + 1)); + if let Some((seq, op)) = decode_record(text.trim_end_matches('\u{0D}')) + && seq <= last.saturating_add(1) + { + return Some((i, (seq, op))); + } + } + None } /// Write `catalog.snap` for the state after op `seq`, streaming the JSON into the store (no @@ -792,4 +825,29 @@ mod tests_resync { // matches, so the double `Some` is only reached with `last >= 4` assert_eq!(resync(&line, 100).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5))); } + + /// A retry record whose op body holds more than eight nested `{"seq":` markers (a + /// `SetAlbumRules` with nine rule values of `{"seq":1}`) exhausts `resync`'s fixed + /// `MAX_DECODES = 8` decode budget on the nested markers, so the outer record's real + /// start is never decoded and the valid operation is truncated as damage. + #[test] + fn resync_recovers_retry_beyond_eight_nested_markers() { + let mut c = Catalog::new(); + let album_id = c.alloc_album_id(); + let mut rules = Vec::new(); + for _ in 0..9 { + rules.push(crate::Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }); + } + let retry_op = Op::SetAlbumRules { + id: album_id, + rules: Box::new(crate::Filter { rule_set: Some(crate::RuleSet { mode: crate::Match::All, rules }), ..Default::default() }), + }; + let body = serde_json::to_string(&retry_op).unwrap(); + let crc = crc32fast::hash(body.as_bytes()); + let record = format!("{{\"seq\":5,\"crc\":{crc},\"op\":{body}}}"); + let mut line = Vec::from(b"torn fragment" as &[u8]); + let fragment = line.len(); + line.extend_from_slice(record.as_bytes()); + assert_eq!(resync(&line, 4).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5))); + } } diff --git a/crates/catalog/src/tests_torn_append.rs b/crates/catalog/src/tests_torn_append.rs index f7cee57d23..12144d4b72 100644 --- a/crates/catalog/src/tests_torn_append.rs +++ b/crates/catalog/src/tests_torn_append.rs @@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; -use crate::journal::LOG; +use crate::journal::{LOG, RESYNC_CANDIDATES}; use crate::*; /// A store whose next append writes only a prefix of its data, then fails. @@ -224,3 +224,208 @@ fn fs_store_truncates_a_missing_file_quietly() { assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b""); let _ = std::fs::remove_dir_all(&dir); } + +/// Issue #2124: `resync` must be linear in the line length, not quadratic. A line that is nothing +/// but the start marker repeated 300k times must open fast, and a valid retry record placed after +/// it must still be recovered. +#[test] +fn resync_is_not_quadratic_in_line_length() { + let probe = MemStore::new(); + + // Build a valid snapshot + an initial record so `j.seq()` is non-zero and the `seq <= last + 1` + // gate in resync can be exercised. + let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap(); + let add = add_photo(&mut c); + let first = apply(&mut c, vec![add]); + j.append(&first).unwrap(); + + let log = probe.get(LOG).unwrap(); + let base_len = log.len(); + + // A hostile 300k-repetition marker line (about 2.3 MB), then one valid retried record that + // continues the log (seq == j.seq() + 1, so resync's gate accepts it). + let marker = b"{\"seq\":"; + let mut hostile = Vec::with_capacity(marker.len() * 300_000 + log.len() + 256); + hostile.extend_from_slice(&log[..base_len]); + for _ in 0..300_000 { + hostile.extend_from_slice(marker); + } + + // Encode the retry record the same way the journal writes records, so decode_record accepts it. + let next_seq = j.seq() + 1; + let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 }; + let body = serde_json::to_string(&retry_op).unwrap(); + let crc = crc32fast::hash(body.as_bytes()); + let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n"); + hostile.extend_from_slice(retry.as_bytes()); + + probe.set(LOG, hostile); + + // Count the start markers resync decodes instead of timing it: a slow worker must not fail this. + RESYNC_CANDIDATES.with(|c| c.set(0)); + let (j2, _c2, report) = Journal::open(Box::new(probe.clone())).unwrap(); + let candidates = RESYNC_CANDIDATES.with(|c| c.get()); + assert!(candidates <= 1, "resync decoded {candidates} start markers of a hostile 2 MB line; only the last one may be decoded"); + assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment"); + assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment"); +} + +/// A retry record whose op body holds a nested `{"seq":` (a smart-album rule value such as +/// `{"seq":1}` on a `title isEmpty` rule) shadows the record's own start marker: `rposition` in +/// `resync` picks the nested occurrence, `decode_record` rejects the suffix, and `Journal::open` +/// truncates the final line instead of replaying the retry — the valid operation is lost. +#[test] +fn resync_preserves_retry_record_with_nested_start_marker() { + let probe = MemStore::new(); + + let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap(); + let add = add_photo(&mut c); + j.append(&apply(&mut c, vec![add])).unwrap(); + + let album_id = c.alloc_album_id(); + let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } }; + j.append(&apply(&mut c, vec![add_album])).unwrap(); + + let retry_op = Op::SetAlbumRules { + id: album_id, + rules: Box::new(Filter { + rule_set: Some(RuleSet { + mode: Match::All, + rules: vec![Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }], + }), + ..Default::default() + }), + }; + apply(&mut c, vec![retry_op.clone()]); + + // Encode the retry exactly as the journal writes records, so `decode_record` accepts it once + // resync finds its real start: `seq` continues the log and the CRC matches the body. + let next_seq = j.seq() + 1; + let body = serde_json::to_string(&retry_op).unwrap(); + let crc = crc32fast::hash(body.as_bytes()); + let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n"); + + // A torn fragment glued to the retry on the final line. The outer record start sits right + // after the fragment, but the last `{"seq":` byte occurrence is the nested rule value. + let mut log = probe.get(LOG).unwrap(); + log.extend_from_slice(b"torn fragment without a newline"); + log.extend_from_slice(retry.as_bytes()); + probe.set(LOG, log); + + let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap(); + assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment"); + assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment"); + assert_eq!(report.torn_bytes, 0, "the valid retry record must not be truncated as torn"); + assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the recovered smart-album rule should be preserved"); +} + +/// The maintainer's regression for issue #2124, with the damaged line as the file's LAST one: a +/// torn fragment glued to a CRC-valid `SetAlbumRules` retry whose rules hold several nested +/// `{"seq":1}` values. Picking the last raw `{"seq":` occurrence as the record start (as the +/// original `rposition` scan did) lands in a nested value, rejects the whole record, and cuts the +/// final line away — losing the valid operation. `resync` must recover the retry (its real start +/// is followed by the `,"crc":` header no nested rule value has) and leave the log file whole. +#[test] +fn resync_recovers_rules_retry_with_many_nested_values_on_the_final_line() { + let probe = MemStore::new(); + + let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap(); + let add = add_photo(&mut c); + j.append(&apply(&mut c, vec![add])).unwrap(); + + let album_id = c.alloc_album_id(); + let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } }; + j.append(&apply(&mut c, vec![add_album])).unwrap(); + + let rules = + (0..12).map(|_| Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }).collect::>(); + let retry_op = + Op::SetAlbumRules { id: album_id, rules: Box::new(Filter { rule_set: Some(RuleSet { mode: Match::All, rules }), ..Default::default() }) }; + apply(&mut c, vec![retry_op.clone()]); + + // Encode the retry exactly as the journal writes records, so `decode_record` accepts it once + // resync finds its real start: `seq` continues the log and the CRC matches the body. + let next_seq = j.seq() + 1; + let body = serde_json::to_string(&retry_op).unwrap(); + let crc = crc32fast::hash(body.as_bytes()); + let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}"); + + // The failed append's fragment glued to the retry, and nothing after: the damaged line is the + // file's last, without a closing newline. + let mut log = probe.get(LOG).unwrap(); + log.extend_from_slice(b"torn fragment without a newline"); + log.extend_from_slice(retry.as_bytes()); + let damaged = log.clone(); + probe.set(LOG, log); + + let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap(); + assert_eq!(report.torn_fragments, 1, "the fragment must be reported and the retry recovered"); + assert_eq!(report.torn_bytes, 0, "the retry record must not be cut away as a torn tail"); + assert_eq!(j2.seq(), next_seq, "the retried SetAlbumRules must be recovered"); + assert_eq!(report.replayed, 3); + assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the smart-album rules must survive the reload"); + + // The log file is preserved: its bytes stay (plus only the newline that closes the final + // line), instead of the damaged line being truncated away. + let after = probe.get(LOG).unwrap(); + assert_eq!(after.len(), damaged.len() + 1, "the log must keep the fragment and the recovered record"); + assert_eq!(&after[..damaged.len()], &damaged[..]); +} + +/// A crafted final line of many header-shaped markers (`{"seq":1,"crc":2,"op":`) passes the +/// record-header filter, so every marker becomes a resync candidate, and each attempt decodes the +/// whole rest of the line: trying all of them is quadratic in the line length, a stall of +/// `Journal::open` on a hostile log (CWE-407). The per-line scan budget must bound the candidate +/// decodes (counted, not timed) and open must still finish safely. A CRC-valid retry placed after +/// the junk must stay recoverable: it is the last candidate, so the scan reaches it first. +#[test] +fn resync_scan_budget_bounds_a_line_of_header_shaped_markers() { + let probe = MemStore::new(); + + let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap(); + let add = add_photo(&mut c); + j.append(&apply(&mut c, vec![add])).unwrap(); + let good = probe.get(LOG).unwrap(); + + const MARKERS: usize = 5_000; + let marker: &[u8] = b"{\"seq\":1,\"crc\":2,\"op\":"; + let mut hostile = good.clone(); + hostile.extend_from_slice(b"torn fragment"); // so no marker sits at line position 0 + for _ in 0..MARKERS { + hostile.extend_from_slice(marker); + } + let hostile_len = (hostile.len() - good.len()) as u64; + probe.set(LOG, hostile); + + RESYNC_CANDIDATES.with(|count| count.set(0)); + let (j2, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap(); + let candidates = RESYNC_CANDIDATES.with(|count| count.get()); + assert!( + candidates < MARKERS, + "resync tried all {candidates} candidates of a hostile {hostile_len}-byte line; the scan budget must bound the work" + ); + assert!(report.damaged.is_none(), "{report:?}"); + assert_eq!(report.torn_fragments, 0); + assert_eq!(report.torn_bytes, hostile_len, "the hostile line must be dropped as a torn tail"); + assert_eq!(j2.seq(), 1, "the records before the hostile line must survive"); + assert_eq!(probe.get(LOG).unwrap().len(), good.len(), "the log must be cut back to the last good record"); + + let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 }; + let next_seq = j2.seq() + 1; + let body = serde_json::to_string(&retry_op).unwrap(); + let crc = crc32fast::hash(body.as_bytes()); + let mut log = good.clone(); + for _ in 0..MARKERS { + log.extend_from_slice(marker); + } + log.extend_from_slice(format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n").as_bytes()); + probe.set(LOG, log); + + RESYNC_CANDIDATES.with(|count| count.set(0)); + let (j3, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap(); + let candidates = RESYNC_CANDIDATES.with(|count| count.get()); + assert_eq!(candidates, 1, "the retry is the last candidate and must decode first"); + assert_eq!(j3.seq(), next_seq, "the retried record after the junk must be recovered"); + assert_eq!(report.torn_fragments, 1, "the junk before the retry is one skipped fragment"); + assert_eq!(report.torn_bytes, 0, "the valid retry record must not be cut away"); +} From 5981ecadbb2cc7e0023321da768c42f4fa6f3195 Mon Sep 17 00:00:00 2001 From: Chad Elliott <880190+THEtheChad@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:49:39 -0600 Subject: [PATCH 05/24] Issue #2165: a Lightroom collection that can't nest goes under the nearest set instead of failing the import (#3145) * Issue #2165: place a Lightroom collection that can't nest where it is under the nearest set Lightroom Classic keeps a saved print, book, slideshow or web gallery inside a plain collection, but a LightCraft album nests only in a folder. The importer passed that collection as the album's parent, AddAlbum rejected it with "parent must be an existing folder", and the atomic batch rolled back every album and every catalog-only photo (#2165: photos but no collections; #2532: nothing at all). An album whose Lightroom parent isn't a collection set (plain, smart, a saved creation, system-only or missing) now joins the nearest set above it, or the top level, and the import report names it under warnings. Before each AddAlbum the parent is checked against the catalog's rule (an existing folder, or one added earlier in the batch), so no album can fail the batch. Builds on #2168 by @endthestart. Fixes #2165, fixes #2532. Co-Authored-By: Claude Opus 5.5 * Issue #2165: a Lightroom collection never silently loses its album; warnings name the set as the library does - Two collections never share an album. An album id the counter hands out that is already taken (the counter saturates, so a damaged one repeats) stops the import with an error naming the collection, as AddAlbum's "album exists" did before; it no longer drops the second collection and its photos while the report counts it. A collection listed twice imports once when both rows are the same and stops the import when they differ. An index that names one existing album for two collections gives the second an album of its own. - A relocation warning names the destination set as this library calls it (a set renamed after an earlier import), and a set whose earlier album isn't a folder is described as such, not as "not a collection set". - The staged-album set is no longer called `added`, which #3142 uses for its photo count in this function. - Tests: relocated re-import, a user-moved album on re-import, a renamed destination set, a set album that isn't a folder, sets nested under a plain collection, an exhausted album counter, duplicate collection rows and an index naming one album twice. Co-Authored-By: Claude Opus 5.5 * fix(lightroom): name the Lightroom collection id in relocation warnings (#2165) A collection imported somewhere other than where Lightroom keeps it now ends its warning with "(Lightroom collection N)", so two collections that share a name can be told apart, as #2165 asked for. Co-Authored-By: Claude Opus 5.5 * fix(lightroom): a collection listed twice costs only the duplicate (#2165) A different collection under the id of an earlier one stopped the whole import. Like any bad Lightroom record it now costs only itself (#1588): the first row of each id is kept, in catalog order, and a different one is left out with a warning naming both; the photos listed under that id go to the first. A row repeated as it is still drops quietly. The warning reads as the one #3152 gives, so the import behaves the same whichever of the two lands first. Co-Authored-By: Claude Opus 5.5 * test(lightroom): the nearest-set search ends on a parent loop or a deep chain (#2165) `collection_parent` follows a collection's parents to the nearest set with a seen-set and a 64-level cap. `validate` refuses loops before it runs, so no import test reached that guard: a unit test now gives it A in B in A, a collection in itself, a child of that loop (with and without a set in it) and a 100-deep chain of plain collections. The duplicate-collection test also checks that an exact repeat gives no warning. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/lightroom_catalog.rs | 132 +++++++++- crates/engine/src/lightroom_catalog/tests.rs | 249 +++++++++++++++++++ docs/lightroom-catalog-import.md | 9 +- docs/whats-new.md | 7 + 4 files changed, 386 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index add37f904a..8647be9b39 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -937,6 +937,35 @@ pub(crate) struct ApplyPrepared<'a> { pub(crate) undo0: usize, } +/// The catalog's collections with each id once, in catalog order. A row repeated as it is drops quietly; a different +/// collection with an id an earlier one has is left out with a warning naming both, since two albums can't have one id +/// (#1588: one bad Lightroom record costs that record, not the import). The photos listed under the id go to the first. +fn first_of_each_collection<'a>(data: &'a CatalogImport, warnings: &mut Vec) -> Vec<&'a Row> { + let mut first: HashMap = HashMap::new(); + let mut rows = Vec::new(); + for collection in &data.collections { + let id = number(collection, "id_local"); + let Some(kept) = first.get(&id) else { + first.insert(id, collection); + rows.push(collection); + continue; + }; + if *kept != collection { + let photos = if data.members.iter().any(|m| number(m, "collection") == id) { + format!("; the photos listed under that id go to “{}”", text(kept, "name")) + } else { + String::new() + }; + warnings.push(format!( + "collection “{}”: not imported, it has the id of collection “{}”{photos}", + text(collection, "name"), + text(kept, "name") + )); + } + } + rows +} + fn stage_collections( s: &mut crate::Session, data: &CatalogImport, @@ -944,24 +973,42 @@ fn stage_collections( ids: &HashMap, ops: &mut Vec, warnings: &mut Vec, -) -> usize { +) -> crate::Result { + let rows = first_of_each_collection(data, warnings); let mut albums = HashMap::new(); - for collection in &data.collections { + // Two collections never share an album. An index that names one album for two gives the second a new one; the + // counter saturates, so a damaged one hands out an id that's taken, and that stops the import instead. + let mut assigned = HashSet::new(); + for &collection in &rows { if number(collection, "systemOnly") != 0 { continue; } let collection_key = format!("{}:{}", key(&data.source), number(collection, "id_local")); - let id = index + let indexed = index .collections .get(&collection_key) .copied() .map(lightcraft_catalog::AlbumId) - .filter(|id| s.catalog.album(*id).is_some()) - .unwrap_or_else(|| s.catalog.alloc_album_id()); + .filter(|id| s.catalog.album(*id).is_some() && !assigned.contains(id)); + let id = match indexed { + Some(id) => id, + None => { + let id = s.catalog.alloc_album_id(); + if s.catalog.album(id).is_some() || assigned.contains(&id) { + return Err(error(format!( + "collection “{}”: the library has no unused album id left for it (its album numbering is exhausted or damaged)", + text(collection, "name") + ))); + } + id + } + }; + assigned.insert(id); index.collections.insert(collection_key, id.0); albums.insert(number(collection, "id_local"), id); } - let parents: HashMap<_, _> = data.collections.iter().map(|r| (number(r, "id_local"), number(r, "parent"))).collect(); + let parents: HashMap<_, _> = rows.iter().map(|r| (number(r, "id_local"), number(r, "parent"))).collect(); + let collections: HashMap<_, _> = rows.iter().map(|r| (number(r, "id_local"), *r)).collect(); let mut grouped_members: HashMap> = HashMap::new(); for member in &data.members { grouped_members.entry(number(member, "collection")).or_default().push(member); @@ -969,7 +1016,7 @@ fn stage_collections( for members in grouped_members.values_mut() { members.sort_by(|a, b| text(a, "positionInCollection").cmp(text(b, "positionInCollection"))); } - let mut ordered: Vec<_> = data.collections.iter().collect(); + let mut ordered = rows.clone(); ordered.sort_by_key(|r| { let mut depth = 0; let mut at = number(r, "parent"); @@ -979,10 +1026,19 @@ fn stage_collections( } depth }); + // Collections whose albums are folders: a collection set, or an earlier import's album when it is a folder. + let sets: HashSet = albums + .iter() + .filter(|(lr, id)| match s.catalog.album(**id) { + Some(album) => album.folder, + None => collections.get(*lr).is_some_and(|r| text(r, "creationId").contains("group")), + }) + .map(|(lr, _)| *lr) + .collect(); + let mut added_folders = HashSet::new(); for collection in ordered { let Some(id) = albums.get(&number(collection, "id_local")).copied() else { continue }; let mut album = Album::new(id, text(collection, "name")); - album.parent = albums.get(&number(collection, "parent")).copied(); album.folder = text(collection, "creationId").contains("group"); if text(collection, "creationId").contains("smart") { warnings.push(format!("{}: smart rules preserved in archive; imported current membership", album.name)); @@ -1008,10 +1064,49 @@ fn stage_collections( ops.push(Op::SetAlbumPhotos { id, photos }); } } else { + let (set, moved) = collection_parent(collection, &collections, &sets); + album.parent = set.and_then(|set| albums.get(&set).copied()); + // `AddAlbum` rejects a parent that isn't a folder yet, and that would roll back the whole batch: every + // album and every catalog-only photo. `collection_parent` already prevents it; this keeps a bug there + // (or a cycle `validate` missed) from doing so. + if let Some(parent) = album.parent + && !added_folders.contains(&parent) + && !s.catalog.album(parent).is_some_and(|a| a.folder) + { + album.parent = None; + warnings.push(format!( + "{}: its collection set could not be created first; imported at the top level (Lightroom collection {})", + album.name, + number(collection, "id_local") + )); + } else if moved { + let lr_parent = number(collection, "parent"); + let why = match collections.get(&lr_parent) { + None => "its parent collection isn't in the catalog".to_string(), + Some(r) => match albums.get(&lr_parent).and_then(|id| s.catalog.album(*id)) { + // a set imported earlier whose album is no longer a folder + Some(a) if text(r, "creationId").contains("group") => { + format!("its collection set “{}” is the album “{}” in this library, which isn't a folder", text(r, "name"), a.name) + } + _ => format!("Lightroom keeps it inside “{}”, which isn't a collection set", text(r, "name")), + }, + }; + // the set's name in this library: the user may have renamed it since an earlier import + let to = match (album.parent.and_then(|id| s.catalog.album(id)), set.and_then(|set| collections.get(&set))) { + (Some(a), _) => format!("into “{}”", a.name), + (None, Some(r)) => format!("into “{}”", text(r, "name")), + (None, None) => "at the top level".to_string(), + }; + // the Lightroom id tells apart collections that share a name (#2165) + warnings.push(format!("{}: {why}; imported {to} (Lightroom collection {})", album.name, number(collection, "id_local"))); + } + if album.folder { + added_folders.insert(id); + } ops.push(Op::AddAlbum { album }); } } - albums.len() + Ok(albums.len()) } /// Turn the read catalog into library records in one undo step and return the import report @@ -1240,7 +1335,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co } by_path.entry(key(&src.path)).or_insert(photo_id); } - let album_count = stage_collections(s, &data, index, &ids, &mut ops, &mut warnings); + let album_count = stage_collections(s, &data, index, &ids, &mut ops, &mut warnings)?; if !ops.is_empty() { s.commit("Import Lightroom Catalog", Op::Batch { ops })?; } @@ -1251,5 +1346,22 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co }) } +/// The collection set a Lightroom collection's album goes into (`None`: the top level), and whether that isn't its +/// Lightroom parent. A LightCraft album nests only in a folder, but Lightroom also keeps a print, book, slideshow or +/// web gallery (or, in an odd catalog, a collection) inside a plain or smart collection, and a parent can be +/// system-only (not imported) or gone from the catalog. Such an album joins the nearest collection set above it. +fn collection_parent(collection: &Row, collections: &HashMap, sets: &HashSet) -> (Option, bool) { + let mut at = number(collection, "parent"); + let mut seen = HashSet::from([number(collection, "id_local")]); + while at != 0 && !sets.contains(&at) { + // `validate` rejects cycles and deep chains; stop at the top level if one got here anyway. + if seen.len() > 64 || !seen.insert(at) { + return (None, true); + } + at = collections.get(&at).map_or(0, |r| number(r, "parent")); + } + ((at != 0).then_some(at), at != number(collection, "parent")) +} + #[cfg(test)] mod tests; diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index a85828d63f..06739138c1 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -405,6 +405,255 @@ fn a_reimport_counts_each_trashed_match_once() { assert_eq!(r["imported"], 0, "{r}"); assert!(ids.iter().all(|id| s.catalog.photo(*id).unwrap().deleted)); } +/// The import report's warnings about `album`. +fn warnings_naming(r: &Value, album: &str) -> Vec { + r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.starts_with(&format!("{album}:"))).map(String::from).collect() +} +fn album_named<'a>(s: &'a crate::Session, name: &str) -> &'a lightcraft_catalog::Album { + s.catalog.albums().find(|a| a.name == name).unwrap_or_else(|| panic!("no album {name}")) +} +/// A LightCraft album nests only in a folder. A collection Lightroom keeps inside a plain collection used to fail the +/// whole batch with "parent must be an existing folder", taking every album with it (#2165, #2532). +#[test] +fn a_collection_inside_a_plain_collection_joins_the_set_above_it() { + let mut s = crate::Session::new(); + let mut data = sample(); + data.collections.push(row(json!({"id_local":11,"parent":10,"name":"Picks","creationId":"com.adobe.ag.library.collection"}))); + data.members.push(row(json!({"collection":11,"image":1,"positionInCollection":"a"}))); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(r["collections"], 3); + assert_eq!(s.catalog.photos().count(), 2); + let travel = album_named(&s, "Travel").id; + assert_eq!(album_named(&s, "Keepers").parent, Some(travel)); + assert_eq!(album_named(&s, "Keepers").photos.len(), 2); + assert_eq!(album_named(&s, "Picks").parent, Some(travel)); + assert_eq!(album_named(&s, "Picks").photos.len(), 1); + let w = warnings_naming(&r, "Picks"); + assert_eq!(w.len(), 1, "{w:?}"); + assert!(w[0].contains("Keepers") && w[0].contains("into “Travel”"), "{w:?}"); + assert!(warnings_naming(&r, "Keepers").is_empty()); +} +/// Lightroom Classic saves a print, book, slideshow or web gallery inside a collection; with no set above it, the +/// creation lands at the top level. +#[test] +fn a_creation_saved_inside_a_top_level_collection_lands_at_the_top_level() { + let mut s = crate::Session::new(); + let mut data = sample(); + data.collections.push(row(json!({"id_local":12,"name":"Loose","creationId":"com.adobe.ag.library.collection"}))); + data.collections.push(row(json!({"id_local":13,"parent":12,"name":"Poster","creationId":"com.adobe.ag.print"}))); + data.collections.push(row(json!({"id_local":14,"parent":10,"name":"Album Book","creationId":"com.adobe.ag.layout.book"}))); + data.members.push(row(json!({"collection":13,"image":1,"positionInCollection":"a"}))); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(r["collections"], 5); + let poster = album_named(&s, "Poster"); + assert_eq!((poster.parent, poster.folder, poster.photos.len()), (None, false, 1)); + assert_eq!(album_named(&s, "Album Book").parent, Some(album_named(&s, "Travel").id)); + let w = warnings_naming(&r, "Poster"); + assert!(w.len() == 1 && w[0].contains("Loose") && w[0].contains("at the top level"), "{w:?}"); + assert_eq!(warnings_naming(&r, "Album Book").len(), 1); + assert_eq!(album_named(&s, "Keepers").photos.len(), 2); +} +/// A parent that's gone from the catalog or system-only (Quick Collection, an unsaved print…) isn't imported; the +/// album lands at the top level, and the report says why it isn't where Lightroom had it. +#[test] +fn a_collection_whose_parent_is_missing_or_system_only_lands_at_the_top_level_with_a_warning() { + let mut s = crate::Session::new(); + let mut data = sample(); + data.collections.push(row(json!({"id_local":11,"parent":99,"name":"Orphan","creationId":"com.adobe.ag.library.collection"}))); + data.collections.push(row(json!({"id_local":5,"name":"quick collection","creationId":"com.adobe.ag.library.collection","systemOnly":1}))); + data.collections.push(row(json!({"id_local":12,"parent":5,"name":"Stray","creationId":"com.adobe.ag.print"}))); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(r["collections"], 4); + assert_eq!(album_named(&s, "Orphan").parent, None); + assert_eq!(album_named(&s, "Stray").parent, None); + assert!(s.catalog.albums().all(|a| a.name != "quick collection")); + let w = warnings_naming(&r, "Orphan"); + assert!(w.len() == 1 && w[0].contains("isn't in the catalog"), "{w:?}"); + let w = warnings_naming(&r, "Stray"); + assert!(w.len() == 1 && w[0].contains("quick collection") && w[0].contains("at the top level"), "{w:?}"); + assert_eq!(album_named(&s, "Keepers").parent, Some(album_named(&s, "Travel").id)); +} +/// Imports `data` keeping `index` between imports, as a library on disk does. +fn import_indexed(s: &mut crate::Session, data: CatalogImport, index: &mut ImportIndex) -> crate::Result { + let undo0 = s.undo.len(); + let missing_sources = HashSet::new(); + let context = + ApplyPrepared { update_existing: false, files: Default::default(), index, archive_path: None, missing_sources: &missing_sources, undo0 }; + apply_prepared(s, data, context).map(|applied| applied.report) +} +/// The sample with “Picks”, a collection Lightroom keeps inside the plain collection “Keepers”. +fn with_picks() -> CatalogImport { + let mut data = sample(); + data.collections.push(row(json!({"id_local":11,"parent":10,"name":"Picks","creationId":"com.adobe.ag.library.collection"}))); + data.members.push(row(json!({"collection":11,"image":1,"positionInCollection":"a"}))); + data +} +/// Importing the catalog again finds the moved album where the first import put it, adds nothing twice and doesn't +/// warn again: the album is already in the library. +#[test] +fn a_relocated_collection_keeps_its_place_on_reimport_without_duplicates_or_a_second_warning() { + let mut s = crate::Session::new(); + let mut index = ImportIndex::default(); + let first = import_indexed(&mut s, with_picks(), &mut index).unwrap(); + assert_eq!(warnings_naming(&first, "Picks").len(), 1); + let second = import_indexed(&mut s, with_picks(), &mut index).unwrap(); + assert_eq!(second["collections"], 3); + assert_eq!(s.catalog.albums().count(), 3); + assert_eq!(album_named(&s, "Picks").parent, Some(album_named(&s, "Travel").id)); + assert_eq!(album_named(&s, "Picks").photos.len(), 1); + assert_eq!(album_named(&s, "Keepers").photos.len(), 2); + assert!(warnings_naming(&second, "Picks").is_empty(), "{second}"); +} +/// Albums the user moved after an import stay where the user put them when the catalog is imported again. +#[test] +fn an_album_the_user_moved_keeps_its_place_on_reimport() { + let mut s = crate::Session::new(); + let mut index = ImportIndex::default(); + import_indexed(&mut s, with_picks(), &mut index).unwrap(); + for name in ["Picks", "Keepers"] { + let id = album_named(&s, name).id; + s.commit("Move Album", Op::MoveAlbum { id, parent: None }).unwrap(); + } + let r = import_indexed(&mut s, with_picks(), &mut index).unwrap(); + assert_eq!(s.catalog.albums().count(), 3); + assert_eq!(album_named(&s, "Picks").parent, None); + assert_eq!(album_named(&s, "Keepers").parent, None); + assert!(warnings_naming(&r, "Picks").is_empty() && warnings_naming(&r, "Keepers").is_empty(), "{r}"); +} +/// A collection new since the last import goes into the set's album, and the warning names that album as the +/// library calls it now, not by its Lightroom name. +#[test] +fn a_relocation_warning_names_the_set_as_the_user_renamed_it() { + let mut s = crate::Session::new(); + let mut index = ImportIndex::default(); + import_indexed(&mut s, sample(), &mut index).unwrap(); + let travel = album_named(&s, "Travel").id; + s.commit("Rename Album", Op::RenameAlbum { id: travel, name: "Trips".into() }).unwrap(); + let r = import_indexed(&mut s, with_picks(), &mut index).unwrap(); + assert_eq!(album_named(&s, "Picks").parent, Some(travel)); + let w = warnings_naming(&r, "Picks"); + assert!(w.len() == 1 && w[0].contains("inside “Keepers”") && w[0].ends_with("imported into “Trips” (Lightroom collection 11)"), "{w:?}"); +} +/// The album an earlier import made for a Lightroom set may no longer be a folder (here: an index that names a plain +/// album). A collection in that set lands at the top level, and the warning says why without calling the set +/// something it isn't. +#[test] +fn a_set_whose_album_is_not_a_folder_puts_its_collections_at_the_top_level() { + let mut s = crate::Session::new(); + let plain = s.catalog.alloc_album_id(); + s.commit("New Album", Op::AddAlbum { album: Album::new(plain, "Travel picks") }).unwrap(); + let mut index = ImportIndex::default(); + index.collections.insert(format!("{}:9", key("test.lrcat")), plain.0); + let r = import_indexed(&mut s, sample(), &mut index).unwrap(); + assert_eq!(s.catalog.albums().count(), 2); + assert!(!s.catalog.album(plain).unwrap().folder); + let keepers = album_named(&s, "Keepers"); + assert_eq!((keepers.parent, keepers.photos.len()), (None, 2)); + let w = warnings_naming(&r, "Keepers"); + assert_eq!(w.len(), 1, "{w:?}"); + assert!(w[0].contains("“Travel” is the album “Travel picks”") && w[0].contains("isn't a folder"), "{w:?}"); + assert!(!w[0].contains("isn't a collection set") && w[0].ends_with("at the top level (Lightroom collection 10)"), "{w:?}"); +} +/// Only the outermost set inside a plain collection moves; the sets and creations inside it keep their places. +#[test] +fn sets_nested_under_a_plain_collection_keep_their_own_nesting() { + let mut s = crate::Session::new(); + let mut data = sample(); + data.collections.push(row(json!({"id_local":12,"name":"Loose","creationId":"com.adobe.ag.library.collection"}))); + data.collections.push(row(json!({"id_local":13,"parent":12,"name":"Outer","creationId":"com.adobe.ag.library.group"}))); + data.collections.push(row(json!({"id_local":14,"parent":13,"name":"Inner","creationId":"com.adobe.ag.library.group"}))); + data.collections.push(row(json!({"id_local":15,"parent":14,"name":"Poster","creationId":"com.adobe.ag.print"}))); + data.members.push(row(json!({"collection":15,"image":1,"positionInCollection":"a"}))); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(r["collections"], 6); + let outer = album_named(&s, "Outer"); + assert_eq!((outer.parent, outer.folder), (None, true)); + let inner = album_named(&s, "Inner"); + assert_eq!((inner.parent, inner.folder), (Some(outer.id), true)); + assert_eq!(album_named(&s, "Poster").parent, Some(inner.id)); + assert_eq!(album_named(&s, "Poster").photos.len(), 1); + let w = warnings_naming(&r, "Outer"); + assert!(w.len() == 1 && w[0].contains("inside “Loose”") && w[0].ends_with("at the top level (Lightroom collection 13)"), "{w:?}"); + assert!(warnings_naming(&r, "Inner").is_empty() && warnings_naming(&r, "Poster").is_empty(), "{r}"); +} +/// The album counter saturates: one at its end hands every collection the same id. The second collection used to be +/// dropped without a word while the report counted it; the import now stops and names it. +#[test] +fn an_exhausted_album_counter_stops_the_import_naming_the_collection() { + let mut s = crate::Session::new(); + s.commit("New Album", Op::AddAlbum { album: Album::new(lightcraft_catalog::AlbumId(u64::MAX - 1), "Last") }).unwrap(); + let err = apply(&mut s, sample(), false).unwrap_err().to_string(); + assert!(err.contains("“Keepers”") && err.contains("no unused album id"), "{err}"); + assert_eq!(s.catalog.albums().count(), 1); + assert!(s.catalog.is_empty()); +} +/// A collection listed twice imports once. A different collection under the same Lightroom id used to stop the import; +/// like any bad record it now costs only itself (#1588): it is left out with a warning naming both, and its photos go +/// to the first. +#[test] +fn a_collection_listed_twice_imports_once_and_a_conflicting_one_is_skipped_with_a_warning() { + let mut s = crate::Session::new(); + let mut data = sample(); + data.collections.push(data.collections[1].clone()); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(r["collections"], 2); + assert_eq!(s.catalog.albums().filter(|a| a.name == "Keepers").count(), 1); + assert_eq!(album_named(&s, "Keepers").photos.len(), 2); + assert_eq!(r["warnings"], json!([]), "an exact repeat drops quietly"); + + let mut s = crate::Session::new(); + let mut data = sample(); + // shallower than the first, so a depth-ordered pass would meet it first + data.collections.push(row(json!({"id_local":10,"parent":0,"name":"Rejects","creationId":"collection"}))); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(r["photos"], 2, "{r}"); + assert_eq!(r["collections"], 2, "{r}"); + assert!(s.catalog.albums().all(|a| a.name != "Rejects")); + let keepers = album_named(&s, "Keepers"); + assert_eq!(keepers.photos.len(), 2); + assert!(keepers.parent.is_some(), "the first row's place is kept"); + assert_eq!( + r["warnings"], + json!(["collection “Rejects”: not imported, it has the id of collection “Keepers”; the photos listed under that id go to “Keepers”"]) + ); + assert_eq!(s.undo.len(), 1); +} +/// The search for the nearest set ends on a parent loop that got past `validate` (A in B in A, a collection in +/// itself) and on a chain of plain collections deeper than 64: the album goes to the top level, flagged as moved. +#[test] +fn the_nearest_set_search_ends_on_a_parent_loop_or_a_deep_chain() { + let plain = |id: i64, parent: i64| row(json!({"id_local":id,"parent":parent,"name":format!("C{id}"),"creationId":"collection"})); + let (a, b, own) = (plain(1, 2), plain(2, 1), plain(3, 3)); + let child = plain(4, 1); + let collections: HashMap = [(1, &a), (2, &b), (3, &own), (4, &child)].into_iter().collect(); + let no_sets = HashSet::new(); + for c in [&a, &b, &own, &child] { + assert_eq!(collection_parent(c, &collections, &no_sets), (None, true), "{c:?}"); + } + // a set in the loop is still found + assert_eq!(collection_parent(&child, &collections, &HashSet::from([2])), (Some(2), true)); + let chain: Vec = (100..200).map(|id| plain(id, if id == 100 { 0 } else { id - 1 })).collect(); + let collections: HashMap = chain.iter().map(|r| (number(r, "id_local"), r)).collect(); + assert_eq!(collection_parent(&chain[99], &collections, &no_sets), (None, true)); +} +/// A damaged index that names one existing album for two collections gives the second an album of its own rather +/// than merging its photos into the first's. +#[test] +fn an_index_naming_one_album_for_two_collections_gives_the_second_its_own() { + let mut s = crate::Session::new(); + let old = s.catalog.alloc_album_id(); + s.commit("New Album", Op::AddAlbum { album: Album::new(old, "Old") }).unwrap(); + let mut index = ImportIndex::default(); + for lr in [10, 11] { + index.collections.insert(format!("{}:{lr}", key("test.lrcat")), old.0); + } + let r = import_indexed(&mut s, with_picks(), &mut index).unwrap(); + assert_eq!(r["collections"], 3); + assert_eq!(s.catalog.album(old).unwrap().photos.len(), 2, "Keepers merges into the album the index names"); + let picks = album_named(&s, "Picks"); + assert_ne!(picks.id, old); + assert_eq!(picks.photos.len(), 1); +} #[test] fn preserves_existing_edits_and_rejects_invalid_structure_before_mutation() { let mut s = crate::Session::new(); diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index e4da7c209f..80169dc859 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -110,7 +110,14 @@ fields are reported. Lightroom's `ProcessVersion` is not mapped: newly imported LightCraft's latest rendering process, and photos already in the library keep theirs ([process-versions.md](process-versions.md)). When a recovery archive is saved, it retains source settings/history/snapshots and original smart-collection rules. Smart collections become regular albums with current -membership. Archived history and snapshots are source data, not native LightCraft history yet. +membership, and so do saved prints, books, slideshows and web galleries (with the photos they hold). A LightCraft +album nests only inside a folder (a Lightroom collection set). A collection or creation Lightroom keeps elsewhere, +such as a print saved inside a plain collection, or one whose parent is system-only or gone from the catalog, joins the +nearest collection set above it, or the top level, and the result names it under warnings (issues #2165, #2532). +Quick Collection and unsaved creations are system-only and not imported; publish collections live in tables the +importer doesn't read. A collection the catalog lists twice imports once; a different collection with the id of an +earlier one is left out with a warning naming both, and the photos listed under that id go to the first. Archived +history and snapshots are source data, not native LightCraft history yet. A Custom white balance on a raw LightCraft develops relative to its as-shot look (ARW, NEF, RW2, RAF, CR3, CR2, PEF, SRW; Lightroom names them all `RAW`) can't be taken as Kelvin: the catalog keeps no as-shot white for Custom photos, so the photo stays As Shot and `Temperature, Tint` are reported diff --git a/docs/whats-new.md b/docs/whats-new.md index 113da1c74c..cc371e0dfc 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -51,6 +51,13 @@ ## 2026-10-30 +### Lightroom catalogs with a print inside a collection import their collections +- Lightroom Classic can keep a saved print, book, slideshow or web gallery inside a plain collection, but a + LightCraft album sits only inside a folder. Importing such a catalog stopped at the end with "parent must be an + existing folder" and brought over no collections, and photos whose originals were offline were lost with them + (issues #2165, #2532). Such a collection now joins the nearest collection set above it, or the top level, and the + import result names it under warnings; so does one whose parent is system-only or gone from the catalog. + ### Lens distortion correction for the Sony A7 III - Raws from the Sony A7 III (ILCE-7M3) now get the camera's own distortion correction, read from the file, like the A7R IVA's: straight lines stay straight at wide angles (the FE 16–35 F4 ZA at 16 mm shifts detail near the From baf079f659c4df026b31ffbbf5a8a5bf380b332c Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Thu, 5 Nov 2026 20:50:13 +0100 Subject: [PATCH 06/24] LR-BEHAV-RENDER-FIDELITY: process V5 rolls raw tone curves off into white in stops, so raising Exposure keeps highlights (#1632) (#3783) * LR-BEHAV-RENDER-FIDELITY: V3 camera tone curve rolls off in stops past its last knot (#1632) A raw's camera tone curve is fitted only to camera JPEG tones below 0.85, so its last knot sits 1 to 3 stops below the sensor's white. Past it, CameraTone::apply closes on white exponentially in linear light: the sensor's white renders at 8-bit 246-254 at Exposure 0 and 254-255 from +1, and raising Exposure turns the top stop the sensor recorded white. Process V3 extends the curve with CameraTone::apply_rolloff: same value and slope at the knot, then gap / (1 + c (2^t - 1)) at t stops past it, the gap halving every stop in the end. On 11 CC0 corpus files with a fitted look, unclipped pixels rendering white drop from up to 22.5% to 0 at +1 EV and from up to 35% to 0 at +2 EV; Exposure 0 renders change by at most 1 code on average. V1 and V2, the fit itself, JPEGs and raws without a fitted look are unchanged. Co-Authored-By: Claude Opus 5.5 * LR-BEHAV-RENDER-FIDELITY: V3 generic raw curve rolls off in stops too; DRO-off, DNG and GPU checks (#1632) Raws without a camera curve take ToneMap::hdr, which reached white about 1/4 stop past the sensor's white and clipped there (o.min(1.0)). Process V3 now uses ToneMap::rolloff_hdr: from half a stop below the white point (tone::GENERIC_KNEE_STOPS) the extended Reinhard curve hands over to the same stop-based shoulder as the camera curve (tone::rolloff_past, shared with CameraTone::apply_rolloff), with the same value and slope at the join. The sensor's white renders at about 235 / 248 / 252 at Exposure 0 / +1 / +2 where V1 and V2 render 239 / 255 / 255. On 6 CC0 DNGs on the generic curve, unclipped pixels rendering white drop from up to 8.4% to 0 at +1 EV and from up to 17.2% to 0 at +2 EV. The DRO-off gate (look_fit::at_most) also checks the V3 shoulder; the rate bound already implies it, so no fit changes and LOOK_VERSION stays. Tests: the generic shoulder (join, slope, monotone, below white, no kink), a regression test that fails with the clipping curve, a DNG ProfileToneCurve under V3, the DRO-off property tests on the V3 shoulder, and a per-process camera-curve GPU check. Docs: process-versions, parity checklist (LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS), gap 3. Co-Authored-By: Claude Opus 5.5 * LR-BEHAV-RENDER-FIDELITY: what's new: process 3 keeps raw highlights when Exposure is raised (#1632) Co-Authored-By: Claude Opus 5.5 * LR-BEHAV-RENDER-FIDELITY: a flat last camera-curve segment joins the V3 shoulder with its own slope (#1632) The V3 camera shoulder took the last segment's slope with a floor of 0.1, so a flat or shallow segment (valid for a fitted, DNG or saved curve) joined with a kink: slope 0 on the curve, about 0.1 just past it. The shoulder now keeps the segment's own slope at the knot. Below 0.1 a quadratic term in 2^t - 1 joins the denominator: it adds no slope at the knot and makes up the 0.1 pace further up, so a flat curve still closes on white. Segments at 0.1 or steeper are byte-identical, and the generic curve passes no floor. Comments now say the shoulder approaches white in real numbers and can round to it in f32. Found in an independent review of the branch. Co-Authored-By: Claude Opus 5.5 * LR-BEHAV-RENDER-FIDELITY: V4's GPU test pins V4; the corpus DRO photos keep their knots under the V5 bound (#1632) The GPU light-operator test assumed the default process is V4; it now sets V4, since V5 is the default. The corpus DRO test checks that dro_off's V5 bound leaves the second-last knot where the rate bound puts it on the Sony DRO samples, so their V1 to V4 renders don't change. Co-Authored-By: Claude Opus 5.5 * LR-BEHAV-RENDER-FIDELITY: the DRO-off curve is main's again, so V1 to V4 keep it (#1632) CodeRabbit found that the V5 bound in `dro_off` could move the second-last knot of a DRO photo whose fitted last segment is flat, and V1 to V4 read that curve too. `dro_off` and `at_most` are back to main's, so the camera-look fit is unchanged and LOOK_VERSION stays. The DRO tests check the V5 shoulder where the lowered segment's slope over its squared gap is at most the fitted one's (then it stays below), and on the Sony DRO corpus samples. Also: `rolloff_hdr`'s doc names the HDR lift, and the release note names DNGs whose curve already reaches white. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/develop/src/settings.rs | 8 +- crates/engine/src/camera_preview/look_fit.rs | 7 +- crates/engine/src/camera_preview/tests.rs | 26 ++ crates/engine/src/files/tests.rs | 32 +++ crates/gpu/tests/it/equivalence.rs | 11 +- crates/pipeline/src/finish.rs | 7 + crates/pipeline/src/light_v3.rs | 4 +- crates/pipeline/src/local.rs | 2 +- crates/pipeline/src/tests_light.rs | 2 +- crates/pipeline/src/tests_tone.rs | 64 +++++ crates/pipeline/src/tone.rs | 237 ++++++++++++++++++- docs/gaps.md | 3 +- docs/parity-checklist.md | 5 +- docs/process-versions.md | 4 +- docs/whats-new.md | 10 + 15 files changed, 404 insertions(+), 18 deletions(-) diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 82de362e5f..55b851b3c2 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -90,12 +90,15 @@ pub enum Process { /// camera curve keeps V2 Whites and fitted pointwise operators follow it /// (`lightcraft_pipeline::light_v3`, `docs/light-v3.md`). V4, + /// V4, with a raw's tone curve rolling off into white in stops past its last fitted knot, so + /// highlights the sensor recorded keep their detail when Exposure lifts them (issue #1632). + V5, } impl Process { /// Every process, oldest first. - pub const ALL: [Process; 4] = [Process::V1, Process::V2, Process::V3, Process::V4]; - pub const LATEST: Process = Process::V4; + pub const ALL: [Process; 5] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5]; + pub const LATEST: Process = Process::V5; pub const fn version(self) -> ProcessVersion { match self { @@ -103,6 +106,7 @@ impl Process { Process::V2 => ProcessVersion(2), Process::V3 => ProcessVersion(3), Process::V4 => ProcessVersion(4), + Process::V5 => ProcessVersion(5), } } } diff --git a/crates/engine/src/camera_preview/look_fit.rs b/crates/engine/src/camera_preview/look_fit.rs index d93cbffe9a..fac4e2df40 100644 --- a/crates/engine/src/camera_preview/look_fit.rs +++ b/crates/engine/src/camera_preview/look_fit.rs @@ -169,7 +169,12 @@ pub(super) fn dro_off(own_tone: &CameraTone) -> CameraTone { // Past its last knot a curve goes on as a shoulder whose rate comes from its last two knots // (`CameraTone::apply`): lowering the second-last knot more than the last steepens it, and the // extended highlights would end up above the fitted curve. Raise the second-last knot (never - // above the fitted curve) until the rate is at most the fitted curve's. + // above the fitted curve) until the rate is at most the fitted curve's. Process V5's shoulder + // (`CameraTone::apply_rolloff`) is not part of this bound or of `at_most`: V1 to V4 read the + // same curve, and a V5 bound here would change their renders. It stays below the fitted + // curve's too when the last segment's slope over the squared gap to white is at most the fitted + // curve's; a lowered curve with a nearly flat last segment can end up above it far past the last + // knot under V5 (issue #1632). let ([a, b], last) = ([own[30], own[31]], knots[31]); let rate = ((b[1] - a[1]) / (b[0] - a[0])).clamp(0.1, 16.0) / (1.0 - b[1]).max(0.01); let floor = last[1] - rate * (1.0 - last[1]).max(0.01) * (b[0] - a[0]); diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index d8673da4ec..733b576f6f 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -1285,6 +1285,30 @@ fn assert_lowered(fitted: &CameraLook, fixed: &CameraLook, what: &str) { let x = 0.001 * 1.005f32.powi(i); assert!(fixed.tone.apply(x) <= fitted.tone.apply(x) + 1e-5, "{what} at {x}: {} > {}", fixed.tone.apply(x), fitted.tone.apply(x)); } + // V5's shoulder stays below too whenever the lowered last segment's slope over its squared gap to + // white is at most the fitted one's (`dro_off` doesn't enforce it, so V1 to V4 keep their curve; + // issue #1632) + if v5_bounded(&fixed.tone, &fitted.tone) { + assert!(v5_below(&fixed.tone, &fitted.tone), "{what}: brighter than the fitted curve under V5"); + } +} + +/// Whether the last segment of `a`, over its squared gap to white, is at most `b`'s: then `a`'s V5 +/// shoulder ([`CameraTone::apply_rolloff`]) is nowhere above `b`'s (issue #1632). +fn v5_bounded(a: &CameraTone, b: &CameraTone) -> bool { + let rate = |t: &CameraTone| { + let k = t.knots(); + ((k[31][1] - k[30][1]) / (k[31][0] - k[30][0])).max(0.0) / (1.0 - k[31][1]).powi(2) + }; + rate(a) <= rate(b) +} + +/// Whether `a`'s V5 curve is nowhere brighter than `b`'s, from deep shadows to far past the last knot. +fn v5_below(a: &CameraTone, b: &CameraTone) -> bool { + (0..=2400).all(|i| { + let x = 0.001 * 1.005f32.powi(i); + a.apply_rolloff(x) <= b.apply_rolloff(x) + 1e-5 + }) } /// Issue #244: Sony's Dynamic Range Optimizer lifts the camera JPEG's shadows, not the raw's. A @@ -1423,6 +1447,8 @@ fn corpus_arw_with_dro_is_lowered_to_the_dro_off_tone() { let fitted = fit_look(&sensor, &reference, &clipped, colour).unwrap(); if dro { assert_lowered(&fitted, &look, name); + // the Sony DRO samples' lowered curves stay below their fitted ones under V5 as well + assert!(v5_below(&look.tone, &fitted.tone), "{name}: brighter than the fitted curve under V5"); for x in lowered { assert!(look.tone.apply(x) < 0.95 * fitted.tone.apply(x), "{name} at {x}: {} vs {}", look.tone.apply(x), fitted.tone.apply(x)); } diff --git a/crates/engine/src/files/tests.rs b/crates/engine/src/files/tests.rs index e8eabc72db..599d173f7d 100644 --- a/crates/engine/src/files/tests.rs +++ b/crates/engine/src/files/tests.rs @@ -1844,3 +1844,35 @@ fn existing_photo_settings_are_not_rewritten() { drop(s); let _ = std::fs::remove_dir_all(&dir); } + +/// Issue #1632: a DNG's `ProfileToneCurve` is the finish stage's camera curve, so process V5 extends +/// it past its last point (the sensor's white, scene 1.0) with the stop roll-off as well. A curve +/// that reaches white there renders as under V4 up to it and white past it; one that ends below +/// white (here 0.9) keeps what Exposure lifts past the sensor's white apart instead of reaching +/// 8-bit 255 within a stop. +#[test] +fn v5_extends_a_dng_tone_curve_past_white_in_stops() { + use lightcraft_color::transfer::linear_to_srgb; + use lightcraft_develop::{DevelopSettings, Process}; + use lightcraft_pipeline::SourceInfo; + let code = |curve: &[f64], process: Process, y: f32| { + let tone = lightcraft_raw::profile::ToneCurve::from_tag(curve).and_then(|c| super::dng_tone_curve(&c)); + let info = SourceInfo { raw: true, camera_tone: Some(tone.expect("a valid curve")), ..SourceInfo::default() }; + let s = DevelopSettings { process: process.version(), ..DevelopSettings::default() }; + let o = lightcraft_pipeline::finish::base_tone(&s, &info, 1.0).apply(y); + (linear_to_srgb(o.clamp(0.0, 1.0)) * 255.0).round() + }; + let to_white = [0.0, 0.0, 0.03, 0.09, 0.18, 0.4, 0.5, 0.78, 1.0, 1.0]; + for y in [0.01, 0.05, 0.18, 0.5, 0.9] { + assert_eq!(code(&to_white, Process::V5, y), code(&to_white, Process::V4, y), "{y}"); + } + for y in [1.0, 2.0, 4.0] { + assert_eq!((code(&to_white, Process::V4, y), code(&to_white, Process::V5, y)), (255.0, 255.0), "{y}"); + } + let below_white = [0.0, 0.0, 0.03, 0.09, 0.18, 0.4, 0.5, 0.72, 1.0, 0.9]; + let at = |process, ev: f32| code(&below_white, process, ev.exp2()); + assert_eq!(at(Process::V5, 0.0), at(Process::V4, 0.0)); + assert_eq!(at(Process::V4, 1.0), 255.0, "V4 is frozen"); + let (white, beyond) = (at(Process::V5, 0.0), at(Process::V5, 1.0)); + assert!(beyond < 254.0 && beyond - white >= 3.0, "{white} then {beyond} a stop past the sensor's white"); +} diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index a85f96177b..24359dbe8e 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -92,6 +92,12 @@ fn camera_tone_and_relative_wb() { s.wb.mode = WbMode::Custom; s.wb.temp = 8000.0; check("camera tone edited", &src, &info, &s, &RenderRequest::fit(320, 240)); + // each process's shoulder past the last knot, with highlights lifted into it (issue #1632) + for p in Process::ALL { + let mut lifted = DevelopSettings { process: p.version(), ..DevelopSettings::default() }; + lifted.light.exposure = 2.0; + check(&format!("camera tone {p:?} exposure +2"), &src, &info, &lifted, &RenderRequest::fit(320, 240)); + } // a camera chroma curve: richer shadows, highlights bleached toward white let curve = curve.with_chroma([1.4, 1.3, 1.1, 1.0, 0.7, 0.4, 0.25, 0.2]).unwrap(); let info = SourceInfo { camera_tone: Some(curve), ..info }; @@ -709,8 +715,7 @@ fn light_v3_operators_match() { let req = RenderRequest::fit(720, 720); for id in ["light.contrast", "light.whites", "light.blacks"] { for v in [-100.0, -50.0, 50.0, 100.0] { - let mut s = DevelopSettings::default(); - assert_eq!(s.process.process(), Process::V4); + let mut s = DevelopSettings { process: Process::V4.version(), ..Default::default() }; lightcraft_develop::controls::set(&mut s, id, v); check(&format!("V4 {id} {v}"), &src, &info, &s, &req); if id == "light.whites" { @@ -723,7 +728,7 @@ fn light_v3_operators_match() { } } } - let mut s = DevelopSettings::default(); + let mut s = DevelopSettings { process: Process::V4.version(), ..Default::default() }; typical(&mut s); s.light.contrast = 35.0; s.light.whites = 40.0; diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 5a9c51b8cf..6feec0b333 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -347,6 +347,13 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { None if info.raw => ToneMap::hdr(l.contrast, l.whites, l.blacks, peak), None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), }, + // V4, with a raw's tone curve rolling off into white in stops: a camera curve past its last + // knot, the generic curve from half a stop below its white point instead of clipping (issue #1632) + Process::V5 => match info.camera_tone.as_ref().filter(|_| info.raw) { + Some(curve) => ToneMap::camera_rolloff_hdr(curve, 0.0, l.whites, 0.0, peak), + None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak), + None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), + }, } } diff --git a/crates/pipeline/src/light_v3.rs b/crates/pipeline/src/light_v3.rs index 43f836101a..03c651c79a 100644 --- a/crates/pipeline/src/light_v3.rs +++ b/crates/pipeline/src/light_v3.rs @@ -278,13 +278,13 @@ pub struct LightOps { /// The fits of Contrast and Blacks, in the order they apply. pub const FITS: [&Fit; 2] = [&fitted::CONTRAST, &fitted::BLACKS]; -/// Whether `s` renders `info` with the V4 operators: process V4 and a raw with its camera's tone +/// Whether `s` renders `info` with the V4 operators: process V4 or later and a raw with its camera's tone /// curve (other sources keep the tone map's own Contrast and Blacks). pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool { let camera_look = info.raw && info.camera_tone.is_some(); match s.process.process() { Process::V1 | Process::V2 | Process::V3 => false, - Process::V4 => camera_look, + Process::V4 | Process::V5 => camera_look, } } diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index 22c17571f9..96177fe3fe 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -375,7 +375,7 @@ pub fn base_detail_radius(px_per_long: f64) -> usize { pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { match s.process.process() { Process::V1 => 0, - Process::V2 | Process::V3 | Process::V4 => base_detail_radius(px_per_long), + Process::V2 | Process::V3 | Process::V4 | Process::V5 => base_detail_radius(px_per_long), } } diff --git a/crates/pipeline/src/tests_light.rs b/crates/pipeline/src/tests_light.rs index c6ea984c49..6e9cc9f128 100644 --- a/crates/pipeline/src/tests_light.rs +++ b/crates/pipeline/src/tests_light.rs @@ -296,7 +296,7 @@ fn v3_sliders_move_a_grey_ramp_their_way() { let ramp = Rgb32f::from_fn(256, 8, |x, _| [0.0005 * 1.035f32.powi(x as i32); 3]); let shot = |id: &str, v: f64| { let mut s = DevelopSettings::default(); - assert_eq!(s.process.process(), Process::V4); + assert!(s.process.process() >= Process::V4, "the default process has the V4 sliders"); controls::set(&mut s, id, v); let r = render(&ramp, &camera_look(), &s, &RenderRequest::fit(256, 8)).image; (0..256).map(|x| r.get(x, 4)).collect::>() diff --git a/crates/pipeline/src/tests_tone.rs b/crates/pipeline/src/tests_tone.rs index adfda3fc0d..f76f44775f 100644 --- a/crates/pipeline/src/tests_tone.rs +++ b/crates/pipeline/src/tests_tone.rs @@ -264,3 +264,67 @@ fn the_base_plane_is_cached_per_process() { assert_ne!(local::base_key(&s1, sg, 0), local::base_key(&s2, sg, 0), "the process is part of the key"); assert_ne!(local::base_key(&s2, sg, 0), local::base_key(&s2, sg, sig.base_detail)); } + +/// Issue #1632: past its last fitted knot (here 1.0 stop below the sensor's white, scene 1.0, at +/// 8-bit 233, as on the CC0 ILCE-7CR file) a raw's camera tone curve closed on white exponentially +/// in linear light, so Exposure +1 rendered the sensor's white at 255 and Exposure +2 left the top +/// stop it recorded (scene 0.5..1.0) under one 8-bit code. The latest process rolls off in stops +/// and keeps both apart; V1 to V4 keep their look. +#[test] +fn exposure_keeps_the_highlights_a_camera_curve_recorded() { + use lightcraft_color::transfer::linear_to_srgb; + let knots = std::array::from_fn(|i| { + let x = 0.003 * 1.18f32.powi(i as i32); + [x, 1.0 - (-3.3 * x).exp()] + }); + let info = SourceInfo { raw: true, camera_tone: crate::tone::CameraTone::new(knots), ..SourceInfo::default() }; + let at = |process: Process, ev: f32, y: f32| { + let o = crate::finish::base_tone(&on(process), &info, 1.0).apply(y * ev.exp2()); + (linear_to_srgb(o.clamp(0.0, 1.0)) * 255.0).round() + }; + for ev in [0.0, 1.0, 2.0] { + let (white, half) = (at(Process::LATEST, ev, 1.0), at(Process::LATEST, ev, 0.5)); + assert!(white <= 254.0, "Exposure {ev:+}: the sensor's white renders at {white}"); + assert!(white - half >= 1.5, "Exposure {ev:+}: the top stop spans {half}..{white}"); + } + // the earlier processes are frozen: the sensor's white at 255 from Exposure +1 + for p in [Process::V1, Process::V2, Process::V3, Process::V4] { + assert_eq!(at(p, 1.0, 1.0), 255.0, "{p:?}"); + } + // up to the last knot every process renders the camera's curve + for y in [0.003, 0.02, 0.18, 0.4, 0.5] { + let (v2, v3) = (crate::finish::base_tone(&on(Process::V2), &info, 1.0), crate::finish::base_tone(&on(Process::LATEST), &info, 1.0)); + assert!((v2.apply(y) - v3.apply(y)).abs() < 1e-6, "{y}"); + } +} + +/// Issue #1632: a raw without a camera curve takes the generic curve, which reached white about ¼ +/// stop past the sensor's white (scene 1.0) and clipped there, so Exposure +1 rendered the top stop +/// the sensor recorded (scene 0.5..1.0) at 8-bit 255 from its upper half. The latest process rolls +/// off in stops from half a stop below the white point; V1 to V4 keep their look. +#[test] +fn exposure_keeps_the_highlights_the_generic_curve_recorded() { + use lightcraft_color::transfer::linear_to_srgb; + let info = SourceInfo { raw: true, ..SourceInfo::default() }; + let at = |process: Process, ev: f32, y: f32| { + let o = crate::finish::base_tone(&on(process), &info, 1.0).apply(y * ev.exp2()); + (linear_to_srgb(o.clamp(0.0, 1.0)) * 255.0).round() + }; + for ev in [0.0, 1.0, 2.0] { + let (white, half) = (at(Process::LATEST, ev, 1.0), at(Process::LATEST, ev, 0.5)); + assert!(white <= 253.0, "Exposure {ev:+}: the sensor's white renders at {white}"); + assert!(white - half >= 3.0, "Exposure {ev:+}: the top stop spans {half}..{white}"); + } + // the curve still reaches white, 5 stops past the sensor's + assert_eq!(at(Process::LATEST, 5.0, 1.0), 255.0); + // the earlier processes are frozen: the sensor's white at 255 from Exposure +1 + for p in [Process::V1, Process::V2, Process::V3, Process::V4] { + assert_eq!(at(p, 1.0, 1.0), 255.0, "{p:?}"); + } + assert_eq!(at(Process::V2, 0.0, 1.0), at(Process::V1, 0.0, 1.0)); + // below the knee every process renders the same curve + let (v2, v3) = (crate::finish::base_tone(&on(Process::V2), &info, 1.0), crate::finish::base_tone(&on(Process::LATEST), &info, 1.0)); + for y in [0.003, 0.02, 0.18, 0.4, 0.6] { + assert_eq!(v2.apply(y), v3.apply(y), "{y}"); + } +} diff --git a/crates/pipeline/src/tone.rs b/crates/pipeline/src/tone.rs index a248ada592..0ff62fce4f 100644 --- a/crates/pipeline/src/tone.rs +++ b/crates/pipeline/src/tone.rs @@ -90,8 +90,88 @@ impl CameraTone { let slope = ((b[1] - a[1]) / (b[0] - a[0])).clamp(0.1, 16.0); 1.0 - (1.0 - b[1]) * (-(y - b[0]) * slope / (1.0 - b[1]).max(0.01)).exp() } + + /// [`CameraTone::apply`] as process V5 extends it past the last knot (issue #1632). The curve is + /// fitted only to camera JPEG tones below 0.85, so its last knot lies 1 to 3 stops below the + /// sensor's white on most photos and everything above it is extrapolated. [`CameraTone::apply`] + /// closes the gap to white exponentially in linear light: it reaches 8-bit 255 within about a + /// stop past the sensor's white, and Exposure +1 turns the top stop the sensor recorded white. + /// Here the gap shrinks in stops instead, `gap / (1 + c·(2^(k·t) − 1))` at `t` stops past the + /// knot, with `c` matching the curve's slope there (so the join is smooth) and the gap halving + /// every [`ROLLOFF_STOPS`] stops in the end. Same value as [`CameraTone::apply`] up to the last + /// knot, monotone, finite and at most 1. In real numbers it only approaches white; in `f32` the + /// gap can round to 0 far up, and within a stop or two for a last knot a few ulps below white. + pub fn apply_rolloff(&self, y: f32) -> f32 { + let (a, b) = (self.knots[30], self.knots[31]); + if !y.is_finite() || y <= b[0] { + return self.apply(y); + } + // the last segment's own slope, so the join is smooth even when it is flat (`new` keeps the + // knots non-decreasing, so it is at least 0) + let slope = ((b[1] - a[1]) / (b[0] - a[0])).max(0.0); + // `CameraTone::new` keeps the last knot below 1, so the gap is positive (no floor: one + // would step the curve down past a knot within it of white) + rolloff_past(y, b, slope, CAMERA_MIN_SLOPE) + } } +/// The pace [`CameraTone::apply_rolloff`] closes on white at least at, as display per unit of scene +/// luminance at the last knot (the floor [`CameraTone::apply`] puts on its slope there). A last +/// segment flatter than this still joins with its own slope; [`rolloff_past`] then adds a term that +/// has no slope at the knot and reaches this pace further up, so a flat curve does not stay below +/// white. +const CAMERA_MIN_SLOPE: f32 = 0.1; + +/// Stops in which the gap between a V5 curve and white halves, far past where its shoulder starts +/// ([`CameraTone::apply_rolloff`], [`ToneMap::rolloff_hdr`]). With 1, the sensor's white renders at +/// 8-bit 239–250 on the CC0 corpus files with a camera curve (Sony, Nikon, Fujifilm) at Exposure 0 +/// and below 254 up to Exposure +2, where the extension of [`CameraTone::apply`] reaches 254–255 by +/// Exposure +1 (issue #1632). +pub const ROLLOFF_STOPS: f32 = 1.0; + +/// Process V5's shoulder past a knee at scene luminance `x` and display `o` (below 1), where the +/// curve rises at `slope` (display per unit of scene luminance): the gap to white is +/// `gap / (1 + c·(2^(k·t) − 1))` at `t = log2(y / x)` stops past the knee, `k = 1 / ROLLOFF_STOPS`, +/// so it halves every [`ROLLOFF_STOPS`] stops in the end. `c` gives it the curve's slope at the +/// knee: d(display)/d(stop) there is `slope · x · ln 2` on the curve and `gap · c · k · ln 2` on the +/// shoulder. When `slope` is below `min_slope`, `d · (u − ln(1 + u))` (with `u = 2^(k·t) − 1`) +/// joins the denominator: it adds no slope at the knee, so the join keeps the curve's own slope, and +/// far up it grows like `d · u`, so the shoulder closes on white at `min_slope`'s pace (the gap still +/// halves every [`ROLLOFF_STOPS`] stops in the end). A term growing faster than `u` would close a +/// flat curve on white faster than a steeper one far up, and a darker curve would end up above it. +/// Monotone for `y ≥ x`, finite and at most 1; in real numbers it only approaches white, while in +/// `f32` the gap rounds to 0 eventually. +fn rolloff_past(y: f32, [x, o]: [f32; 2], slope: f32, min_slope: f32) -> f32 { + let gap = 1.0 - o; + let k = 1.0 / ROLLOFF_STOPS; + // bounded, so `c · 0` right past the knee stays 0 for a gap of a few ulps + let per = |s: f32| (s * x / (gap * k)).min(1e30); + let c = per(slope); + let d = (per(min_slope) - c).max(0.0); + let u = (k * (y / x).log2()).exp2() - 1.0; + // each term only when its coefficient is positive: `0 · ∞` is NaN far up + let linear = if c > 0.0 { c * u } else { 0.0 }; + let floor = if d > 0.0 { d * past_join(u) } else { 0.0 }; + 1.0 - gap / (1.0 + linear + floor) +} + +/// `u − ln(1 + u)` for `u ≥ 0`: 0 with no slope at 0, then rising like `u` (infinite for infinite +/// `u`). In `f64`, where the difference keeps its digits down to tiny `u`. +fn past_join(u: f32) -> f32 { + if u.is_infinite() { + return u; + } + let u = f64::from(u); + (u - u.ln_1p()).max(0.0) as f32 +} + +/// Stops below its white point where process V5's generic raw curve ([`ToneMap::rolloff_hdr`]) +/// leaves the extended Reinhard curve for the [`ROLLOFF_STOPS`] shoulder, instead of clipping at +/// the white point. With ½, the sensor's white of a raw without a camera curve (scene 1.0, about +/// ¼ stop below that white point at default settings) renders at about 8-bit 235, 248 and 252 at +/// Exposure 0, +1 and +2 where V1 to V4 render 239, 255 and 255 (issue #1632). +pub const GENERIC_KNEE_STOPS: f32 = 0.5; + /// Scene EV over grey where [`ToneMap::hdr`] starts lifting highlights above the SDR curve. const HDR_FROM_EV: f32 = 1.5; @@ -111,6 +191,16 @@ impl ToneMap { /// gain map only lifts highlights), then the highlights gain up to `peak − 1` more as in /// [`ToneMap::hdr`]. pub fn camera_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::camera_with(|y| curve.apply(y), curve.chroma, contrast, whites, blacks, peak) + } + + /// [`ToneMap::camera_hdr`] of process V5: past its last knot the camera curve rolls off in stops + /// ([`CameraTone::apply_rolloff`]) instead of closing on white within a stop of the sensor's. + pub fn camera_rolloff_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::camera_with(|y| curve.apply_rolloff(y), curve.chroma, contrast, whites, blacks, peak) + } + + fn camera_with(curve: impl Fn(f32) -> f32, chroma: [f32; CHROMA_N], contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 }; let adjustment = Self::display(contrast, whites, blacks); let neutral = contrast == 0.0 && whites == 0.0 && blacks == 0.0; @@ -118,12 +208,12 @@ impl ToneMap { let lut = (0..LUT_N) .map(|i| { let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32; - let y = curve.apply(GREY * 2f32.powf(ev)); + let y = curve(GREY * 2f32.powf(ev)); let o = if neutral { y } else { adjustment.apply(y) }; if peak > 1.0 { (o + (peak - 1.0) * smooth(HDR_FROM_EV, top, ev)).clamp(0.0, peak) } else { o } }) .collect(); - ToneMap { lut, chroma: curve.chroma } + ToneMap { lut, chroma } } /// `contrast`, `whites`, `blacks` in −100..100 (Lightroom slider units). pub fn new(contrast: f64, whites: f64, blacks: f64) -> ToneMap { @@ -136,6 +226,19 @@ impl ToneMap { /// white point moved up by the headroom, so the result stays monotone, never exceeds `peak`, /// and reaches it there (within the table's range). pub fn hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::generic(contrast, whites, blacks, peak, false) + } + + /// [`ToneMap::hdr`] of process V5 (issue #1632): from [`GENERIC_KNEE_STOPS`] below the white + /// point the curve rolls off into white in stops, with the same value and slope at the join, + /// instead of reaching white about ¼ stop past the sensor's white and clipping there. The SDR + /// curve stays below 1 (SDR white) and is the same as [`ToneMap::hdr`]'s below the join; for + /// `peak` above 1 the HDR lift then takes highlights up to `peak`, as in [`ToneMap::hdr`]. + pub fn rolloff_hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::generic(contrast, whites, blacks, peak, true) + } + + fn generic(contrast: f64, whites: f64, blacks: f64, peak: f32, rolloff: bool) -> ToneMap { let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 }; let c = (contrast / 100.0) as f32; let slope = if c >= 0.0 { 1.0 + 0.55 * c } else { 1.0 + 0.4 * c }; @@ -144,12 +247,17 @@ impl ToneMap { let wl = GREY * 2f32.powf(white_ev); let pre = 1.0 + GREY / wl; // keep grey near grey let b = (blacks / 100.0) as f32; + // extended Reinhard with white point wl: y(1 + y/wl²)/(1 + y), reaching 1 at wl + let reinhard = |y: f32| y * (1.0 + y / (wl * wl)) / (1.0 + y); + // V5's knee, below the white point, and the curve's slope there: (1 + y(2 + y)/wl²)/(1 + y)² + let knee = wl * (-GENERIC_KNEE_STOPS).exp2(); + let knee_slope = (1.0 + knee * (2.0 + knee) / (wl * wl)) / ((1.0 + knee) * (1.0 + knee)); + let knee = [knee, reinhard(knee)]; let lut = (0..LUT_N) .map(|i| { let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32; let y = GREY * 2f32.powf(ev * slope) * pre; - // extended Reinhard with white point wl: y(1 + y/wl²)/(1 + y) - let mut o = y * (1.0 + y / (wl * wl)) / (1.0 + y); + let mut o = if rolloff && y > knee[0] && knee[1] < 1.0 { rolloff_past(y, knee, knee_slope, 0.0) } else { reinhard(y) }; o = o.min(1.0); // Toe: blacks < 0 crushes, > 0 lifts. if b < 0.0 { @@ -324,6 +432,127 @@ mod tests { assert!(serde_json::from_value::(serde_json::json!({"knots": invalid})).is_err()); } + #[test] + fn rolloff_joins_the_curve_smoothly_and_never_reaches_white() { + let curve = CameraTone::new(knots()).unwrap(); + let last = curve.knots()[31]; + // the camera's curve up to the last knot + for i in 0..200 { + let y = last[0] * i as f32 / 199.0; + assert_eq!(curve.apply_rolloff(y), curve.apply(y), "{y}"); + } + // continuous, with the slope of the last segment, at the knot + let a = curve.knots()[30]; + let slope = (last[1] - a[1]) / (last[0] - a[0]); + let h = last[0] * 1e-3; + let after = (curve.apply_rolloff(last[0] + h) - curve.apply_rolloff(last[0])) / h; + assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}"); + // monotone, below white, and slower to close on it than the V1/V2 extension + let mut previous = last[1]; + for i in 1..3000 { + let y = last[0] * 1.005f32.powi(i); + let o = curve.apply_rolloff(y); + assert!(o >= previous && o < 1.0, "{y}: {o}"); + assert!(o <= curve.apply(y) + 1e-6, "{y}"); + previous = o; + } + assert!(1.0 - curve.apply_rolloff(last[0] * 8.0) > 4.0 * (1.0 - curve.apply(last[0] * 8.0))); + // a steep last segment joins with its own slope, and a last knot next to white without a step + for top in [0.9, 0.99995, 1.0 - f32::EPSILON] { + let mut k = knots(); + k[31] = [k[30][0] * 1.01, top]; + let c = CameraTone::new(k).unwrap(); + let slope = (k[31][1] - k[30][1]) / (k[31][0] - k[30][0]); + assert!(slope > 16.0 || top < 0.99, "{slope}"); + let mut prev = c.apply_rolloff(k[31][0]); + assert_eq!(prev, top); + for i in 1..2000 { + let o = c.apply_rolloff(k[31][0] * 1.0001f32.powi(i)); + assert!(o.is_finite() && o >= prev && o <= 1.0, "{top} {i}: {o} < {prev}"); + prev = o; + } + if top == 0.9 { + let h = k[31][0] * 1e-5; + let after = (c.apply_rolloff(k[31][0] + h) - top) / h; + assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}"); + } + } + // a flat or shallow last segment joins with its own slope (not the 0.1 floor of the V1/V2 + // extension) and still closes on white further up + for s in [0.0f32, 0.05] { + let mut k = knots(); + k[31][1] = k[30][1] + s * (k[31][0] - k[30][0]); + let c = CameraTone::new(k).unwrap(); + let (x, top) = (k[31][0], k[31][1]); + let h = x * 1e-4; + let after = (c.apply_rolloff(x + h) - top) / h; + assert!((after - s).abs() < 0.01, "{s}: right slope {after}"); + let mut prev = top; + for i in 1..3000 { + let o = c.apply_rolloff(x * 1.005f32.powi(i)); + assert!(o.is_finite() && o >= prev && o <= 1.0, "{s} {i}: {o} < {prev}"); + prev = o; + } + assert!(1.0 - c.apply_rolloff(x * 64.0) < (1.0 - top) / 4.0, "{s}"); + for y in [f32::MAX, f32::INFINITY] { + assert!((0.0..=1.0).contains(&c.apply_rolloff(y)), "{s} {y}"); + } + } + // hostile input + for y in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX] { + let o = curve.apply_rolloff(y); + assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}"); + } + // the tone map built from it is monotone and bounded, SDR and HDR + for peak in [1.0f32, 4.0] { + let t = ToneMap::camera_rolloff_hdr(&curve, 0.0, 0.0, 0.0, peak); + let mut prev = -1.0; + for i in 0..2400 { + let o = t.apply(1e-5 * 1.01f32.powi(i)); + assert!((0.0..=peak).contains(&o) && o >= prev - 1e-6, "{peak} {i}: {o}"); + prev = o; + } + } + } + + #[test] + fn generic_rolloff_joins_the_curve_smoothly_and_never_reaches_white() { + for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0), (0.0, -100.0, 0.0)] { + for peak in [1.0f32, 4.0] { + let (clip, roll) = (ToneMap::hdr(c, w, b, peak), ToneMap::rolloff_hdr(c, w, b, peak)); + let (clip, roll) = (clip.lut(), roll.lut()); + // the generic curve up to the knee, never brighter past it + let join = roll.iter().zip(clip).position(|(r, c)| r != c).expect("the shoulder starts inside the table"); + assert!(join > 2 && roll[join] < clip[join], "{c} {w} {b} {peak}: {join}"); + for (i, (r, c)) in roll.iter().zip(clip).enumerate() { + assert!(*r <= c + 1e-6, "{c} {w} {b} {peak} {i}: {r} > {c}"); + } + // same value and slope at the join: the step across it is the step before it + let (before, across) = (roll[join - 1] - roll[join - 2], roll[join] - roll[join - 1]); + assert!((across / before - 1.0).abs() < 0.02, "{c} {w} {b} {peak}: {before} then {across}"); + // monotone, and below white where the V1/V2 curve clips (SDR) or lifts to `peak` (HDR) + assert!(roll.windows(2).all(|p| p[1] >= p[0] - 1e-6), "{c} {w} {b} {peak}"); + if peak == 1.0 { + assert_eq!(clip[LUT_N - 1], 1.0); + // close to it at the top of the table at default settings (10 EV over grey); + // Whites −100 moves the white point, and so the shoulder, up 1.6 stops + let top = roll[LUT_N - 1]; + assert!(top < 1.0 && (top > 0.999 || w < 0.0), "{c} {w} {b}: {top}"); + } + } + } + // no kink where V1/V2 clip: there the clipped curve stops rising at once + let (clip, roll) = (ToneMap::new(0.0, 0.0, 0.0), ToneMap::rolloff_hdr(0.0, 0.0, 0.0, 1.0)); + let kink = |lut: &[f32]| lut.windows(3).filter(|p| p[1] - p[0] > 1e-5).map(|p| 1.0 - (p[2] - p[1]) / (p[1] - p[0])).fold(0.0f32, f32::max); + assert!(kink(clip.lut()) > 0.9); + assert!(kink(roll.lut()) < 0.05, "{}", kink(roll.lut())); + // hostile input (NaN passes through `ToneMap::apply` as on every curve) + for y in [f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX, f32::MIN_POSITIVE] { + let o = roll.apply(y); + assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}"); + } + } + #[test] fn monotone_and_bounded() { for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0)] { diff --git a/docs/gaps.md b/docs/gaps.md index 6025db3bed..0a7992644e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -17,7 +17,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app |---:|---|---|---|---:|---| | 1 B | **Camera colour is estimated, not measured** (LR-PROF-CAMERACOLOR). Raws start from a per-file fit to the camera JPEG, 10 bundled profiles, 52 spectral matrices (plus same-sensor bodies, e.g. the X-T30 through the X-T3) or chart-measured matrices (the EOS D60); others use a neutral matrix (a black-and-white camera JPEG gives its tone curve only, #577; dark JPEG tones also guide the toe, #1307) | ΔE vs camera JPEG 2.9–10 after fitting (raw-parity.md); 1 chart-calibrated model (EOS D60: its Kelvin scale and fallback colour, the look stays the JPEG fit) vs 1,500 Adobe Standard profiles | every raw shooter sees colour that is close but not Lightroom's; some get neutral-matrix colour | 50–90 | [raw-parity](raw-parity.md#colour) | | 2 B | **CR3 variants no public file uses** (LR-IMP-FORMATS): `crx.rs` refuses vertical-tile C-RAW, partial-subband and other plane coding, multi-tile 0x200 and adaptive low-frequency gains, and those files fall back to the preview. All 110 CC0 CR3s on raw.pixls.us (31 folders) decode from sensor data, so none of these variants has a public sample; 26 CR3 bodies are verified (M50 / R100 / R8 exact, R5 Mark II pinned, 22 more pinned on one CC0 file each and checked against the camera JPEG, [cr3.md](cr3.md#further-bodies-one-cc0-file-each)). HEIF stills are `.HIF` files, not CR3; no CR3 sRAW / mRAW sample exists | measured: Canon's share whose camera fully works 73% → 94% (raw-parity.md); 18 of 22 popular Canon bodies write CR3, all 18 now verified | +0.3 points of photographers; the variants surface only as user files that open as a preview | 10–25 | [raw-parity](raw-parity.md#remaining-work-ranked-by-photographers-unlocked-per-hour) | -| 3 B | **Render fidelity partial** (LR-BEHAV-RENDER-FIDELITY): calibrated camera-look Contrast and Blacks; other operators need measurement | process V3 reduces held-out response error from 0.136 to 0.038 stops for Contrast and 0.424 to 0.077 for Blacks on one Sony camera; Whites remains V2 pending a follow-up | imported Lightroom edits still differ, especially on uncalibrated operators and cameras | 30–60 | [calibrated Light operators](light-v3.md), [process versions](process-versions.md) | +| 3 B | **Render fidelity partial** (LR-BEHAV-RENDER-FIDELITY): calibrated camera-look Contrast and Blacks; other operators need measurement; from process V5 raw tone curves roll off into white in stops, so Exposure keeps recorded highlights (#1632) | process V3 reduces held-out response error from 0.136 to 0.038 stops for Contrast and 0.424 to 0.077 for Blacks on one Sony camera; Whites remains V2 pending a follow-up | imported Lightroom edits still differ, especially on uncalibrated operators and cameras | 30–60 | [calibrated Light operators](light-v3.md), [process versions](process-versions.md) | | 4 | ~~Original-pixel detail at 100%~~ (LR-VIEW-ZOOM): closed 2026-10-12, see Closed recently | checklist row ✅ | — | 0 | [ui-parity](ui-parity.md) | | 5 B | **AI masks: Subject, Sky, People, Background, Landscape** are heuristics; Object / Describe run SAM 3 but its download has no mirror configured | `crates/segment`; ai-masks.md; MASK rows 67% | masking is how most Lightroom users edit today | 40–70 + model decision | [target-app-parity](target-app-parity.md#ai) | | 6 B | **Compressed ORF** (every Olympus / OM body since ~2008) | measured: 66 of 78 Olympus / OM models preview-only; `orf.rs` refuses; OM bucket 3% of photographers, 3% of them fully work | +2.6 points; best gain per hour of any raw gap (~0.2) | 8–15 | [raw-parity](raw-parity.md#compressed-orf-a-clean-room-starting-point) (the two Olympus patents that describe the method) | @@ -90,6 +90,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Gap 3: process V5 rolls a raw's tone curve off into white in stops, so raising Exposure keeps the highlights the sensor recorded (#1632); the gap stays open (no Lightroom comparison) and hours are unchanged | | 2026-10-27 | minor | Gap 26: the loupe shows built previews (they were rendered again), photos ahead and the whole view are prepared in the background with settings per mode; gap not closed | | 2026-10-27 | minor | Gap 26: culling speed measured and improved (progressive Local browse, camera previews made ahead, a CR3's smallest covering JPEG, camera JPEG first at 100 %); what is left listed; gap not closed | | 2026-11-02 | minor | PERF-STEP-STALL: the catalog log is written and synced off the UI thread, so stepping and flagging never wait for the drive (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, counted as unsaved, never dropped; gap 26 not closed | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index d970e1ba08..e4a8463cdc 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -466,7 +466,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-OFFLINE | Offline editing | P1 | ✅ | | local-first: everything works offline | | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | -| LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs` | Process V4 calibrates global camera-look Contrast and Blacks against black-box Lightroom exports of Sony ILCE-7CR photos. Held-out response errors are 0.038 and 0.077 stops; V1/V2 keep their rendering. Whites retains V2 and awaits a follow-up. Exposure, Highlights/Shadows, other operators and broader camera coverage remain open (`docs/light-v3.md`). | +| LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs` | Process V4 calibrates global camera-look Contrast and Blacks against black-box Lightroom exports of Sony ILCE-7CR photos. Held-out response errors are 0.038 and 0.077 stops; V1/V2 keep their rendering. Whites retains V2 and awaits a follow-up. Exposure, Highlights/Shadows, other operators and broader camera coverage remain open (`docs/light-v3.md`). From process V5 a raw's tone curve rolls off into white in stops (past a camera curve's last fitted knot, or from half a stop below the generic curve's white point instead of clipping), so Exposure +1 and +2 keep the highlights the sensor recorded: on 12 CC0 corpus raws and 6 CC0 DNGs on the generic curve, unclipped pixels whose luminance renders at 254 or more fall from up to 22.5 % to 0 at +1 EV and from up to 35 % to at most 0.03 % at +2 EV, apart from one sky that is mostly at the clip (#1632). Not compared with Lightroom's output | | LR-BEHAV-DRAGDROP | Drag and drop | P1 | ✅ | `crates/ui-egui/src/lib.rs`, `crates/ui-egui/src/panels/grid.rs` (`drag_feedback`), `crates/ui-egui/src/panels/left.rs` (`drop_target`, `album_drag_over`, `top_level_drop_target`, `drag_auto_scroll`), `crates/ui-egui/src/destination.rs`, `crates/ui-egui/src/widgets.rs` (`context_menu`), `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/tests/carried_right_click.rs`, `crates/ui-egui/src/tests/carried_text_field_menu.rs` | a right-click while photos are carried opens no context menu (every menu opened through `widgets::context_menu`: sidebar rows, grid cells, lists; a text field's own Cut / Copy / Paste menu too); files → app (a drop-target card while they hover, then the import review); grid photos → an album row (adds the selection, with a count badge while dragging); sidebar album / folder rows → a folder (moves it; its name follows the pointer); a drag of albums or grid photos near the top or bottom edge of the sidebar scrolls it (faster nearer the edge, only while the pointer is over the sidebar); when another folder has the same name, the dragged label, the Move question and the toast name the folder it is in (`home (/a)`); an album drop's toast does the same for an album of that name in another album folder (two in the same place have nothing to tell them apart and keep the plain name); only the primary button drags photos and drops them: a right-button drag over a grid cell neither picks photos up nor changes the selection, and a right-button release while photos are dragged neither drops them nor ends the drag | | LR-BEHAV-TOAST | Toast notifications | P1 | ✅ | `crates/ui-egui/src/panels.rs` | | | LR-BEHAV-DIALOGS | Dialogs fit the window | P1 | ✅ | `crates/ui-egui/src/dialogs.rs` (`dialog_body`, `list_height`), `crates/ui-egui/src/tests/dialog_fit.rs`, `crates/ui-egui/src/tests/dialog_copy.rs`, `crates/ui-egui/src/tests/dialogs.rs` (`a_click_outside_closes_the_dialog_when_settings_allow_it`) | a dialog taller than the window (Export on a 1366×768 screen, issue #781) never runs off it: its options scroll while the title bar and the Cancel / confirm row stay on screen (the confirm button names its action: Create, Rename, Create Stacks, Export 3 Photos…, with "OK" kept only for a one-field prompt opened with a command that has no verb, `crates/ui-egui/src/tests/dialog_copy.rs`); lists that scroll on their own (What's New, All Metadata, shortcuts, smart-album rules, credits) get shorter first; dialogs that fit look as before; Import keeps its own resizable, scrolling window; Settings → Dialogs → Close a dialog by clicking outside it (off by default, so a stray click never throws away a dialog's choices): a click pressed and released on the dimmed backdrop closes the dialog like Esc and doesn't reach the panels below, while a drag that ends outside (a slider pulled past the edge) or a click that closes a dropdown keeps it; the import review never closes this way (`clicked_backdrop`); a one-line prompt (Rename Folder, New Folder on Disk, the preset and version names, New Library when its name can't be used, Auto-Tag from Tracklog) the engine refuses stays open with its text and shows the reason in a toast, so the name can be corrected, where it used to close without a word; a New Folder on Disk that works says so (“Created folder “Selects” in “2026/Shoot””, naming the parent by its last two folders as dialogs do) | @@ -731,7 +731,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-DEV-CALIB | Calibration panel | P1 | ✅ | `ctl:calibration.*` | | | LRC-DEV-TAT | Targeted adjustment tools | P1 | ✅ | `cmd:develop.targeted` (`target`: curve / hue / sat / lum) | | | LRC-DEV-DEFAULTS | Per-camera raw defaults | P1 | ✅ | `cmd:library.preferences` (`camera`, `import.perCamera`), `crates/ui-egui/src/dialogs/settings.rs` | Settings → Import: raw default and per-camera presets | -| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks. New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. | +| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks, V5 rolls raw tone curves off into white in stops (#1632). New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. | | LRC-DEV-VIEWOPTIONS | Develop view options | P2 | 🟡 | `cmd:view.viewOptions`, `crates/ui-egui/src/dialogs/settings.rs` (`view_options`) | View ▸ View Options… (⌘J), the Loupe View part: Show Info Overlay with Info 1 / Info 2, and the three lines of each (none, file name, capture date, dimensions, exposure, camera, lens, camera + lens) with Use Defaults; Show Briefly When Photo Changes under each Info (one at most): with the overlay off, that Info shows for 3 s each time the loupe changes photo; General's Show message when loading or rendering photos (on by default; off, the loupe does not say "Rendering…"); applied as they change, saved with the app settings; `view.viewOptions {info1, info2, briefly, loupeMessages}` sets them for agents. Not yet: the Grid View tab, more fields (ratings, metadata, copy name), the video-frame option | | LRC-DEV-LOUPEOVERLAY | Loupe overlay: layout image | P2 | 🟡 | `cmd:view.chooseLayoutImage`, `cmd:view.layoutImage`, `cmd:view.layoutImageOpacity`, `cmd:view.layoutImageMatte`, `crates/ui-egui/src/panels/layout_overlay.rs` | View ▸ Loupe Overlay: a PNG with transparency (a cover layout, a banner's safe areas) fitted and centred over the loupe photo, following zoom and pan; opacity and matte (the photo darkened outside the graphic's box) in steps; ⌥⌘O shows / hides it; read off the UI thread; saved with the UI state. Not yet: the Grid and Guides overlays, moving and resizing the layout with ⌘ held, free opacity / matte sliders | | LRC-DEV-VIDEO | Video frame capture | P2 | ⬜ | | | @@ -801,6 +801,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V5 rolls a raw's tone curve off into white in stops, past a camera curve's last knot and from half a stop below the generic curve's white point, so raising Exposure no longer turns recorded highlights white (#1632); statuses and counts unchanged | | 2026-11-05 | minor | LR-LIB-PEOPLE: face boxes another app drew on the photo as stored land on the upright photo (#2674) | | 2026-11-02 | minor | LRC-DEV-AUTOSYNC (N-A3, note 18): Auto Sync carries white balance as a mode or on each photo's own scale: As Shot and Auto per photo (were the active photo's numbers), a Temp move keeps each photo's tint, the same number on photos of the same scale, a photo of another scale (a JPEG beside a raw) moves by as much; Sync Settings unchanged; status unchanged | | 2026-10-29 | minor | LR-PREF-LOCALSTORAGE, LRC-LIB-PREVIEWS: the preview cache stays uncapped and warns once per session when its drive has under 10 % or 20 GB free, with a button to Settings → Performance; statuses unchanged | diff --git a/docs/process-versions.md b/docs/process-versions.md index ed1f66b31a..5a96152f79 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -12,7 +12,8 @@ stronger Light sliders, issue #196) without changing a single photo someone has | **V1** | LightCraft's rendering from before process versions existed. Frozen. | | **V2** | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no median under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | | **V3** | Pixel-scale sharpening (issue #757): Radius uses the original photo’s pixels, Detail controls halo damping, and downsized sources retain a response-matched sharpening band. V1 and V2 keep texture-band sharpening exactly. The sharpen plane is keyed by radius and process and invalidated after noise-reduction changes. The Highlights/Shadows base and tone map are unchanged from V2. | -| **V4** (the latest) | V3 plus calibrated global Contrast (per channel) and Blacks (per-channel/luminance mix) on raws with a camera tone curve. Whites behaves exactly as V2, both signs; its calibration is a planned follow-up. Other sources and local adjustments retain V2 operators. See [calibrated Light operators](light-v3.md). | +| **V4** | V3 plus calibrated global Contrast (per channel) and Blacks (per-channel/luminance mix) on raws with a camera tone curve. Whites behaves exactly as V2, both signs; its calibration is a planned follow-up. Other sources and local adjustments retain V2 operators. See [calibrated Light operators](light-v3.md). | +| **V5** (the latest) | V4 plus: a raw's tone curve rolls off into white in stops instead of reaching it within about a stop of the sensor's white, so raising Exposure keeps the highlights the sensor recorded (issue #1632). **Camera curve** (the look fitted to the embedded JPEG, or a DNG's `ProfileToneCurve`; `CameraTone`): past its last knot `CameraTone::apply_rolloff` closes the gap to white by `gap / (1 + c·(2^t − 1))` at `t` stops past the knot, with `c` matching the curve's slope there and the gap halving every stop in the end (`tone::ROLLOFF_STOPS`); `ToneMap::camera_rolloff_hdr` builds the table from it. Under V1 to V4 the curve past its last knot (fitted only to camera JPEG tones below 0.85, so 1 to 3 stops below the sensor's white on most photos) closes on white exponentially in linear light: the sensor's white renders at 8-bit 246 to 254 at Exposure 0 and 254 to 255 from Exposure +1. On the 11 CC0 corpus files with a fitted look (8 Sony, 2 Nikon, 1 Fujifilm) it now renders at 239 to 250 at Exposure 0 and 247 to 253 at +1. A DNG curve that reaches white at the sensor's white renders as before. **Generic curve** (raws without a camera curve, `ToneMap::rolloff_hdr`): from half a stop below its white point (`tone::GENERIC_KNEE_STOPS`) the same shoulder takes over, with the extended Reinhard curve's value and slope at the join, where V1 to V4 clip at the white point (scene 1.18 at default settings, ¼ stop above the sensor's white). The sensor's white renders at about 235, 248 and 252 at Exposure 0, +1 and +2 (V1 to V4: 239, 255, 255; the CC0 Canon R8 file and 6 CC0 DNGs without a camera curve). Content past the old clip point, such as a clipped sky, now renders up to 15 codes below white at Exposure 0 and reaches 255 about 5 stops past the sensor's white. Below the last knot or the join, JPEGs and other display-referred sources, and the camera fit itself are unchanged; CPU and GPU share the tone LUT. | ## The rule @@ -102,4 +103,5 @@ extra field and retain their existing cached renders. No cache-version bump is n | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | V5: a raw's tone curve rolls off into white in stops, so raising Exposure keeps recorded highlights (#1632) | | 2026-10-12 | minor | Calibrated Contrast and Blacks, V2 Whites, resolved-process cache keys and number coordination | diff --git a/docs/whats-new.md b/docs/whats-new.md index cc371e0dfc..c0b75f74c6 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -21,6 +21,16 @@ hot pixels on a sensor. Stars and other points of light that are kept don't count, so a dense star field still loses its hot pixels. Settings ▸ Performance ▸ Hot pixel limit sets the share (0.05 % to 1 %). +### Raising Exposure keeps raw highlights (process 5) +- Raising Exposure on a raw no longer turns the brightest tones the sensor recorded white (issue #1632). The tone + curve now eases into white a stop at a time instead of reaching it within about a stop of the sensor's white: at + Exposure +1 and +2 a sky, a lit wall or a face keeps its detail where it used to go flat white. At Exposure 0 the + brightest tones render a few codes darker (on average 1 code or less on the photos measured), and fully clipped + areas such as a blown sky stay slightly below pure white until Exposure lifts them further. A DNG whose own tone + curve already reaches white at the sensor's white renders as before. This is rendering + process 5: new photos (and Reset) get it, photos you already edited keep their look until you choose Photo ▸ Update + to Current Process. See [process versions](process-versions.md). + ## 2026-11-02 ### The Windows title bar is readable from the moment the window opens From 58da12bc5c38e22980729e170429fe42359f8b46 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 22:08:12 +0200 Subject: [PATCH 07/24] Export: built-in presets for Instagram Feed, Story / Reel, Web / Portfolio, Full Resolution (#2104) (#2209) * The named-export-preset system itself (export.presets / export.savePreset / export.deletePreset, user presets saved with the library, the Export dialog dropdown and File > Export with Preset) already existed; this adds the four named built-ins the issue asks for, locks them in with an expand / round-trip / apply test, and updates the LR-EXP-DIALOG and LR-EXP-PREVIOUS tracker rows (the stale 'no named export presets yet' note goes away). * #2104: test all four built-in export presets, not only Instagram Feed The named built-in preset test expanded, validated and rendered Instagram Feed alone. It now runs the same checks for each of the four names: the expanded settings, validation as app.export params, the round trip through a user preset, and a render at the size the preset sets. Full Resolution Master sets no long edge, so its render must be the photo's own size, with no resize. The rendered size is also compared with output_size, the same calculation the exporter uses. * The preset sets a 1920 px long edge and nothing about the shape, so a 3:2 photo exports at 1920 x 1280 and no 9:16 frame is made. The export options have no crop-to-aspect setting, and none is added here. The preset's doc comment and the LR-EXP-DIALOG row of the parity checklist say so, and the checklist has a revision line for this and for the translations. * The Export dialog shows built-in preset names through builtin_label, which looks them up in the language catalogs. Instagram Feed, Instagram Story / Reel, Web / Portfolio and Full Resolution Master were in none of the catalogs, so every language showed them in English. Each catalog now carries the four names next to the existing JPEG (Small) and JPEG (Large) entries. The translations are drafts and need review by a native speaker of each language. A new test checks that every catalog has an entry for each of the four names. The catalog comparison only reports gaps, so without this test a missing name would pass silently. * Address review for pull request 2209 * #2104: the four built-in export preset names in the catalogs main added after this branch was cut (Finnish, Indonesian, Swedish, Vietnamese). The i18n test that every catalog carries the four names failed on them after the rebase; each of the four now carries them next to the existing JPEG (Large) entry, in the same shape as the other thirteen catalogs. The translations are drafts and need review by a native speaker of each language. * Say the Web / Portfolio preset keeps copyright and creator metadata The copyright export metadata policy embeds the copyright notice, status, usage terms and info URL together with the creator (export/encoding.rs fills the artist field before the policy match returns), so the LR-EXP-DIALOG row and the 2026-10-17 revision line understated the preset as keeping copyright-only metadata. Both now say copyright and creator metadata. * Docs: finish the parity-checklist merge The merge left conflict markers in the revision history. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/export.rs | 25 +++++++++ crates/engine/src/export/options.rs | 12 ++++ crates/engine/src/library.rs | 3 + crates/engine/src/tests/export.rs | 87 +++++++++++++++++++++++++++++ crates/ui-egui/locales/cs.json | 4 ++ crates/ui-egui/locales/de.json | 4 ++ crates/ui-egui/locales/es.json | 4 ++ crates/ui-egui/locales/fi.json | 4 ++ crates/ui-egui/locales/fr.json | 4 ++ crates/ui-egui/locales/id.json | 4 ++ crates/ui-egui/locales/it.json | 4 ++ crates/ui-egui/locales/ja.json | 4 ++ crates/ui-egui/locales/ka.json | 4 ++ crates/ui-egui/locales/pl.json | 4 ++ crates/ui-egui/locales/pt-br.json | 4 ++ crates/ui-egui/locales/ru.json | 4 ++ crates/ui-egui/locales/sv.json | 4 ++ crates/ui-egui/locales/uk.json | 4 ++ crates/ui-egui/locales/vi.json | 4 ++ crates/ui-egui/locales/zh-hans.json | 4 ++ crates/ui-egui/locales/zh-hant.json | 4 ++ crates/ui-egui/src/i18n/tests.rs | 30 +++++++++- docs/parity-checklist.md | 15 ++--- 23 files changed, 227 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs index 9af0606d9d..65692e0eac 100644 --- a/crates/engine/src/cmd/export.rs +++ b/crates/engine/src/cmd/export.rs @@ -14,6 +14,31 @@ impl Session { builtin_presets().into_iter().map(|p| (p, true)).chain(self.export_presets.iter().cloned().map(|p| (p, false))).collect() } + /// The user's export presets, renamed where they shadow a built-in: the built-ins are looked up + /// first, so a preset whose name matches one of them (in any case) could never be selected or + /// exported, and the save path refuses a built-in's name. Such a preset gets a free name of its + /// own (` (mine)`, then a number when that is taken too), keeping its settings. + pub(crate) fn rename_shadowing_export_presets(&mut self) { + let builtins: Vec = builtin_presets().into_iter().map(|p| p.name).collect(); + // the names that may not be taken: the built-ins', and every user preset's own + let mut taken: Vec = builtins.clone(); + taken.extend(self.export_presets.iter().map(|p| p.name.clone())); + for preset in self.export_presets.iter_mut() { + if !builtins.iter().any(|b| b.eq_ignore_ascii_case(&preset.name)) { + continue; + } + let base = format!("{} (mine)", preset.name); + let mut name = base.clone(); + let mut n = 2; + while taken.iter().any(|t| t.eq_ignore_ascii_case(&name)) { + name = format!("{base} {n}"); + n += 1; + } + taken.push(name.clone()); + preset.name = name; + } + } + /// `app.export` params with a named `preset` expanded: the preset's params, overridden by the /// call's own (`preset` itself removed). Unknown preset names are an error. pub fn export_params(&self, p: &Value) -> std::result::Result { diff --git a/crates/engine/src/export/options.rs b/crates/engine/src/export/options.rs index 5edf078aa5..75884263ed 100644 --- a/crates/engine/src/export/options.rs +++ b/crates/engine/src/export/options.rs @@ -198,6 +198,11 @@ pub struct ExportPreset { } /// The built-in export presets (File → Export with Preset). +/// +/// A preset sets output options (format, quality, size, colour space, sharpening, metadata), never a +/// crop. "Instagram Story / Reel" therefore applies no crop to 9:16: it sets a 1920 px long edge only, so +/// a 3:2 photo exports at 1920 × 1280. The export options have no crop-to-aspect setting; a photo's own +/// crop is the only way to change its shape before export. pub fn builtin_presets() -> Vec { let p = |name: &str, params: serde_json::Value| ExportPreset { name: name.into(), params }; vec![ @@ -205,6 +210,13 @@ pub fn builtin_presets() -> Vec { p("JPEG (Large)", serde_json::json!({"format": "jpeg", "quality": 92, "longEdge": 0, "colorSpace": "srgb"})), p("Original + Settings", serde_json::json!({"format": "original"})), p("DNG", serde_json::json!({"format": "dng"})), + p("Instagram Feed", serde_json::json!({"format": "jpeg", "quality": 85, "longEdge": 1080, "colorSpace": "srgb", "sharpen": "screen"})), + p( + "Instagram Story / Reel", + serde_json::json!({"format": "jpeg", "quality": 85, "longEdge": 1920, "colorSpace": "srgb", "sharpen": "screen"}), + ), + p("Web / Portfolio", serde_json::json!({"format": "jpeg", "quality": 85, "longEdge": 2048, "colorSpace": "srgb", "metadata": "copyright"})), + p("Full Resolution Master", serde_json::json!({"format": "jpeg", "quality": 95, "longEdge": 0, "colorSpace": "displayP3"})), ] } diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 8cd242face..2338d4f1a8 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -581,6 +581,9 @@ impl Session { self.last_export = prefs.last_export; self.last_merge = prefs.last_merge; self.export_presets = prefs.export_presets; + // a user preset whose name shadows a built-in one could never be selected or exported + // (the built-ins are looked up first); it gets a name of its own instead + self.rename_shadowing_export_presets(); self.print_templates = prefs.print_templates; self.metadata_presets = prefs.metadata_presets; self.filter_presets = prefs.filter_presets; diff --git a/crates/engine/src/tests/export.rs b/crates/engine/src/tests/export.rs index 531f1d652c..bd5124d71e 100644 --- a/crates/engine/src/tests/export.rs +++ b/crates/engine/src/tests/export.rs @@ -189,6 +189,63 @@ fn presets_conflicts_and_subfolders() { assert_eq!(written, ["out/Sub/LC01347.png"]); } +/// Each of the four named delivery-target built-ins: listed as built-in, expanded to the settings the +/// issue asks for, valid as `app.export` params, round-tripped through a user preset, and rendered at +/// its size. A long edge is all a preset sets, so none of them crops the photo. +#[test] +fn named_builtin_presets_expand_round_trip_and_apply() { + use crate::export::output_size; + let mut s = Session::with_demo(); + // the issue's four named built-ins are listed, marked builtin + let builtin: Vec = s + .execute("export.presets", &json!({})) + .unwrap() + .as_array() + .unwrap() + .iter() + .filter(|p| p["builtin"].as_bool().unwrap()) + .map(|p| p["name"].as_str().unwrap().to_string()) + .collect(); + // 0 = no resize: the photo's own (cropped) full size + let issue = [ + ("Instagram Feed", json!({"format": "jpeg", "quality": 85, "longEdge": 1080, "colorSpace": "srgb", "sharpen": "screen"})), + ("Instagram Story / Reel", json!({"format": "jpeg", "quality": 85, "longEdge": 1920, "colorSpace": "srgb", "sharpen": "screen"})), + ("Web / Portfolio", json!({"format": "jpeg", "quality": 85, "longEdge": 2048, "colorSpace": "srgb", "metadata": "copyright"})), + ("Full Resolution Master", json!({"format": "jpeg", "quality": 95, "longEdge": 0, "colorSpace": "displayP3"})), + ]; + for (name, settings) in &issue { + assert!(builtin.contains(&name.to_string()), "{name}: {builtin:?}"); + // expanding one yields exactly the issue's settings, and they validate as app.export params + let params = s.export_params(&json!({"preset": name})).unwrap(); + assert_eq!(¶ms, settings, "{name}"); + ExportOptions::validate("app.export", ¶ms).unwrap_or_else(|e| panic!("{name}: {e:?}")); + // round trip: save as a user preset → expand again → identical ExportOptions + let mine = format!("My {name}"); + s.execute("export.savePreset", &json!({"name": mine, "params": params})).unwrap(); + let again = s.export_params(&json!({"preset": mine})).unwrap(); + assert_eq!(ExportOptions::from_json(¶ms), ExportOptions::from_json(&again), "{name}"); + } + // built-in names (the new ones too) are reserved + assert!(s.execute("export.savePreset", &json!({"name": "web / portfolio", "params": {}})).is_err()); + // applying each one really renders at its size, and the photo keeps its own shape. The fixture + // is a demo scene at 2048×1365 instead of the demo library's 6000×4000: a preset only sets a + // long edge, so its behaviour is the same at this size, and every preset edge (1080, 1920, + // 2048) still lands — the largest one exactly at the fixture's own size, unresized. + use lightcraft_catalog::{Op, Photo, Source}; + let id = s.catalog.alloc_photo_id(); + let photo = Photo::new(id, Source::Demo { scene: 1 }, "LC01200.JPG", "JPEG", 2048, 1365, "2026-09-28T09:30:00"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo.clone()) }).unwrap(); + for (name, settings) in &issue { + let o = ExportOptions::from_json(settings); + let e = export_photo(&mut s, id, &o, 1).unwrap(); + assert_eq!((e.width, e.height), output_size(&photo, &o), "{name}"); + match settings["longEdge"].as_u64().unwrap_or(0) { + 0 => assert!(o.resize.is_none(), "{name}: full size means no resize"), + edge => assert_eq!(e.width.max(e.height) as u64, edge, "{name}: {}×{}", e.width, e.height), + } + } +} + /// Issue #2571: a subfolder with `..`, a root or a drive wrote outside the chosen folder. It is /// cleaned where the folder is used, so a preset or the Export dialog's field (which set it /// without `from_json`) are covered as well as command parameters. @@ -1463,3 +1520,33 @@ fn huge_export_size_is_an_error() { assert!(s.render_now(id, huge, huge).is_err()); assert!(s.render_now(id, 10, 70_000).is_err()); } + +/// A user export preset whose name collides with a built-in one (in any case) is shadowed by it: +/// the built-ins are looked up first, so the user's preset can never be selected or exported, and +/// the save path refuses to recreate it under a free name. Loading the preferences renames it to a +/// name of its own instead, keeping its settings. +#[test] +fn a_user_preset_naming_a_built_in_is_renamed_when_the_library_opens() { + let lib = temp_dir("export-preset-rename"); + { + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + s.close_library().unwrap(); + } + std::fs::write(lib.join("prefs.json"), r#"{"exportPresets": [{"name": "web / portfolio", "params": {"format": "png", "width": 64}}]}"#).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + + let builtins: Vec = crate::export::builtin_presets().into_iter().map(|p| p.name).collect(); + assert_eq!(s.export_presets.len(), 1, "the user's preset is kept"); + let name = s.export_presets[0].name.clone(); + assert!(!builtins.iter().any(|b| b.eq_ignore_ascii_case(&name)), "{name} still shadows a built-in"); + assert_eq!(s.export_presets[0].params, json!({"format": "png", "width": 64}), "its settings are kept"); + // it is reachable under its own name: the export takes the user's settings + let p = s.export_params(&json!({"preset": name})).unwrap(); + assert_eq!((p["format"].as_str(), p["width"].as_u64()), (Some("png"), Some(64)), "{p}"); + // and the built-in of that name is still the built-in + let b = s.export_params(&json!({"preset": "Web / Portfolio"})).unwrap(); + assert_eq!((b["format"].as_str(), b["longEdge"].as_u64()), (Some("jpeg"), Some(2048)), "{b}"); + let _ = std::fs::remove_dir_all(&lib); +} diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 51851dda54..95f52edb1b 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -954,6 +954,10 @@ "It tests this album, so testing it back would loop": "Testuje toto album, takže zpětný test vytvoří smyčku", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Obraz s redukovaným šumem ještě není vytvořen a obrazy se nevytvářejí automaticky (Nastavení, Redukce šumu pomocí AI).", "JPEG (Large)": "JPEG (velký)", + "Instagram Feed": "Instagram Feed", + "Instagram Story / Reel": "Instagram Story / Reel", + "Web / Portfolio": "Web / portfolio", + "Full Resolution Master": "Master v plném rozlišení", "JPEG (Small)": "JPEG (malý)", "Join the ArtCraft Discord": "Připojit se k Discordu ArtCraft", "Join the ArtCraft Discord…": "Připojit se k Discordu ArtCraft…", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index a89c918694..c05a66246b 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -754,6 +754,10 @@ "Invert Component": "Komponente umkehren", "Invert Mask": "Maske umkehren", "JPEG (Large)": "JPEG (groß)", + "Instagram Feed": "Instagram-Feed", + "Instagram Story / Reel": "Instagram-Story / Reel", + "Web / Portfolio": "Web / Portfolio", + "Full Resolution Master": "Master in voller Auflösung", "JPEG (Small)": "JPEG (klein)", "JPEG with the same name (`IMG_0001.CR3` + `IMG_0001.JPG`) no longer share one sidecar: the raw keeps `IMG_0001.xmp`,": "JPEG mit gleichem Namen (`IMG_0001.CR3` + `IMG_0001.JPG`) keine Begleitdatei mehr: RAW verwendet `IMG_0001.xmp`,", "Join the ArtCraft Discord": "ArtCraft auf Discord beitreten", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 101d7c4fb0..bacf411182 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -756,6 +756,10 @@ "Invert Component": "Invertir componente", "Invert Mask": "Invertir máscara", "JPEG (Large)": "JPEG (grande)", + "Instagram Feed": "Feed de Instagram", + "Instagram Story / Reel": "Historias / Reel de Instagram", + "Web / Portfolio": "Web / Portfolio", + "Full Resolution Master": "Máster a resolución completa", "JPEG (Small)": "JPEG (pequeño)", "Join the ArtCraft Discord": "Unirse al Discord de ArtCraft", "Join the ArtCraft Discord…": "Unirse al Discord de ArtCraft…", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 17f2ca7728..43be15d273 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -967,6 +967,10 @@ "It tests this album, so testing it back would loop": "Se testaa tätä albumia, joten sen testaaminen takaisin muodostaisi silmukan", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Sen kohinanpoistettua kuvaa ei ole vielä tehty, eikä kuvia tehdä itsestään (Asetukset, Tekoälykohinanpoisto).", "JPEG (Large)": "JPEG (suuri)", + "Instagram Feed": "Instagram-syöte", + "Instagram Story / Reel": "Instagram-story / Reel", + "Web / Portfolio": "Web / Portfolio", + "Full Resolution Master": "Täysresoluutioinen masteri", "JPEG (Small)": "JPEG (pieni)", "Join the ArtCraft Discord": "Liity ArtCraftin Discordiin", "Join the ArtCraft Discord…": "Liity ArtCraftin Discordiin…", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index ed035df142..974347cc4d 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -715,6 +715,10 @@ "Invert Component": "Inverser le composant", "Invert Mask": "Inverser le masque", "JPEG (Large)": "JPEG (grand)", + "Instagram Feed": "Fil Instagram", + "Instagram Story / Reel": "Story / Reel Instagram", + "Web / Portfolio": "Web / Portfolio", + "Full Resolution Master": "Master pleine résolution", "JPEG (Small)": "JPEG (petit)", "Join the ArtCraft Discord": "Rejoindre le Discord d'ArtCraft", "Join the ArtCraft Discord…": "Rejoindre le Discord d'ArtCraft…", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 11e4f344ef..70999cc4f5 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -972,6 +972,10 @@ "It tests this album, so testing it back would loop": "Album itu sudah menjadikan album ini sebagai syarat; menjadikannya syarat di sini akan menimbulkan perulangan", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Hasil pengurangan noise foto ini belum dibuat, dan tidak dibuat secara otomatis (Pengaturan, Pengurangan noise AI).", "JPEG (Large)": "JPEG (besar)", + "Instagram Feed": "Umpan Instagram", + "Instagram Story / Reel": "Instagram Story / Reel", + "Web / Portfolio": "Web / Portofolio", + "Full Resolution Master": "Master Resolusi Penuh", "JPEG (Small)": "JPEG (kecil)", "Join the ArtCraft Discord": "Gabung ke Discord ArtCraft", "Join the ArtCraft Discord…": "Gabung ke Discord ArtCraft…", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 6aca1673bf..cf5082aba1 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -716,6 +716,10 @@ "Invert Component": "Inverti componente", "Invert Mask": "Inverti maschera", "JPEG (Large)": "JPEG (grande)", + "Instagram Feed": "Feed Instagram", + "Instagram Story / Reel": "Storie / Reel Instagram", + "Web / Portfolio": "Web / Portfolio", + "Full Resolution Master": "Master a piena risoluzione", "JPEG (Small)": "JPEG (piccolo)", "Join the ArtCraft Discord": "Unisciti al Discord di ArtCraft", "Join the ArtCraft Discord…": "Unisciti al Discord di ArtCraft…", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index bd03abd901..3a9c49e79a 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -564,6 +564,10 @@ "Instant ’70s": "インスタント’70s", "Invert Component": "構成要素を反転", "JPEG (Large)": "JPEG(大)", + "Instagram Feed": "Instagram フィード", + "Instagram Story / Reel": "Instagram ストーリー / リール", + "Web / Portfolio": "ウェブ / ポートフォリオ", + "Full Resolution Master": "フル解像度マスター", "JPEG (Small)": "JPEG(小)", "Join the ArtCraft Discord": "ArtCraftのDiscordに参加", "Join the ArtCraft Discord…": "ArtCraftのDiscordに参加…", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index d2b75bb0ca..e3a773e93f 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -843,6 +843,7 @@ "Fujifilm RAFs from 59 camera models now get the lens correction the camera stores in the file: distortion (with the": "59 კამერის მოდელის Fujifilm RAF-ები ახლა იღებს ობიექტივის კორექციას, რომელსაც კამერა ფაილში ინახავს: დეფორმაცია (", "Fujifilm lens corrections": "Fujifilm-ის ობიექტივის კორექციები", "Full": "სრული", + "Full Resolution Master": "სრული გარჩევადობის მასტერი", "Full Screen Preview": "სრულეკრანიანი გადახედვა", "Full screen mode": "სრულეკრანიანი რეჟიმი", "Full size": "სრული ზომა", @@ -1018,6 +1019,8 @@ "Inspect Lightroom Catalog": "Lightroom-ის კატალოგის შემოწმება", "Inspect Photo": "ფოტოს შემოწმება", "Inspecting Lightroom Catalog": "Lightroom-ის კატალოგი მოწმდება", + "Instagram Feed": "Instagram ფიდი", + "Instagram Story / Reel": "Instagram სთორი / რილსი", "Install Denoise Model": "ხმაურის მოცილების მოდელის ინსტალაცია", "Install Face Model": "სახეების მოდელის ინსტალაცია", "Install from file…": "ინსტალაცია ფაილიდან…", @@ -2252,6 +2255,7 @@ "Watched-folder auto import; Convert to DNG; Duplicate; Build Standard / 1:1 / Smart Previews.": "ავტოიმპორტი თვალთვალის ქვეშ მყოფი საქაღალდიდან; DNG-ად გარდაქმნა; დუბლირება; სტანდარტული / 1:1 / ჭკვიანი წინასწარი ხედების შექმნა.", "Watermark": "ჭვირნიშანი", "We": "ოთხ", + "Web / Portfolio": "ვებ / პორტფოლიო", "Wednesday": "ოთხშაბათი", "What's New": "რა არის ახალი", "When GPU rendering is on but no graphics processor can be found, LightCraft now says so once at start-up instead": "როცა GPU რენდერი ჩართულია, მაგრამ გრაფიკული პროცესორი ვერ მოიძებნა, LightCraft ახლა ამას გაშვებისას ერთხელ გეუბნებათ, ნაცვლად იმისა,", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index a67aed3ba6..44719aacbf 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -698,6 +698,10 @@ "Invert Component": "Odwróć składnik", "Invert Mask": "Odwróć maskę", "JPEG (Large)": "JPEG (duży)", + "Instagram Feed": "Instagram – kanał", + "Instagram Story / Reel": "Instagram Story / Reel", + "Web / Portfolio": "Web / portfolio", + "Full Resolution Master": "Master w pełnej rozdzielczości", "JPEG (Small)": "JPEG (mały)", "Join the ArtCraft Discord": "Dołącz do Discorda ArtCraft", "Join the ArtCraft Discord…": "Dołącz do Discorda ArtCraft…", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 43f89f051c..47c8098394 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -724,6 +724,10 @@ "Invert Component": "Inverter componente", "Invert Mask": "Inverter máscara", "JPEG (Large)": "JPEG (grande)", + "Instagram Feed": "Feed do Instagram", + "Instagram Story / Reel": "Story / Reel do Instagram", + "Web / Portfolio": "Web / Portfólio", + "Full Resolution Master": "Master em resolução total", "JPEG (Small)": "JPEG (pequeno)", "Join the ArtCraft Discord": "Entrar no Discord do ArtCraft", "Join the ArtCraft Discord…": "Entrar no Discord do ArtCraft…", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 4972f221d0..4bec3def29 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -794,6 +794,10 @@ "Invert": "Инвертировать", "Invert Mask": "Инвертировать маску", "JPEG (Large)": "JPEG (большой)", + "Instagram Feed": "Лента Instagram", + "Instagram Story / Reel": "Stories / Reels Instagram", + "Web / Portfolio": "Веб / портфолио", + "Full Resolution Master": "Мастер в полном разрешении", "JPEG (Small)": "JPEG (малый)", "Join the ArtCraft Discord": "Присоединяйтесь к Discord ArtCraft", "Join the ArtCraft Discord…": "Присоединиться к Discord ArtCraft…", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 12024b0ec2..f88ce066d7 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -1064,6 +1064,10 @@ "Join the ArtCraft Discord": "Gå med i ArtCraft på Discord", "Join the ArtCraft Discord…": "Gå med i ArtCraft på Discord…", "JPEG (Large)": "JPEG (stor)", + "Instagram Feed": "Instagram-flöde", + "Instagram Story / Reel": "Instagram-story / Reel", + "Web / Portfolio": "Webb / Portfölj", + "Full Resolution Master": "Master i full upplösning", "JPEG (Small)": "JPEG (liten)", "JPEG with the same name (`IMG_0001.CR3` + `IMG_0001.JPG`) no longer share one sidecar: the raw keeps `IMG_0001.xmp`,": "JPEG med samma namn (`IMG_0001.CR3` + `IMG_0001.JPG`) delar inte längre en sidofil: raw-filen behåller `IMG_0001.xmp`,", "Keep in Local": "Behåll i Lokalt", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index beb3e4b278..a2c3c9ea0d 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -806,6 +806,10 @@ "Instant ’70s": "Миттєві 70-ті", "Invert Component": "Інвертувати компонент", "JPEG (Large)": "JPEG (великий)", + "Instagram Feed": "Стрічка Instagram", + "Instagram Story / Reel": "Stories / Reels Instagram", + "Web / Portfolio": "Веб / портфоліо", + "Full Resolution Master": "Майстер у повній роздільності", "JPEG (Small)": "JPEG (малий)", "Join the ArtCraft community on Discord": "Приєднатися до спільноти ArtCraft у Discord", "Keywords (K)": "Ключові слова (K)", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 22e907f721..c0d3bfdbfb 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -889,6 +889,10 @@ "It tests this album, so testing it back would loop": "Nó kiểm tra album này, nên kiểm tra ngược lại sẽ tạo vòng lặp", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Ảnh đã khử nhiễu chưa được tạo, và ảnh không tự tạo (Cài đặt, AI Denoise).", "JPEG (Large)": "JPEG (Lớn)", + "Instagram Feed": "Bảng tin Instagram", + "Instagram Story / Reel": "Instagram Story / Reel", + "Web / Portfolio": "Web / Hồ sơ", + "Full Resolution Master": "Master độ phân giải đầy đủ", "JPEG (Small)": "JPEG (Nhỏ)", "JPEG with the same name (`IMG_0001.CR3` + `IMG_0001.JPG`) no longer share one sidecar: the raw keeps `IMG_0001.xmp`,": "JPEG cùng tên (`IMG_0001.CR3` + `IMG_0001.JPG`) không còn dùng chung một sidecar: raw giữ `IMG_0001.xmp`,", "Join the ArtCraft Discord": "Tham gia Discord ArtCraft", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 6b1c636724..c7201b9a56 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -832,6 +832,10 @@ "Invert": "反相", "Invert Mask": "反相蒙版", "JPEG (Large)": "JPEG(大)", + "Instagram Feed": "Instagram 动态", + "Instagram Story / Reel": "Instagram 快拍 / 短视频", + "Web / Portfolio": "网页 / 作品集", + "Full Resolution Master": "全分辨率母版", "JPEG (Small)": "JPEG(小)", "Join the ArtCraft Discord": "加入 ArtCraft Discord", "Join the ArtCraft Discord…": "加入 ArtCraft Discord…", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index ffcfaa6816..3b75e1ab6e 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -833,6 +833,10 @@ "Invert": "反轉", "Invert Mask": "反轉遮色片", "JPEG (Large)": "JPEG(大尺寸)", + "Instagram Feed": "Instagram 動態", + "Instagram Story / Reel": "Instagram 限時動態 / 短影片", + "Web / Portfolio": "網頁 / 作品集", + "Full Resolution Master": "全解析度母版", "JPEG (Small)": "JPEG(小尺寸)", "Join the ArtCraft Discord": "加入 ArtCraft Discord", "Join the ArtCraft Discord…": "加入 ArtCraft Discord…", diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 6220bcb3dd..b7f4a00e6d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -388,9 +388,33 @@ fn preferences_round_trip_and_old_settings_remain_readable() { assert_eq!(restored.language, Locale::ZhHans); } -/// Smart-album choice values read as words in every language (English "Public Domain"), never as -/// rule ids like `publicDomain`; an id the field doesn't know shows as written. A yes/no value -/// reads Yes / No, or the language's contextual entry for it where it has one. +#[test] +fn catalogs_contain_core_workflows() { + for language in Locale::ALL.iter().filter(|language| **language != Locale::En) { + for key in ["Import Photos…", "Export…", "Exposure", "White Balance", "Settings", "Language"] { + let value = language.tr(key); + assert!(!value.is_empty() && value != key, "{language:?}: {key}"); + } + } +} + +/// The built-in export presets' names show translated in the Export dialog (`builtin_label`), so +/// every catalog carries them. A translation may keep the English text, so this checks that an +/// entry exists: the catalog comparison only reports gaps, and a gap would show English silently. +#[test] +fn export_preset_names_are_translated_in_every_catalog() { + for language in Locale::ALL.iter().filter(|language| **language != Locale::En) { + for key in ["Instagram Feed", "Instagram Story / Reel", "Web / Portfolio", "Full Resolution Master"] { + assert!(language.catalog().contains_key(key), "{language:?} has no translation for {key:?}"); + } + } +} + +/// Smart-album choice values read as words in every language (English "Public Domain", German +/// "Gemeinfrei"), never as rule ids like `publicDomain`; an id the field doesn't know shows as +/// written. Unlike other labels these must be translated: an untranslated one would be English +/// in the middle of a translated rule. A yes/no value reads Yes / No, or the language's +/// contextual entry for it where it has one. #[test] fn choice_values_read_as_words_in_every_language() { use lightcraft_catalog::rules::{FIELDS, Kind, bool_label}; diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index e4a8463cdc..2186555517 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -390,7 +390,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| LR-EXP-DIALOG | Export dialog | P0 | ✅ | `cmd:dialog.export`, `cmd:app.export` (`preset`), `cmd:export.presets`, `cmd:export.savePreset`, `cmd:export.deletePreset`, `crates/ui-egui/src/dialogs.rs`, `crates/engine/src/export.rs` | batch export; built-in presets (JPEG Small 2048 px / Large full size, Original + Settings, DNG) and saved user presets (library prefs) load into the dialog; deleting a user preset is command-only; on a short window the options scroll and Cancel / Export stay visible (LR-BEHAV-DIALOGS, issue #781) | +| LR-EXP-DIALOG | Export dialog | P0 | ✅ | `cmd:dialog.export`, `cmd:app.export` (`preset`), `cmd:export.presets`, `cmd:export.savePreset`, `cmd:export.deletePreset`, `crates/ui-egui/src/dialogs.rs`, `crates/engine/src/export.rs` | batch export; built-in presets (JPEG Small 2048 px / Large full size, Original + Settings, DNG, Instagram Feed 1080 px, Instagram Story / Reel 1920 px long edge with no crop to 9:16, Web / Portfolio 2048 px copyright and creator metadata, Full Resolution Master full size P3) and saved user presets (library prefs) load into the dialog; deleting a user preset is command-only; on a short window the options scroll and Cancel / Export stay visible (LR-BEHAV-DIALOGS, issue #781) | | LR-EXP-TYPE | File types | P0 | ✅ | `cmd:app.export` (`format`), `crates/engine/src/export.rs` (`ExportFormat`), `crates/engine/src/tests/export.rs` | JPEG, PNG, TIFF, PSD (flat, 8/16-bit, no layers: `crates/codecs/src/psd.rs`), WebP, AVIF, JPEG XL (issue #247: `jixel`, native only; lossy with quality or lossless, 8/16-bit, effort fast/normal (jixel's slowest search left out: jxl-oxide misdecodes its files), progressive, EXIF/XMP boxes; lossy files in Adobe RGB / ProPhoto are written as Rec. 2020, lossless keep any space via ICC; `crates/codecs/src/jxl_encode.rs`), DNG (raw photos: lossless re-encode with the edits in the embedded XMP; a raw without colour matrices of its own, as a NEF, gets the colour it opens with as `ColorMatrix1` / `ForwardMatrix1` / `AsShotNeutral`, also in Convert / Copy as DNG, so other raw converters open it, issue #1745), Original (+ XMP sidecar). Non-raw → DNG not supported; no JPEG XL export in the web build. Opaque 8-bit PNG/TIFF/WebP exports omit the redundant alpha channel; real transparency is retained (#1670). | | LR-EXP-DIM | Output size | P0 | ✅ | `cmd:app.export` (`longEdge`, `shortEdge`, `width`, `height`, `fit`, `megapixels`, `percent`, `dontEnlarge`, `ppi`), `crates/engine/src/export.rs` (`Resize`), `crates/ui-egui/src/dialogs.rs` | full size = the cropped native size (no longer upscaled); both of Lightroom's boxes: Dimensions (W × H fits either orientation) and Width & Height (`fit: widthHeight`, each edge bound to its own number, #1620); ppi written to JFIF / pHYs / TIFF tags; at most 65,535 px an edge, and an export enlarged past the photo's size stops at 512 megapixels (Lightroom's ceiling too) and is refused, with the size it would need, when it needs more memory than the computer has (it aborted the process before) | | LR-EXP-QUALITY | JPEG quality | P0 | ✅ | `cmd:app.export` (`quality`, `limitKb`), `crates/codecs/src/jpeg_par.rs` | 4:4:4 chroma (4:2:0 when a file-size limit is set); Huffman tables made for each image from its own symbol counts (T.81 Annex K.2) instead of the example tables: the same pixels, 12–14 % smaller files at quality 80–100 on a 24 MP photo-like image, still interleaved baseline (issue #1373); ordinary and HDR gain map JPEGs search quality up to the requested maximum to fit `limitKb`, including gain map and metadata, or return an error. Tested by `size_limit_respected` and `hdr_jpeg_size_limit_respected`. | @@ -403,7 +403,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EXP-WATERMARK | Watermark | P1 | 🟡 | `cmd:app.export` (`watermark`: text, or `{text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}`), `crates/engine/src/export.rs` (`Watermark`, `WATERMARK_PARAMS`) | text uses Inter SemiBold, the existing Mincho-first CJK chain, then Thai faces from `CRAFT_FONTS_DIR`, shared with contact-sheet captions and slideshow overlays (#2052, partial). Decomposed (NFD) text, as macOS often writes file names, is composed to NFC first, so Hangul syllables and Vietnamese letters draw whole instead of as loose jamo and marks; CJK compatibility ideographs keep their code points (issue #3480, #3277; `decomposed_hangul_draws_whole_syllables`, `decomposed_vietnamese_draws_its_composed_letters`, `compatibility_ideographs_keep_their_code_points`). Horizontal Thai mark positioning remains incomplete. Arabic export fallback is deferred until joining and bidi reordering exist; UI font fallback is unchanged. Text (`size` = height as a fraction of the short edge, 0.005..0.5, default 0.035; `color` sRGB `[r,g,b]`; `shadow`; Japanese vertical glyph forms and origins, tested by `biz_ud_vertical_watermarks_place_punctuation_at_the_top_right`; extended grapheme cells keep decomposed dakuten/handakuten and Latin accents together, tested by `vertical_watermarks_keep_combining_marks_in_one_cell` and `upright_watermark_cell_retains_multiple_glyphs` (see `docs/vertical-watermarks.md`)) or a graphic with transparency (EXIF orientation applied before sizing; oversized graphics fit the rotated image bounds without stretching, tested by `graphic_watermark_honours_exif_orientation` and `graphic_watermark_keeps_aspect_when_fitted_and_rotated`; `image` path, `imageWidth` = fraction of the photo's width, 0.01..1, converted to the output colour space); `anchor` (nine positions), `insetX` / `insetY` (margins from the side and from the top/bottom edges, each a fraction of the short edge, 0..0.4; the Export dialog's Horizontal and Vertical inset sliders, as in Lightroom Classic; the older single `inset` still reads as both; tested by `watermark_insets_are_horizontal_and_vertical`), `rotation` (0, 90, 180 or 270 degrees clockwise, the Export dialog's Rotate row, as Lightroom Classic's rotate buttons; sized before it is turned, placed and inset by the turned box; tested by `watermark_rotation_turns_the_text_in_its_corner` and `graphic_watermark_is_placed_scaled_and_blended`), `opacity` 0..1. Unknown keys and out-of-range values are errors (issue #183). The Export dialog previews it on the first exported photo's thumbnail (`draw_watermark_preview` scales the 6 px minimum text size to the preview so it matches the file), tested by `watermark_preview_scales_the_minimum_text_size` and `export_dialog_previews_the_watermark` | | LR-EXP-NAMING | File naming | P1 | ✅ | `cmd:app.export` (`naming`, `startNumber`), `crates/engine/src/rename.rs` (`expand_tokens`) | one template language for export, Rename Photos and import renaming: `{name}`, `{num}` (number at the end of the name), `{seq}` / `{seq:N}`, `{date}` / `{date:%Y-%m-%d}`, `{folder}`, `{camera}`, `{lens}`, `{iso}`, `{rating}`, `{title}`, `{creator}`, `{ext}`; free-form template rather than a list of named schemes | | LR-EXP-LOCATION | Destination folder | P0 | ✅ | `cmd:app.export` (`dir`, `destinationMode`: specificFolder / sameAsOriginal, `subfolder`, `conflict`: unique / overwrite / skip), `cmd:export.checkTarget`, `crates/ui-egui/src/dialogs.rs` (Choose… folder picker), `crates/engine/src/originals.rs`, `crates/catalog/src/safe_file.rs` | folder picker on the desktop; Export to: Specific folder or Same folder as original photo (each photo into its original's folder + the subfolder; a demo/browser photo or a missing folder is that photo's error, issue #956); existing files get `-2`, `-3`… by default; the policy covers a file and its sidecars together; a catalogued original (or its sidecar) is never written over, whatever the policy or an exact `path` (export, `ui.render`, MCP `render_photo`, merge `previewPath`, `lightcraft-cli render`); files are written to a temp file and renamed into place (issue #93; not synced file by file — exports can be made again, issue #134) | -| LR-EXP-PREVIOUS | Export with previous settings | P0 | ✅ | `cmd:app.exportPrevious`, `cmd:dialog.export` | last options persist in prefs.json; dialog prefilled; no named export presets yet | +| LR-EXP-PREVIOUS | Export with previous settings | P0 | ✅ | `cmd:app.exportPrevious`, `cmd:dialog.export` | last options persist in prefs.json; dialog prefilled; named export presets live in LR-EXP-DIALOG | | LR-EXP-DNGOPT | DNG options | P2 | 🟡 | `cmd:app.export` (`dngCompression`), `crates/engine/src/export.rs` | compression: lossless JPEG (default), ZIP, none, or lossy (demosaiced linear camera RGB as 8-bit JPEG tiles at the export quality, a `LinearizationTable` restoring linear values, scaled to the resize long edge when set; `crates/raw/tests/it/lossy_dng.rs`); no embedded JPEG preview size | | LR-EXP-ORIGINAL | Original + XMP | P1 | ✅ | `cmd:app.export` (`format: original`), `crates/engine/src/tests/export.rs` | file copied byte for byte, sidecar named after the output and subject to the conflict policy | | LR-EXP-RENDERDNG | Render to DNG (Classic 15.5) | P2 | 🟡 | `cmd:app.export` (`format: rendereddng`), `crates/raw/src/dngwrite.rs` (`write_rendered_dng`), `crates/raw/tests/it/rendered_dng.rs` | export format `rendereddng` (dialog: Format DNG, "DNG of: Rendered photo"): the rendered photo (edit, crop, size, sharpening, watermark baked in) as a LinearRaw DNG of 16-bit float Deflate tiles in the export colour space, with `ColorMatrix1` / `ForwardMatrix1` for that space, a neutral `AsShotNeutral` and an identity `ProfileToneCurve` so raw converters show it as rendered; HDR edits keep highlights above white. Not a menu command on selected photos (Lightroom adds the DNG to the catalog next to the original); export only | @@ -822,14 +822,11 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-24 | minor | KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K (`panel.editKeywords`, Edit Keywords) shows the Keywords panel with its Keyword List open and opens the picked keyword in Edit Keyword Tag; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-29 | minor | LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket, with sharper raw fallback and the available camera JPEG retained when rendering cannot help (#2237, part of #2056); import loupe remains open; counts unchanged | | 2026-10-25 | minor | LRC-LIB-CATALOG-SWITCH: a library's `catalog.snap` or folder given at launch (double-clicked in Explorer or Finder) opens that library instead of the last one, and is never imported as photos; status unchanged (✅) | -| 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged | | 2026-10-25 | patch | LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence reservation; exhausted later files are reported failed while earlier transfers remain accounted for; status counts unchanged | | 2026-10-25 | patch | LR-META-XMP and LRC-MAP-TRACKLOG reject incomplete ISO timestamps: XMP capture-time fallback remains available and malformed GPX times are untimed; status and feature counts unchanged | | 2026-10-27 | patch | MENU-BAR: every shortcut the app shows (a menu row, a button's tooltip, a hint, the empty-album line, the Keyboard Shortcuts dialog) lists its modifiers on macOS in the menu bar's order, ⌃⌥⇧⌘ (`⇧⌘I`, not `⌘⇧I`); the empty-album line follows the keymap; status counts unchanged | -| 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged | | 2026-10-25 | patch | LR-IMP-FORMATS: JPEG ICC APP2 chunk sequences are validated before colour conversion; valid reordered chunks remain supported and malformed profiles use the existing sRGB fallback; status unchanged (🟡) | | 2026-10-13 | minor | LR-IMP-FORMATS / LR-IMP-CAMERA-COVERAGE: Canon CRW decodes (clean-room; 6 bodies pixel-exact, G5 preview-only) | -| 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged | | 2026-10-26 | minor | LR-IMP-FORMATS: the Canon CRW decoder moved to craft-libs as `craft-crw` (path dependency until that branch merges); `crates/raw/src/vendor/crw.rs` is the adapter, the clean-room record lives in craft-libs (crates/crw/clean-room there) | | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | @@ -838,8 +835,6 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-24 | patch | Integration batch 43: Integrated main 98702b5c, preserving the new fail-closed GPS metadata check for Original export. Watermark geometry/orientation and HDR JPEG size-limit fixes remain in their shared helpers; no feature-count changes. | | 2026-10-23 | minor | LR-FILT-FLAG, LRC-LIB-FILTERBAR: the filter bar's flag toggles combine (any of them, `library.filter` `flags`), issue #2588; status and counts unchanged | | 2026-10-24 | patch | LR-EXP-METADATA: Original export refuses embedded GPS or nonblank place names when Remove Location Info is on; status and feature counts unchanged | -| 2026-10-24 | patch | LR-LIB-RATING, LR-LIB-DELETE: a slider drag still open when a rating, flag or label takes the photo out of the view, or when the photo is deleted, ends as its own undo step before the selection moves on, as moving to the next photo does; LR-BEHAV-LOCALIZE lists all 18 languages; status unchanged | -| 2026-10-24 | patch | Integration batch 43: Integrated main 98702b5c, preserving the new fail-closed GPS metadata check for Original export. Watermark geometry/orientation and HDR JPEG size-limit fixes remain in their shared helpers; no feature-count changes. | | 2026-10-23 | patch | LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the merge dialog makes a new preview each time it opens, also after a failed one (#2708); status unchanged | | 2026-10-23 | patch | LR-VIEW-HISTOGRAM: the histogram stays at the top of the Edit panel while its sliders scroll (#2679); status unchanged | | 2026-10-23 | patch | Export integration: Integrated main 5ca49b3e, retaining Width & Height resizing, export format/bit-depth validation and batch panic cancellation alongside the existing watermark and HDR JPEG size-limit fixes. No feature-count changes. | @@ -907,7 +902,6 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-14 | patch | LR-META-XMP: automatic sidecar writes that fail (folder offline or read-only) wait and are written again once the files are reachable, with a notice (`cmd:library.retrySidecars`); status unchanged | | 2026-10-13 | minor | LR-BEHAV-WINDOW (new, 🟡): the desktop app's window opens at the size it was left at, zoomed / maximized if it was; full screen and the place on the desktop are not remembered | | 2026-10-14 | minor | LR-IMP-CAMERA-COVERAGE: Nikon D600, D610 and D5000 NEFs drop the filler and noise columns on the right (a band), and the D600 and D610 measure their white level inside the image (#1627); status unchanged (🟡) | -| 2026-10-15 | patch | LR-VIEW-BEFOREAFTER: side by side and stacked panes share click-zoom animation for whole-frame images, window tiles and input; render requests keep the final target (#1821); status unchanged | | 2026-10-14 | patch | LR-MASK-BRUSH: ⇧-click with the brush draws a straight stroke from where the last stroke ended, tapering when the brush changed in between (`cmd:mask.brushStroke` `connect`); status unchanged | | 2026-10-14 | minor | LR-VIEW-ZOOM 🟡 → ✅: soft proofing gets zoom windows (mask overlays already had them; row text corrected), 1:1 pixels tested equal to the full-size export, slider-drag latency at 1:1 measured on Linux | | 2026-10-14 | patch | LR-IMP-LOCAL: browsing a folder from the sidebar records it as browsed, as `library.browse` does, so its untouched photos aren't forgotten while in use; status unchanged (✅) | @@ -1030,8 +1024,6 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-28 | patch | LR-BEHAV-ACCESS: the photo in Detail view is named with its file name, rating, flag and label (`Photo: `) for screen readers, as the grid names it, instead of "Photo"; status stays 🟡 | | 2026-10-28 | patch | LR-BEHAV-ACCESS: the grid's Thumbnail size control is a slider to screen readers, with its value and range, and takes Increment / Decrement and the Up / Down keys; status stays 🟡 | | 2026-10-28 | patch | LRC-LIB-FOLDERS: Local's standard places (Pictures, Desktop, Downloads, Home) no longer offer Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; the prompt started with the translated label, so confirming it in another language renamed the real folder to that word; a folder kept with Browse Folder… still renames from its real name; status unchanged (✅) | -| 2026-10-27 | patch | MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Select Only Active Photo and Paste Settings from Previous were not in the Edit menu's layout and ended up after Settings…, near the end of the menu; they now sit with the other Select and Paste rows. On macOS the Edit menu no longer shows two separators in a row where Settings… moved to the app menu; status unchanged (✅) | -| 2026-10-27 | patch | MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say that Close Window and the red close button of the main window quit the app, after the check Quit makes; kept on purpose; a user page says so; status unchanged (✅) | | 2026-10-24 | patch | LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started, so a move that is refused no longer switches the question off; status unchanged (✅) | | 2026-10-24 | patch | LR-IMP-ADD-DIALOG: an import checks that each file a scan already probed is as it was up to 16 files at a time (an import batch's files, at most) instead of one after another, and looks up a batch's sidecars the same way (`import::sidecars_of`); on a network share a folder of thousands of photos spent most of its import time waiting for those checks; status unchanged (✅) | | 2026-10-23 | minor | LR-BEHAV-LOCALIZE: panel layout toasts, the face recognition prompts and toasts, and the second window's title are looked up in the interface language in all 17 catalogs; status unchanged (🟡) | @@ -1047,4 +1039,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-29 | patch | LR-BEHAV-TITLEBAR: a dialog's backdrop leaves the integrated title bar undimmed, as a macOS sheet does (the bar's controls stay inactive, a click on it is not a click outside the dialog, dragging its empty space still moves the window); status unchanged (🟡) | | 2026-10-29 | minor | LR-MASK-OBJECTS: an Object / Describe selection's stored grid is enlarged along the photo's edges (fast guided filter of its logits by log luminance, a 1.5-cell window), so a raised Exposure no longer draws an outline around the subject (#3272); existing AI masks are 1–2 px tighter at edges; status unchanged (🟡) | | 2026-10-30 | patch | LR-MASK-COLORRANGE: a colour-range mask keeps its first 64 samples however it is loaded (sidecar `lc:settings`, presets, `develop.merge`, `render --settings`, catalog and history), not only through `mask.add` / `mask.update`, so a document with thousands can't stall a render or lose the GPU device (issue #2556); status unchanged (✅) | +| 2026-10-17 | minor | LR-EXP-DIALOG: built-in export presets for the issue #2104 delivery targets — Instagram Feed (1080 px, screen sharpening), Instagram Story / Reel (1920 px), Web / Portfolio (2048 px, copyright-only metadata), Full Resolution Master (full size, Display P3, quality 95); LR-EXP-PREVIOUS drops its stale "no named export presets yet" note; status unchanged (✅) | +| 2026-10-17 | minor | LR-EXP-DIALOG: built-in export presets for the issue #2104 delivery targets — Instagram Feed (1080 px, screen sharpening), Instagram Story / Reel (1920 px), Web / Portfolio (2048 px, copyright and creator metadata), Full Resolution Master (full size, Display P3, quality 95); LR-EXP-PREVIOUS drops its stale "no named export presets yet" note; status unchanged (✅) | +| 2026-10-20 | patch | LR-EXP-DIALOG: the four built-in export presets are translated in all 17 catalogs (translations pending native-speaker review); Instagram Story / Reel states that it applies no crop to 9:16; status unchanged (✅) | | 2026-10-31 | patch | LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread under an activity row with ✕ instead of on the UI thread, where a large library left the window not responding (#3468). A stopped search leaves the view as it was and keeps what it read; a control request gets the same `{photos}` when the search ends. | From ef7f99d12fe5d28d8992c6a47fc23c8ed684eedf Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 22:12:00 +0200 Subject: [PATCH 08/24] Add GFX100S II to the spectral camera matrix table (#3139) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GFX100S II is a current Fujifilm body with no measured-matrix path, so any photo its JPEG fit does not accept falls to the neutral fallback instead of step 4's matrices. A unit test pins spectral::find to GFX 100's matrix for this model, following the existing GFX100S → GFX 100 same-sensor pattern. Add ("Fujifilm", "GFX100S II", "GFX 100") to SAME_SENSOR next to the other Fujifilm same-sensor rows, plus a unit test asserting the lookup returns GFX 100's matrices (fails today, passes after the edit). Test: gfx100s_ii_uses_gfx_100_matrices failed before the change and passes after. Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/raw/src/spectral.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/raw/src/spectral.rs b/crates/raw/src/spectral.rs index 6c4e7c46ce..95e4cc6f4b 100644 --- a/crates/raw/src/spectral.rs +++ b/crates/raw/src/spectral.rs @@ -47,10 +47,12 @@ impl Camera { } } -/// `(make, model as sold, table model)`: bodies sharing a table camera's sensor that rawtoaces-data's alias list +/// `(make, model as sold, table model)`: bodies using a table camera's data that rawtoaces-data's alias list /// doesn't name, kept here because the table is generated. Fujifilm's 26.1 MP X-Trans CMOS 4 bodies use the X-T3's /// or X-T4's sensor (X-T30 issue: a black-and-white Acros camera JPEG gives no colour to fit, and without matrices the photo /// opened in the muted neutral fallback). +/// The GFX100S II has no measured data of its own: it borrows the GFX 100's matrices as the nearest medium-format +/// body in the table, which is closer than the neutral camera-RGB-approximately-sRGB fallback but not its own sensor. const SAME_SENSOR: &[(&str, &str, &str)] = &[ ("Fujifilm", "X-T30", "X-T3"), ("Fujifilm", "X-T30 II", "X-T3"), @@ -60,6 +62,7 @@ const SAME_SENSOR: &[(&str, &str, &str)] = &[ ("Fujifilm", "X-E4", "X-T3"), ("Fujifilm", "X-S20", "X-T4"), ("Fujifilm", "X-M5", "X-T3"), + ("Fujifilm", "GFX100S II", "GFX 100"), ]; /// Model names compared without case, the brand, a leading `EOS` or a trailing `DIGITAL` @@ -178,6 +181,13 @@ mod tests { } } + #[test] + fn gfx100s_ii_uses_gfx_100_matrices() { + // GFX100S II is not in the table, so its raws never get step 4's measured matrices + // and fall back to step 5's neutral camera-RGB-approximately-sRGB. + assert_eq!(find(Some("FUJIFILM"), "GFX100S II").map(|c| c.model), Some("GFX 100"),); + } + #[test] fn other_cameras_and_other_makes_find_nothing() { assert_eq!(find(Some("Canon"), "Canon EOS 7D"), None); From 098c9294aa49942720d62c89355f3931f8e8d00f Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 22:25:37 +0200 Subject: [PATCH 09/24] shortcuts: H toggles mask pins while masking (#1458) * shortcuts: H toggles the mask pins while masking In the Masking panel an unmodified H press runs view.maskPins (the same switch as View > Show Mask Pins) instead of opening Remove; a Remove key reassigned to anything else keeps opening Remove there, and outside Masking H still opens Remove. * shortcuts: test the H mask-pin toggle H toggles the mask pins while the Masking panel is open and does not open Remove there; from the other panels it still opens Remove and leaves the pins alone. * shortcuts: keep the H docs truthful In the Masking panel an unmodified H toggles the mask pins and does not open Remove, a Remove key reassigned to anything else still opens Remove there, and outside Masking H still opens Remove, so the Hide pins row moves from done to partial: Remove's spot pins have no hide toggle. The H comparison row, the revision histories and the parity summary are updated to match. --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/ui-egui/src/shortcuts.rs | 24 +++++- crates/ui-egui/src/tests/keymap.rs | 128 ++++++++++++++++++++++++++++- docs/parity-checklist.md | 3 +- docs/ui-parity.md | 9 +- 4 files changed, 157 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 07cfe8ba03..9ab12fe079 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -388,22 +388,37 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { if keyboard_owned(app, ctx) || app.recording_shortcut.is_some() || app.ui.name_edit.is_some() { return; } - let (fire, aliased) = pressed_commands(app, ctx); + let (mut fire, aliased, h_press) = pressed_commands(app, ctx); for (id, params) in aliased { fire_alias(app, ctx, id, params); } + // while the Masking panel is open, an unmodified H that no assignment has claimed toggles the + // mask pins (the View ▸ Show Mask Pins switch) instead of opening Remove; the full-screen + // preview shows no panels and a minimized window hides the panel, so there H keeps its own + // binding + if h_press + && app.ui.right == crate::state::RightPanel::Masking + && !app.ui.fullscreen + && crate::docking::exposed(app, crate::docking::Panel::Tools) + { + let _ = app.run("view.maskPins", json!({})); + fire.retain(|f| f != "panel.remove"); + } let rotate_fires = fire.iter().any(|f| f == "crop.rotateAspect"); for f in fire { fire_command(app, ctx, &f, rotate_fires); } } -/// The keys pressed this frame: the commands to fire, and the aliases (command and params) to run. -fn pressed_commands(app: &LightcraftApp, ctx: &egui::Context) -> (Vec, Vec<(&'static str, serde_json::Value)>) { +/// The keys pressed this frame: the commands to fire, the aliases (command and params) to run, and +/// whether an unmodified H that no keymap assignment has claimed was pressed (the Masking panel's +/// pin toggle, see `handle`). +fn pressed_commands(app: &LightcraftApp, ctx: &egui::Context) -> (Vec, Vec<(&'static str, serde_json::Value)>, bool) { let mut fire: Vec = Vec::new(); // shortcuts the native menu bar handles (it consumes those key presses itself) let native = |sc: &str| app.native_shortcuts.contains(sc); let mut aliased: Vec<(&'static str, serde_json::Value)> = Vec::new(); + let mut h_press = false; let keymap = &app.ui.settings.keymap; let grid = library_grid(app); // The grid navigation keys act on the photos in view, so they wait while the full-screen preview @@ -459,8 +474,9 @@ fn pressed_commands(app: &LightcraftApp, ctx: &egui::Context) -> (Vec, V } } fixed_photo_keys(i, &native, &taken, grid_navigation, &mut fire); + h_press = matches(i, Modifiers::NONE, Key::H) && !native("H") && !taken.contains(&(Modifiers::NONE, Key::H)); }); - (fire, aliased) + (fire, aliased, h_press) } /// The fixed photo keys pressed: ratings 0-5, colour labels 6-9 (with Shift: and advance), and in a grid the diff --git a/crates/ui-egui/src/tests/keymap.rs b/crates/ui-egui/src/tests/keymap.rs index 6e784de1a4..71adfca8bc 100644 --- a/crates/ui-egui/src/tests/keymap.rs +++ b/crates/ui-egui/src/tests/keymap.rs @@ -1,13 +1,15 @@ //! Headless tests of the editable keymap (Help ▸ Keyboard Shortcuts): a changed shortcut fires //! its command and not the old one's, the editor records a key press without running it, Esc //! cancels recording without closing the dialog, and the keymap survives a save/load of `ui.json`. +//! It also covers the H key: H toggles the mask pins while the Masking panel shows (it opens +//! Remove everywhere else, and only an unmodified H does). use std::time::Duration; use serde_json::json; use crate::headless::Headless; -use crate::state::{Dialog, ViewMode}; +use crate::state::{Dialog, RightPanel, ViewMode}; use crate::{LightcraftApp, Services}; const T: Duration = Duration::from_secs(20); @@ -567,3 +569,127 @@ fn a_is_the_aspect_lock_under_crop_and_visualize_spots_elsewhere() { assert!(h.app.ui.visualize_spots, "Visualize Spots is on"); assert_eq!(aspect(&h), before, "and the aspect is untouched"); } + +/// Open the right-hand panel `command` and check it is the active one. +fn open_panel(h: &mut Headless, command: &str, panel: RightPanel) { + // the panel commands toggle: don't switch off a panel that is already open + if h.app.ui.right != panel { + h.app.run(command, json!({})).unwrap(); + } + h.step(); + h.step(); + assert_eq!(h.app.ui.right, panel, "{command}"); +} + +/// H toggles the mask pins while the Masking panel shows; it opens Remove everywhere else. +#[test] +fn h_toggles_the_mask_pins_while_masking() { + let mut h = demo(); + open_panel(&mut h, "panel.masking", RightPanel::Masking); + assert!(h.app.ui.mask_pins, "pins are shown by default"); + key(&mut h, "H", false); + assert!(!h.app.ui.mask_pins, "H hides the pins"); + key(&mut h, "H", false); + assert!(h.app.ui.mask_pins, "H shows them again"); + // the same toggle as View ▸ Show Mask Pins + h.app.run("view.maskPins", json!({"show": false})).unwrap(); + key(&mut h, "H", false); + assert!(h.app.ui.mask_pins); +} + +#[test] +fn h_while_masking_does_not_open_remove() { + let mut h = demo(); + open_panel(&mut h, "panel.masking", RightPanel::Masking); + for _ in 0..2 { + key(&mut h, "H", false); + assert_eq!(h.app.ui.right, RightPanel::Masking, "H stays in Masking"); + assert_ne!(h.app.ui.tool, "remove"); + } +} + +#[test] +fn h_opens_remove_when_another_panel_is_active() { + for (command, panel) in [("panel.edit", RightPanel::Edit), ("panel.crop", RightPanel::Crop), ("panel.redeye", RightPanel::RedEye)] { + let mut h = demo(); + open_panel(&mut h, command, panel); + let pins = h.app.ui.mask_pins; + key(&mut h, "H", false); + assert_eq!(h.app.ui.right, RightPanel::Remove, "H from {panel:?}"); + assert_eq!(h.app.ui.tool, "remove"); + assert_eq!(h.app.ui.mask_pins, pins, "H outside Masking leaves the pins alone"); + } +} + +/// Remove stays on whatever key the keymap gives it: only an unmodified H press is overridden in +/// Masking, so a reassigned Remove key still opens Remove there and leaves the pins alone. +#[test] +fn a_remapped_remove_key_still_opens_remove_while_masking() { + let mut h = demo(); + let r = h.app.run("app.setShortcut", json!({"id": "panel.remove", "shortcut": "J"})).unwrap(); + assert_eq!(r["shortcut"], "J", "{r}"); + open_panel(&mut h, "panel.masking", RightPanel::Masking); + let pins = h.app.ui.mask_pins; + key(&mut h, "J", false); + assert_eq!(h.app.ui.right, RightPanel::Remove, "the reassigned Remove key opens Remove in Masking"); + assert_eq!(h.app.ui.tool, "remove"); + assert_eq!(h.app.ui.mask_pins, pins, "the reassigned key leaves the pins alone"); +} + +/// H stays the mask-pin key while Masking is open even after Remove moved to another key: only an +/// explicit assignment of H itself takes the toggle away. J keeps opening Remove, and outside +/// Masking the now unbound H does nothing. +#[test] +fn h_still_toggles_the_pins_when_remove_moves_to_another_key() { + let mut h = demo(); + h.app.run("app.setShortcut", json!({"id": "panel.remove", "shortcut": "J"})).unwrap(); + open_panel(&mut h, "panel.masking", RightPanel::Masking); + assert!(h.app.ui.mask_pins, "pins are shown by default"); + key(&mut h, "H", false); + assert!(!h.app.ui.mask_pins, "H toggles the pins after Remove moved away"); + key(&mut h, "H", false); + assert!(h.app.ui.mask_pins); + assert_eq!(h.app.ui.right, RightPanel::Masking, "H does not open Remove"); + // J keeps opening Remove while Masking is open + key(&mut h, "J", false); + assert_eq!(h.app.ui.right, RightPanel::Remove, "J opens Remove"); + assert_eq!(h.app.ui.tool, "remove"); + // outside Masking the unbound H does nothing + open_panel(&mut h, "panel.edit", RightPanel::Edit); + key(&mut h, "H", false); + assert_eq!(h.app.ui.right, RightPanel::Edit, "unbound H does nothing outside Masking"); + assert!(h.app.ui.mask_pins, "and it leaves the pins alone"); +} + +/// The full-screen preview shows no panels (the Masking panel state stays behind it): H keeps +/// opening Remove there instead of toggling the invisible panel's pins. +#[test] +fn h_keeps_its_binding_in_the_full_screen_preview() { + let mut h = demo(); + open_panel(&mut h, "panel.masking", RightPanel::Masking); + h.app.run("view.fullScreenPreview", json!({})).unwrap(); + assert!(h.app.ui.fullscreen); + key(&mut h, "H", false); + assert!(h.app.ui.fullscreen, "H does not leave the full-screen preview"); + assert_eq!(h.app.ui.right, RightPanel::Remove, "H opens Remove in the full-screen preview"); + assert_eq!(h.app.ui.tool, "remove"); + assert!(h.app.ui.mask_pins, "the pins are untouched"); +} + +/// A minimized Tools window hides the Masking panel (the panel state stays Masking behind it): +/// H keeps opening Remove there instead of toggling the invisible panel's pins. +#[test] +fn h_keeps_its_binding_when_the_masking_panel_is_not_exposed() { + use crate::docking::Panel; + let mut h = demo(); + open_panel(&mut h, "panel.masking", RightPanel::Masking); + h.app.run("ui.dock", json!({"operation": "float", "panel": "tools", "rect": [400, 100, 320, 500]})).unwrap(); + h.app.run("ui.dock", json!({"action": {"SetMinimized": {"panel": "tools", "minimized": true}}})).unwrap(); + h.step(); + assert_eq!(h.app.ui.right, RightPanel::Masking, "the panel state stays Masking"); + assert!(!crate::docking::exposed(&h.app, Panel::Tools), "the minimized window hides the panel"); + key(&mut h, "H", false); + assert_eq!(h.app.ui.right, RightPanel::Remove, "H opens Remove while the panel is hidden"); + assert_eq!(h.app.ui.tool, "remove"); + assert!(h.app.ui.mask_pins, "the pins are untouched"); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 2186555517..e8c0e1a709 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -684,7 +684,7 @@ From `06-shortcuts.md` part 1. Evidence is our binding; conflicts are explained | KEY-ESC | Leave tool / view — Esc | P0 | ✅ | `cmd:view.back`, `crates/ui-egui/src/icons.rs` (`navigation_arrowheads_have_both_halves`), `crates/ui-egui/src/tests/crop_tool.rs` | top-bar navigation arrowheads render both halves at 1× and 2× scale; in the crop tool Esc closes the tool first (the crop stays), the next Esc goes back to the grid; Esc that ends an edit in a text field does nothing else | | KEY-COMMIT | Commit tool — Return | P1 | ✅ | `cmd:tool.done` | Return closes Crop / Remove / Red Eye / Masking back to Edit (edits apply live, as in Lightroom) | | KEY-DELETE-PIN | Delete selected pin — ⌫ | P0 | ✅ | `cmd:mask.delete`, `cmd:spot.delete` | ⌫ deletes the active mask (Masking) or the selected spot (Remove), never the photo while retouching | -| KEY-HIDEPINS | Hide pins — H | P2 | ✅ | `cmd:view.toolOverlay`, `crates/ui-egui/src/tests/tool_overlay.rs` | ⇧H cycles the Tool Overlay (Auto → Always → Selected → Never) for spot and mask pins, since H opens Remove; also View ▸ Tool Overlay and the Remove / Masking panels (#224) | +| KEY-HIDEPINS | Hide pins — H | P2 | 🟡 | `cmd:view.toolOverlay`, `cmd:view.maskPins`, `cmd:panel.remove`, `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/tests/tool_overlay.rs`, `crates/ui-egui/src/tests/keymap.rs` (`h_toggles_the_mask_pins_while_masking`, `h_while_masking_does_not_open_remove`, `h_opens_remove_when_another_panel_is_active`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`, `h_keeps_its_binding_in_the_full_screen_preview`, `h_keeps_its_binding_when_the_masking_panel_is_not_exposed`) | ⇧H cycles the Tool Overlay (Auto → Always → Selected → Never) for spot and mask pins; also View ▸ Tool Overlay and the Remove / Masking panels (#224). In the visible Masking panel an unmodified H itself toggles the mask pins (the same switch as View ▸ Show Mask Pins) and does not open Remove; the toggle yields only to an explicit assignment of H itself, and a Remove key reassigned to anything else still opens Remove there. Outside Masking — and wherever no panel shows (the full-screen preview, a minimized or hidden panel) — H keeps its own binding (Remove, by default). Remove's spot pins have no H hide toggle (⇧H only), so the row is partial | ## Lightroom Classic extras @@ -801,6 +801,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) | | 2026-11-05 | minor | LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V5 rolls a raw's tone curve off into white in stops, past a camera curve's last knot and from half a stop below the generic curve's white point, so raising Exposure no longer turns recorded highlights white (#1632); statuses and counts unchanged | | 2026-11-05 | minor | LR-LIB-PEOPLE: face boxes another app drew on the photo as stored land on the upright photo (#2674) | | 2026-11-02 | minor | LRC-DEV-AUTOSYNC (N-A3, note 18): Auto Sync carries white balance as a mode or on each photo's own scale: As Shot and Auto per photo (were the active photo's numbers), a Temp move keeps each photo's tint, the same number on photos of the same scale, a photo of another scale (a JPEG beside a raw) moves by as much; Sync Settings unchanged; status unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a0932f2f4a..a771673237 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -65,7 +65,7 @@ auto-repeat used to flip the zoom back and forth (`crates/ui-egui/src/space_hand | Expand/collapse edit sections | ⌘⌥1–5 | ⌘1–6 | ⌘0 = Zoom to Fit, ⌘1 = Zoom 100 %; Geometry lives in the Crop panel | | Histogram | ⌘⇧H | ⌘0 | ⌘0 = Zoom to Fit | | Square Grid | ⇧G | (none; ⇧G = Guided Upright) | Guided Upright is a button in the Crop panel | -| Hide / show pins (Tool Overlay) | ⇧H (cycles Auto, Always, Selected, Never) | H (Classic) | H opens Remove; View ▸ Tool Overlay and the Remove / Masking panels pick a mode | +| Hide / show pins (Tool Overlay) | ⇧H (cycles Auto, Always, Selected, Never); H toggles the mask pins while the Masking panel shows | H (Classic) | elsewhere H opens Remove, a reassigned Remove key still opens Remove in Masking, and the pin toggle yields only to an explicit assignment of H itself; View ▸ Tool Overlay and the Remove / Masking panels pick a mode | | Export dialog | ⌘⇧E (+ ⇧E) | ⇧E | ⌘⇧E is "Edit in Photoshop" there; no external-editor command yet | | Crop overlay cycle | ⇧O | O | O = mask overlay; ⇧O (mask colour / overlay orientation) unused otherwise | | Create Version | ⌘⇧S (+ ⇧M) | ⇧M (Windows: Ctrl+⇧S) | — | @@ -99,6 +99,12 @@ default, also some GNOME / Xfce setups) the window manager takes the drag first: **Still missing / broken:** - Tab / ⇧Tab (hide the side panels / all panels): Tab moves the keyboard focus here (accessibility), so it is not bound; F5 (hide the top panel) is not bound either. +- `H` toggles the mask pins while the Masking panel shows (the same switch as View → Show Mask Pins) and opens Remove everywhere + else — wherever no panel shows (the full-screen preview, a minimized or hidden panel), H keeps its own binding and opens Remove there + too. Only an unmodified H toggles, and it yields only to an explicit assignment of H itself: a Remove key reassigned in Help → Keyboard + Shortcuts still opens Remove while the Masking panel shows. + Lightroom (Classic) uses H to hide the pins of every local tool. ⇧H still cycles the Tool Overlay (#224), which hides + the Remove tool's spot pins that way. - ⌘M / ⌘H / ⌘Q / ⌘W rely on the platform window defaults (unverified). @@ -172,6 +178,7 @@ establish OS keyboard delivery or cross-platform acceptance. | Date | Change | Summary | |---|---|---| +| 2026-10-28 | minor | Shortcuts: in the Masking panel H toggles the mask pins (the same switch as View → Show Mask Pins) instead of opening Remove; only an unmodified H toggles and it yields only to an explicit assignment of H itself, a Remove key reassigned in Help → Keyboard Shortcuts still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default) | | 2026-10-24 | minor | KEYC-METADATA: ⌘⌥K / Ctrl+Alt+K (Photo ▸ Enable Painting) paints the painter box's keyword, stops painting when pressed again, and with the box empty opens the Keywords panel | | 2026-10-24 | minor | KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K (Edit Keywords) opens the keyword picked in the Keyword List in Edit Keyword Tag | | 2026-10-25 | minor | KEYC-METADATA: ⌘⌥⇧K / Ctrl+Alt+Shift+K (Set Keyword Shortcut) and ⇧K add and remove the keyword shortcut's keywords; the Keyword List marks them with a + | From 1b6e722292befa8924147196ea501ff72de812e6 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 22:32:03 +0200 Subject: [PATCH 10/24] Import review: say what the folder scan left out (#2944) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * LR-IMP-ADD-DIALOG: a folder scan counts the folders it could not read and the files it skipped The bounded folder walk used to drop a folder it could not list, and every file its caller refused, without a trace. It now counts both (Walked::unreadable and Walked::skipped); which files are returned, their order, the limits and the handling of links are unchanged, and the Limits struct is untouched. import::expand_report keeps those counts with the walk's truncation flag (Expansion); expand_within delegates to it. ScanOutput carries truncated, unreadable and unsupported, filled by scan_with, and scan_report gives the session-backed scan the same output while storing the probes for the import that follows exactly as scan does. library.importPreview returns truncated and skipped {unreadable, unsupported} next to the keys it already had, and says so in its description. A walk that stops at a bound is still logged once, in expand_report, as before. * LR-IMP-ADD-DIALOG: tests for the scan's skipped, unreadable and truncated counts The walk counts files its caller refuses (and not hidden files or the skipped folder) and a folder that vanishes before it is entered. expand_report, scan_with and library.importPreview report unsupported files, a walk cut at the depth limit and an unlistable folder, keep the probes for the import, and leave a file named on its own uncounted. The unlistable folder uses no permissions on Unix and a deny entry on Windows, and does nothing where the process can list it anyway. * LR-IMP-ADD-DIALOG: the import review says when its scan left something out When the folder scan stopped at the walk limit, could not read some folders, or skipped files that are not a supported photo type, the review now shows one line under the count (for example "Stopped at the scan limit: there may be more photos · 2 folders could not be read · 3 files skipped (not a supported photo type)"). It shows nothing when the scan left nothing out. The counts come from the scan's output and are kept on the dialog. The two messages with a count go in every formats catalog, as the build requires, and the plain message in every plain catalog. * LR-IMP-ADD-DIALOG: tests for the import review's scan note Opening the review for a folder with a stray text file, for a tree deeper than the walk goes, and for a folder of photos only shows the matching line, or none. The line follows the counters while the review is open, is written in the language in use, and names singular and plural counts correctly. * LR-IMP-ADD-DIALOG: tracker note for the import review's scan note The row says what the review reports when its scan left something out, what library.importPreview returns for it, and which other folder walks do not report these counts. Revision history and last-updated line added; the status stays done and the generated summary is not touched. * LR-IMP-ADD-DIALOG: XMP sidecars are not counted as unsupported files The import reads a photo's XMP sidecar along with the photo, so a sidecar is not a file the scan skipped. expand_report now leaves .xmp files (any letter case) out of Expansion::unsupported, which feeds ScanOutput, the "skipped.unsupported" count of library.importPreview and the review's note; every other file that is not a supported photo type still counts. The walk itself stays generic: Walked::skipped still counts every file its caller refused, and which files are returned is unchanged. * LR-IMP-ADD-DIALOG: tests for leaving XMP sidecars out of the unsupported count A folder with a photo, sidecars in lower, upper and mixed case (one in a subfolder) and a text file reports one unsupported file through the expansion, the scan and library.importPreview; a folder of photos and sidecars only reports none. The review shows no note for sidecars alone and the text file's line once one is added. * LR-IMP-ADD-DIALOG: tracker wording for the sidecar exclusion The row and the revision-history entry say that XMP sidecars are not counted among the files the review reports as skipped. * rename importPreview's walk-truncation flag to scanLimited - avoids one reply using truncated for two meanings once #2705/#2873 land (maintainer request) * ui: translate the import scan notes into cs, fi, id, it, ka, pl, sv and vi * fix: register the scan note against the Ui, not the Context (main's register takes &Ui) * Report diagnostics even when the scan finds no photos When a scan finds no photos, the message now says what it left out: folders it could not read, files that are not photos, or a walk stopped at its limit. A complete scan with no photos keeps the plain message. * Format the scan results the merge touched Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/library/specs.rs | 14 +- crates/engine/src/import.rs | 6 +- crates/engine/src/import/files.rs | 65 ++++- crates/engine/src/import/scan.rs | 35 ++- crates/engine/src/tests/import.rs | 210 ++++++++++++++++ crates/engine/src/walk.rs | 61 ++++- crates/ui-egui/locales/cs-formats.json | 4 +- crates/ui-egui/locales/cs.json | 3 +- crates/ui-egui/locales/de-formats.json | 2 + crates/ui-egui/locales/de.json | 1 + crates/ui-egui/locales/es-formats.json | 2 + crates/ui-egui/locales/es.json | 1 + crates/ui-egui/locales/fi-formats.json | 4 +- crates/ui-egui/locales/fi.json | 3 +- crates/ui-egui/locales/fr-formats.json | 2 + crates/ui-egui/locales/fr.json | 1 + crates/ui-egui/locales/id-formats.json | 4 +- crates/ui-egui/locales/id.json | 3 +- crates/ui-egui/locales/it-formats.json | 4 +- crates/ui-egui/locales/it.json | 3 +- crates/ui-egui/locales/ja-formats.json | 2 + crates/ui-egui/locales/ja.json | 1 + crates/ui-egui/locales/ka-formats.json | 4 +- crates/ui-egui/locales/ka.json | 3 +- crates/ui-egui/locales/pl-formats.json | 4 +- crates/ui-egui/locales/pl.json | 3 +- crates/ui-egui/locales/pt-br-formats.json | 2 + crates/ui-egui/locales/pt-br.json | 1 + crates/ui-egui/locales/ru-formats.json | 2 + crates/ui-egui/locales/ru.json | 1 + crates/ui-egui/locales/sv-formats.json | 4 +- crates/ui-egui/locales/sv.json | 3 +- crates/ui-egui/locales/uk-formats.json | 2 + crates/ui-egui/locales/uk.json | 1 + crates/ui-egui/locales/vi-formats.json | 4 +- crates/ui-egui/locales/vi.json | 3 +- crates/ui-egui/locales/zh-hans-formats.json | 2 + crates/ui-egui/locales/zh-hans.json | 1 + crates/ui-egui/locales/zh-hant-formats.json | 2 + crates/ui-egui/locales/zh-hant.json | 1 + crates/ui-egui/src/dialogs/import.rs | 18 +- crates/ui-egui/src/dialogs/import/body.rs | 23 ++ crates/ui-egui/src/dialogs/import/scan.rs | 18 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/drop_import.rs | 9 +- crates/ui-egui/src/tests/import_scan_note.rs | 242 +++++++++++++++++++ crates/ui-egui/src/tests/scan_probes.rs | 9 +- docs/parity-checklist.md | 4 +- 48 files changed, 747 insertions(+), 51 deletions(-) create mode 100644 crates/ui-egui/src/tests/import_scan_note.rs diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 4274e689c9..7732b855ba 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1325,16 +1325,22 @@ pub fn specs() -> Vec { "Review Import", [], None, - "{paths: [file or folder (recursive)]} → {candidates: [{path, name, format, kind, width, height, fileSize, captured, duplicate?: path|content, existing?, error?, previewOnly?: why a raw can only be shown from its embedded preview}], duplicates, scanned} — nothing is added", + "{paths: [file or folder (recursive)]} → {candidates: [{path, name, format, kind, width, height, fileSize, captured, duplicate?: path|content, existing?, error?, previewOnly?: why a raw can only be shown from its embedded preview}], duplicates, scanned, scanLimited: bool (the folder walk stopped at its scan limit: there may be more photos), skipped: {unreadable (folders that could not be listed), unsupported (files in the folders that are not a supported photo type, XMP sidecars not counted; a file named in paths is always tried)}} — nothing is added", always, |s, p| { let paths = strs(p, "paths"); if paths.is_empty() { return Err(bad("library.importPreview", "no paths")); } - let c = crate::import::scan(s, &paths); - let dups = c.iter().filter(|c| c.duplicate.is_some()).count(); - Ok(json!({"scanned": c.len(), "duplicates": dups, "candidates": c})) + let out = crate::import::scan_report(s, &paths); + let dups = out.candidates.iter().filter(|c| c.duplicate.is_some()).count(); + Ok(json!({ + "scanned": out.candidates.len(), + "duplicates": dups, + "candidates": out.candidates, + "scanLimited": out.truncated, + "skipped": {"unreadable": out.unreadable, "unsupported": out.unsupported}, + })) } ), cmd!( diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index b4ee766048..cd3123e522 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -46,7 +46,8 @@ pub(crate) use commit::workers; pub use commit::{batch_size, civil, commit_prepared, system_clock}; pub use defaults::{CameraDefault, ImportDefaults, apply_import_defaults, has_import_look, import_defaults}; pub use files::{ - EXTENSIONS, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_within, is_supported, launch_deadline, launch_path, launch_path_until, + EXTENSIONS, Expansion, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_report, expand_within, is_supported, launch_deadline, + launch_path, launch_path_until, }; pub(crate) use files::{expand_noting, probe_all, probe_paths, probe_with}; #[cfg(test)] @@ -54,7 +55,8 @@ use job::PreparedItem; pub use job::{ImportJob, Prepared, candidate_thumb_key, import, import_with}; pub(crate) use scan::scan_files; pub use scan::{ - ScanInput, ScanOutput, ScanProgress, browse_files, browse_order, browse_path, browse_queue, browse_queue_until, browse_spelling, scan, scan_with, + ScanInput, ScanOutput, ScanProgress, browse_files, browse_order, browse_path, browse_queue, browse_queue_until, browse_spelling, scan, + scan_report, scan_with, }; #[cfg(test)] use scan::{library_files, library_hashes}; diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index 39c55f56ff..d6a9c6eea9 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -24,6 +24,11 @@ pub fn is_supported(path: &Path) -> bool { path.extension().is_some_and(|e| EXTENSIONS.contains(&e.to_string_lossy().to_lowercase().as_str())) } +/// An XMP sidecar (`.xmp`, any letter case): read with its photo on import, never a photo itself. +fn is_xmp_sidecar(path: &Path) -> bool { + path.extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp")) +} + /// The web file picker's accept list, derived from [`EXTENSIONS`]. Each extension /// is listed in both cases: browsers' `accept` matching is case-insensitive per /// spec, but some implementations (e.g. Windows/Edge) match case-sensitively and @@ -78,19 +83,57 @@ pub(crate) fn expand_noting( paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits, - mut note: Option, + note: Option, ) -> (Vec, bool) { - let mut out = Vec::new(); - let mut truncated = false; + let e = expand_report_noting(paths, skip, limits, note); + (e.files, e.truncated) +} + +/// What expanding import sources found, and what the walks left out ([`expand_report`]), so a +/// review can say that it did not see everything. +#[derive(Clone, Debug, Default)] +pub struct Expansion { + /// Supported files, folders walked recursively and deduplicated by path, in walk order. + pub files: Vec, + /// A walk stopped at a depth or entry bound: there may be more files. + pub truncated: bool, + /// Folders whose contents couldn't be listed (permissions, a folder that vanished or went offline). + pub unreadable: usize, + /// Files found inside the folders walked that are not a supported type (see [`is_supported`]), + /// not counting XMP sidecars, which the import reads with their photos. A file named directly + /// is attempted whatever its extension and is never counted here. Both counts add up over the + /// sources, so a folder named twice (or inside another source) counts twice. + pub unsupported: usize, +} + +/// [`expand_within`] keeping the walks' diagnostics. A walk that stops at a bound is logged here +/// (once per folder), as it always was. +pub fn expand_report(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits) -> Expansion { + expand_report_noting(paths, skip, limits, None) +} + +/// ([`expand_report`], handing the listing of every folder that is walked to `note`, as +/// [`expand_noting`] does.) +fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits, mut note: Option) -> Expansion { + let mut out = Expansion::default(); for p in paths { let p = Path::new(p); if skip.is_some_and(|s| p == s) { continue; } if p.is_dir() { + // XMP sidecars are read with their photos, not skipped: they are left out of the count + let mut sidecars = 0usize; + let keep = |f: &Path| { + let keep = is_supported(f); + if !keep && is_xmp_sidecar(f) { + sidecars = sidecars.saturating_add(1); + } + keep + }; let w = match note.as_mut() { - Some(note) => crate::walk::files_in_noting(p, skip, limits, is_supported, &mut **note), - None => crate::walk::files_in(p, skip, limits, is_supported), + Some(note) => crate::walk::files_in_noting(p, skip, limits, keep, &mut **note), + None => crate::walk::files_in(p, skip, limits, keep), }; if w.truncated { log::warn!( @@ -101,16 +144,18 @@ pub(crate) fn expand_noting( limits.max_depth ); } - truncated |= w.truncated; - out.extend(w.files.into_iter().map(|f| f.to_string_lossy().to_string())); + out.truncated |= w.truncated; + out.unreadable = out.unreadable.saturating_add(w.unreadable); + out.unsupported = out.unsupported.saturating_add(w.skipped.saturating_sub(sidecars)); + out.files.extend(w.files.into_iter().map(|f| f.to_string_lossy().to_string())); } else { // explicitly named files are attempted even with an unknown extension (sniffed) - out.push(p.to_string_lossy().to_string()); + out.files.push(p.to_string_lossy().to_string()); } } let mut seen = std::collections::HashSet::new(); - out.retain(|p| seen.insert(p.clone())); - (out, truncated) + out.files.retain(|p| seen.insert(p.clone())); + out } /// What a path given on the command line at launch becomes ([`launch_path`]). diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index ad247c22c6..aaae16c7a4 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -1,4 +1,4 @@ -use super::files::{Seen, expand, is_supported, probe_all, reusable_probes}; +use super::files::{Seen, expand, expand_report, is_supported, probe_all, reusable_probes}; use super::types::ImportCandidate; use super::{HashMap, Path, PathBuf, PhotoId, ProbeInfo, Session, Source}; @@ -77,6 +77,12 @@ pub struct ScanProgress { pub struct ScanOutput { pub candidates: Vec, pub probes: HashMap, + /// A folder walk stopped at a depth or entry bound: there may be more photos ([`Expansion`]). + pub truncated: bool, + /// Folders whose contents couldn't be listed. + pub unreadable: usize, + /// Files inside the folders that are not a supported photo type (XMP sidecars not counted). + pub unsupported: usize, } impl ScanInput { @@ -283,20 +289,32 @@ fn browse_order_until(files: &mut [String], sort: &lightcraft_catalog::Sort, can /// against the library and earlier candidates). Nothing is added; the probes are kept for the /// import that follows. pub fn scan(s: &mut Session, paths: &[String]) -> Vec { + scan_report(s, paths).candidates +} + +/// [`scan`] keeping what the walks left out. The probes are already kept in the session for the +/// import that follows, so `probes` of the output is empty. +pub fn scan_report(s: &mut Session, paths: &[String]) -> ScanOutput { let (input, paths) = ScanInput::new(s, paths); - let out = scan_with(input, &paths, &ScanProgress::default()); - s.import_probes = out.probes; - out.candidates + let mut out = scan_with(input, &paths, &ScanProgress::default()); + s.import_probes = std::mem::take(&mut out.probes); + out } /// [`scan`] without the session, so it can run on a worker thread. Stops early (returning what it /// has) when `progress.cancel` is set. pub fn scan_with(input: ScanInput, paths: &[String], progress: &ScanProgress) -> ScanOutput { - let files = expand(paths, input.skip.as_deref()); - scan_files(input, files, progress) + let expansion = expand_report(paths, input.skip.as_deref(), crate::walk::Limits::default()); + let mut out = scan_files(input, expansion.files, progress); + out.truncated = expansion.truncated; + out.unreadable = expansion.unreadable; + out.unsupported = expansion.unsupported; + out } -/// [`scan_with`] for files that were found already (`paths` expanded, [`expand`]). +/// [`scan_with`] for files that were found already (`paths` expanded, [`expand`]). The walks' +/// diagnostics ([`ScanOutput::truncated`] and friends) are left empty: who expanded the paths has +/// them ([`expand_report`]). pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &ScanProgress) -> ScanOutput { use std::sync::atomic::Ordering::Relaxed; let by_path = library_files(&input.library, &files); @@ -357,5 +375,6 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc } out.push(c); } - ScanOutput { candidates: out, probes: kept } + // (the walks' diagnostics are [`scan_with`]'s: these files were found already) + ScanOutput { candidates: out, probes: kept, truncated: false, unreadable: 0, unsupported: 0 } } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 54f3382014..49176077fb 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -2172,6 +2172,216 @@ fn expand_stops_at_the_walk_limits() { let _ = std::fs::remove_dir_all(&d); } +/// `levels` folders named `d` nested below `root` (created); the innermost one's path. +fn nested(root: &Path, levels: usize) -> std::path::PathBuf { + let mut dir = root.to_path_buf(); + for _ in 0..levels { + dir = dir.join("d"); + } + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Expanding folders reports what the walks left out — files of an unsupported type, a walk that +/// stopped at a bound — and returns the same files as `expand_within`; a file named on its own is +/// attempted whatever its extension and is not counted as unsupported. +#[test] +fn expand_report_counts_what_the_walks_left_out() { + use crate::import::{expand_report, expand_within}; + let d = temp_dir("expand-report"); + write_png(&d.join("a.png"), 1); + write_png(&d.join("sub/b.png"), 2); + std::fs::write(d.join("notes.txt"), "x").unwrap(); + std::fs::write(d.join("sub/readme.md"), "x").unwrap(); + std::fs::write(d.join("sub/.hidden.txt"), "x").unwrap(); + let named = temp_dir("expand-report-named"); + std::fs::write(named.join("odd.dat"), "x").unwrap(); + let paths = [d.to_string_lossy().to_string(), named.join("odd.dat").to_string_lossy().to_string()]; + let limits = crate::walk::Limits::default(); + + let e = expand_report(&paths, None, limits); + assert_eq!(e.files.len(), 3, "both photos and the named file: {:?}", e.files); + assert_eq!((e.unsupported, e.unreadable, e.truncated), (2, 0, false), "notes.txt and readme.md; the hidden file is not counted: {e:?}"); + assert_eq!(expand_within(&paths, None, limits), (e.files.clone(), false), "expand_within is the same walk"); + + // stopping one level down: the second folder is never listed, so its files are not counted + let e = expand_report(&paths[..1], None, crate::walk::Limits { max_depth: 1, max_entries: 1000 }); + assert_eq!((e.files.len(), e.unsupported, e.truncated), (1, 1, true), "{e:?}"); + let _ = std::fs::remove_dir_all(&d); + let _ = std::fs::remove_dir_all(&named); +} + +/// A scan says that its folder walk stopped at the depth limit (there may be more photos), and +/// does not when the tree ends within it. +#[test] +fn scan_with_reports_a_walk_that_stopped_at_a_bound() { + use crate::import::{ScanInput, ScanProgress, scan_with}; + let scan = |dir: &Path| { + let mut s = Session::new().with_fs(); + let (input, paths) = ScanInput::new(&mut s, &[dir.to_string_lossy().to_string()]); + scan_with(input, &paths, &ScanProgress::default()) + }; + // the deepest folder a walk lists is one level above the limit; one more folder is never entered + let cut = temp_dir("scan-cut"); + write_png(&cut.join("top.png"), 1); + write_png(&nested(&cut, crate::walk::MAX_DEPTH - 1).join("last.png"), 2); + nested(&cut, crate::walk::MAX_DEPTH); + let out = scan(&cut); + assert_eq!(out.candidates.len(), 2, "what was reached is still returned"); + assert_eq!((out.truncated, out.unreadable, out.unsupported), (true, 0, 0)); + + let whole = temp_dir("scan-whole"); + write_png(&whole.join("top.png"), 1); + write_png(&nested(&whole, crate::walk::MAX_DEPTH - 1).join("last.png"), 2); + let out = scan(&whole); + assert_eq!(out.candidates.len(), 2); + assert_eq!((out.truncated, out.unreadable, out.unsupported), (false, 0, 0)); + let _ = std::fs::remove_dir_all(&cut); + let _ = std::fs::remove_dir_all(&whole); +} + +/// A folder this process is not allowed to list, until it is dropped (Unix: no permissions; +/// Windows: a deny entry for Everyone on listing it). +struct Unlistable(std::path::PathBuf); + +impl Unlistable { + /// `None` when the folder can still be listed (the super-user ignores permissions) or the + /// means to deny it is missing: the test then has nothing to check. + fn new(dir: &Path) -> Option { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o000)).ok()?; + } + #[cfg(windows)] + { + let denied = std::process::Command::new("icacls").arg(dir).args(["/deny", "*S-1-1-0:(RD)"]).output(); + if !denied.is_ok_and(|o| o.status.success()) { + return None; + } + } + // from here the folder is restored on drop, whatever the test does + let guard = Unlistable(dir.to_path_buf()); + std::fs::read_dir(dir).is_err().then_some(guard) + } +} + +impl Drop for Unlistable { + fn drop(&mut self) { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755)); + } + #[cfg(windows)] + { + let _ = std::process::Command::new("icacls").arg(&self.0).args(["/remove:d", "*S-1-1-0"]).output(); + } + } +} + +/// A folder the scan can't list is counted — by the scan and by `library.importPreview` — and the +/// photos around it are still found. +#[test] +fn an_unlistable_folder_is_reported_by_the_scan() { + use crate::import::{ScanInput, ScanProgress, scan_with}; + let src = temp_dir("unlistable"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("locked").join("b.png"), 2); + let Some(locked) = Unlistable::new(&src.join("locked")) else { + eprintln!("skipped: this process can still list a folder it was denied"); + let _ = std::fs::remove_dir_all(&src); + return; + }; + let mut s = Session::new().with_fs(); + let (input, paths) = ScanInput::new(&mut s, &[src.to_string_lossy().to_string()]); + let out = scan_with(input, &paths, &ScanProgress::default()); + assert_eq!(out.candidates.len(), 1, "only the photo outside the folder"); + assert_eq!((out.unreadable, out.unsupported, out.truncated), (1, 0, false)); + let r = s.execute("library.importPreview", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!((r["scanned"].clone(), r["skipped"].clone()), (json!(1), json!({"unreadable": 1, "unsupported": 0})), "{r}"); + drop(locked); + let _ = std::fs::remove_dir_all(&src); +} + +/// `library.importPreview` reports the walk's diagnostics next to the keys it always returned, and +/// still leaves its probes for the import that follows. +#[test] +fn import_preview_reports_what_the_scan_skipped() { + let src = temp_dir("preview-diag"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("sub/b.png"), 2); + std::fs::write(src.join("notes.txt"), b"not a photo").unwrap(); + std::fs::write(src.join("sub/readme.md"), b"x").unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.importPreview", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!((r["scanned"].clone(), r["duplicates"].clone()), (json!(2), json!(0)), "{r}"); + assert_eq!(ids(&r, "candidates"), 2, "{r}"); + assert_eq!(r["scanLimited"], false, "{r}"); + assert_eq!(r["skipped"], json!({"unreadable": 0, "unsupported": 2}), "notes.txt and readme.md are reported: {r}"); + for f in [src.join("a.png"), src.join("sub").join("b.png")] { + let key = f.to_string_lossy().to_string(); + assert!(s.import_probes.contains_key(&key), "the probe of {key} is kept for the import: {:?}", s.import_probes.keys()); + } + // a second preview reuses them: a file that has not changed is not read again + let reads = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (counted, probe) = (reads.clone(), s.media.file_probe.clone().unwrap()); + s.media.file_probe = Some(std::sync::Arc::new(move |path: &str| { + counted.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + probe(path) + })); + let again = s.execute("library.importPreview", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(again["scanned"], 2, "{again}"); + assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 0, "the first preview's probes are reused"); + + // a file named on its own is tried, not reported as skipped + let r = s.execute("library.importPreview", &json!({"paths": [src.join("notes.txt").to_string_lossy()]})).unwrap(); + assert_eq!((r["scanned"].clone(), r["skipped"]["unsupported"].clone()), (json!(1), json!(0)), "{r}"); + + // a walk that stopped at the depth limit says so + let deep = temp_dir("preview-deep"); + write_png(&deep.join("top.png"), 3); + nested(&deep, crate::walk::MAX_DEPTH); + let r = s.execute("library.importPreview", &json!({"paths": [deep.to_string_lossy()]})).unwrap(); + assert_eq!((r["scanned"].clone(), r["scanLimited"].clone()), (json!(1), json!(true)), "{r}"); + let _ = std::fs::remove_dir_all(&src); + let _ = std::fs::remove_dir_all(&deep); +} + +/// XMP sidecars are read with their photos, so they are not "skipped": the expansion, the scan and +/// `library.importPreview` count them (in any letter case, in subfolders too) as nothing, and still +/// count every other file that is not a photo. +#[test] +fn xmp_sidecars_are_not_counted_as_unsupported() { + use crate::import::{ScanInput, ScanProgress, expand_report, scan_with}; + let mut s = Session::new().with_fs(); + // sidecars beside a photo, a sidecar without one, in any case, one deeper; plus a text file + let mixed = temp_dir("sidecars-mixed"); + write_png(&mixed.join("a.png"), 1); + std::fs::write(mixed.join("a.xmp"), b"x").unwrap(); + std::fs::write(mixed.join("b.XMP"), b"x").unwrap(); + std::fs::create_dir_all(mixed.join("sub")).unwrap(); + std::fs::write(mixed.join("sub").join("c.Xmp"), b"x").unwrap(); + std::fs::write(mixed.join("c.txt"), b"x").unwrap(); + // only photos and sidecars + let tidy = temp_dir("sidecars-only"); + write_png(&tidy.join("a.png"), 2); + std::fs::write(tidy.join("a.xmp"), b"x").unwrap(); + std::fs::write(tidy.join("b.XMP"), b"x").unwrap(); + for (dir, unsupported) in [(&mixed, 1usize), (&tidy, 0)] { + let path = dir.to_string_lossy().to_string(); + let e = expand_report(std::slice::from_ref(&path), None, crate::walk::Limits::default()); + assert_eq!((e.files.len(), e.unsupported), (1, unsupported), "expand_report {e:?}"); + let (input, paths) = ScanInput::new(&mut s, std::slice::from_ref(&path)); + let out = scan_with(input, &paths, &ScanProgress::default()); + assert_eq!((out.candidates.len(), out.unsupported), (1, unsupported), "scan_with"); + let r = s.execute("library.importPreview", &json!({"paths": [path]})).unwrap(); + assert_eq!((r["scanned"].clone(), r["skipped"]["unsupported"].clone()), (json!(1), json!(unsupported)), "{r}"); + } + let _ = std::fs::remove_dir_all(&mixed); + let _ = std::fs::remove_dir_all(&tidy); +} + /// Raw containers LightCraft cannot decode but shows by their embedded JPEG are picked up from a folder /// (the extensions are in `import::EXTENSIONS`; the files differ so none is a duplicate) and import as preview only. #[test] diff --git a/crates/engine/src/walk.rs b/crates/engine/src/walk.rs index db024f7098..f0c4033dd6 100644 --- a/crates/engine/src/walk.rs +++ b/crates/engine/src/walk.rs @@ -41,6 +41,13 @@ pub struct Walked { pub truncated: bool, /// Directory entries looked at. pub entries: usize, + /// Folders whose contents couldn't be listed (permissions, a folder that vanished or went + /// offline): the walk skipped them and carried on. Only a refused listing counts, not an + /// entry inside a listed folder that couldn't be examined. + pub unreadable: usize, + /// Files the walk reached that `keep` refused. Hidden entries and the skipped folder are left + /// out silently and not counted. + pub skipped: usize, } /// Whether the entry has a dot-prefixed name or a Windows or macOS hidden attribute. @@ -93,7 +100,8 @@ pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, Entr /// The files below folder `root` that `keep` accepts. Hidden entries (names starting with `.`) /// are left out, the folder `skip` (e.g. the library's own) is never entered, and the walk stops -/// at `limits` (see [`Walked::truncated`]). Unreadable folders are skipped. +/// at `limits` (see [`Walked::truncated`]). Unreadable folders are skipped and counted +/// ([`Walked::unreadable`]), as are the files `keep` refuses ([`Walked::skipped`]). pub fn files_in(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool) -> Walked { walk(root, skip, limits, keep, |_| true, None) } @@ -140,6 +148,8 @@ fn walk( if !is_dir { if keep(&path) { out.files.push(path); + } else { + out.skipped = out.skipped.saturating_add(1); } continue; } @@ -150,7 +160,10 @@ fn walk( out.truncated = true; continue; } - let Ok(rd) = std::fs::read_dir(&path) else { continue }; + let Ok(rd) = std::fs::read_dir(&path) else { + out.unreadable = out.unreadable.saturating_add(1); + continue; + }; let mut children: Vec<(PathBuf, bool)> = Vec::new(); // (the folder's listing, for who asked for it; all of it unless something below says otherwise) let mut listed = note.is_some().then(Vec::new); @@ -348,6 +361,50 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// Files the caller's `keep` refuses are counted (an import reports most of them as + /// unsupported), and so are only those: hidden files and the skipped folder are left out without a count, and + /// the files returned are the same ones in the same order. + #[test] + fn unkept_files_are_counted_as_skipped() { + let d = tmp("skipped"); + for f in ["a.jpg", "b.txt", "c.png", "sub/d.jpg", "sub/e.md", ".hidden.txt", "lib/l.txt"] { + let p = d.join(f); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, b"x").unwrap(); + } + let lib = d.join("lib"); + let w = files_in(&d, Some(&lib), Limits::default(), |p| p.extension().is_some_and(|e| e == "jpg")); + let rel: Vec = w.files.iter().map(|p| p.strip_prefix(&d).unwrap().to_string_lossy().replace('\\', "/")).collect(); + assert_eq!(rel, ["a.jpg", "sub/d.jpg"]); + assert_eq!((w.skipped, w.unreadable, w.truncated), (3, 0, false), "{w:?}"); + let _ = std::fs::remove_dir_all(&d); + } + + /// A folder that is gone by the time the walk reaches it (here removed while an earlier file is + /// looked at, as an unplugged disk or a deleted folder would be) is counted as unreadable; + /// the walk carries on and still returns the other files. + #[test] + fn a_folder_that_vanishes_is_counted_as_unreadable() { + let d = tmp("vanished"); + for f in ["a.jpg", "b/b.jpg", "c.jpg"] { + let p = d.join(f); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, b"x").unwrap(); + } + let gone = d.join("b"); + // `a.jpg` is looked at before the folder `b` is entered + let w = files_in(&d, None, Limits::default(), |p| { + if p.ends_with("a.jpg") { + let _ = std::fs::remove_dir_all(&gone); + } + true + }); + let rel: Vec = w.files.iter().map(|p| p.strip_prefix(&d).unwrap().to_string_lossy().replace('\\', "/")).collect(); + assert_eq!(rel, ["a.jpg", "c.jpg"]); + assert_eq!((w.unreadable, w.skipped, w.truncated), (1, 0, false), "{w:?}"); + let _ = std::fs::remove_dir_all(&d); + } + /// Folder imports must not revisit the user's own library through symlinks /// or through an alias to the library's parent. #[cfg(unix)] diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index e65ad627ef..d642bc85ae 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -320,5 +320,7 @@ "Panel layout could not be restored: {error}": "Rozložení panelů se nepodařilo obnovit: {error}", "Panel move was not applied: {error}": "Přesun panelu nebyl použit: {error}", "{name} is installed": "{name} je nainstalován", - "{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto" + "{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto", + "{n} folder{} could not be read": "Složky, které se nepodařilo přečíst: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 95f52edb1b..5cb9ba0e45 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2449,5 +2449,6 @@ "Set up name suggestions…": "Nastavit návrhy jmen…", "Top bar": "Horní lišta", "Tool strip": "Pruh nástrojů", - "Bottom bar": "Dolní lišta" + "Bottom bar": "Dolní lišta", + "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 70ced17114..8c119e8ec9 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -161,6 +161,8 @@ "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "{n} Änderung(en) konnten nicht auf den Datenträger geschrieben werden{0:.0}: {e}\nWenn du jetzt beendest, gehen sie verloren.{1:.0}", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} Änderung(en) nur im Arbeitsspeicher, nicht auf dem Datenträger gespeichert{0:.0}: {e}\nLightCraft versucht es automatisch erneut; wenn du jetzt beendest, gehen sie verloren.{1:.0}", "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "{n} Änderung(en) nur im Arbeitsspeicher gespeichert{:.0}: {e} – LightCraft versucht es erneut", + "{n} file{} skipped (not a supported photo type)": "Übersprungene Dateien (kein unterstützter Fototyp): {n}{:.0}", + "{n} folder{} could not be read": "Ordner, die nicht gelesen werden konnten: {n}{:.0}", "{n} found · {sel} selected": "{n} gefunden · {sel} ausgewählt", "{n} photos": "Fotos: {n}", "{n} photos in {} are hidden by the filters above": "{n} Fotos in {} werden durch die obigen Filter ausgeblendet", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index c05a66246b..12dae2c870 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2087,6 +2087,7 @@ "Metadata read": "Metadaten gelesen", "Failed": "Fehlgeschlagen", "Stopped": "Angehalten", + "Stopped at the scan limit: there may be more photos": "Am Suchlimit angehalten: Es gibt möglicherweise weitere Fotos", "Stopped by an error (see the log)": "Durch einen Fehler angehalten (siehe Protokoll)", "Not saved": "Nicht gespeichert", "A folder is being synchronized": "Ein Ordner wird gerade synchronisiert", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 7b697e946b..2a001f3891 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -161,6 +161,8 @@ "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "Cambios que no se pudieron escribir en el disco: {n}{0:.0}: {e}\nSi se sale ahora, se perderán.{1:.0}", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "Cambios guardados en memoria, pero no escritos en el disco: {n}{0:.0}: {e}\nLightCraft vuelve a intentarlo automáticamente; si se sale ahora, se perderán.{1:.0}", "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "Cambios guardados solo en memoria: {n}{:.0}: {e}; LightCraft volverá a intentarlo", + "{n} file{} skipped (not a supported photo type)": "Archivos omitidos (no son de un tipo de foto compatible): {n}{:.0}", + "{n} folder{} could not be read": "Carpetas que no se pudieron leer: {n}{:.0}", "{n} found · {sel} selected": "{n} encontradas · {sel} seleccionadas", "{n} photos": "{n} fotos", "{n} photos in {} are hidden by the filters above": "Los filtros de arriba ocultan {n} fotos en {}", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index bacf411182..b4aaf400a8 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2114,6 +2114,7 @@ "Metadata read": "Metadatos leídos", "Failed": "Con errores", "Stopped": "Detenido", + "Stopped at the scan limit: there may be more photos": "Se detuvo en el límite de exploración: puede haber más fotos", "Stopped by an error (see the log)": "Detenido por un error (ver el registro)", "Not saved": "Sin guardar", "A folder is being synchronized": "Se está sincronizando una carpeta", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 720519a1cc..12cdf13df8 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -317,5 +317,7 @@ "Panel layout could not be restored: {error}": "Paneelien asettelua ei voitu palauttaa: {error}", "Panel move was not applied: {error}": "Paneelin siirtoa ei otettu käyttöön: {error}", "{name} is installed": "{name} on asennettu", - "{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä" + "{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä", + "{n} folder{} could not be read": "Kansiot, joita ei voitu lukea: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 43be15d273..d5dc27d8c0 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2360,5 +2360,6 @@ "Set up name suggestions…": "Määritä nimiehdotukset…", "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", - "Bottom bar": "Alapalkki" + "Bottom bar": "Alapalkki", + "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 3aa2166971..cc78f8331e 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -161,6 +161,8 @@ "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "Impossible d’écrire {n} modification{} sur le disque : {e}\nSi vous quittez maintenant, {} seront perdues.", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} modification{} enregistrée(s) en mémoire mais non écrite(s) sur le disque : {e}\nLightCraft réessaiera automatiquement ; quitter maintenant entraînerait la perte de {}.", "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "{n} modification{} enregistrée(s) en mémoire mais non écrite(s) sur le disque : {e} — LightCraft réessaiera.", + "{n} file{} skipped (not a supported photo type)": "Fichiers ignorés (type de photo non pris en charge) : {n}{:.0}", + "{n} folder{} could not be read": "Dossiers illisibles : {n}{:.0}", "{n} found · {sel} selected": "{n} trouvé(s) · {sel} sélectionné(s)", "{n} photos": "{n} photos", "{n} photos in {} are hidden by the filters above": "Les filtres ci-dessus masquent {n} photos dans {}", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 974347cc4d..8406d3e2ae 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1922,6 +1922,7 @@ "Metadata read": "Métadonnées lues", "Failed": "Échecs", "Stopped": "Arrêté", + "Stopped at the scan limit: there may be more photos": "Arrêt à la limite d'analyse : il peut y avoir d'autres photos", "Stopped by an error (see the log)": "Arrêté par une erreur (voir le journal)", "Not saved": "Non enregistré", "A folder is being synchronized": "Un dossier est en cours de synchronisation", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 22eb2d49e3..85c06ed3e1 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -320,5 +320,7 @@ "{name} is installed and in use: face recognition is on": "{name} sudah terinstal dan digunakan: pengenalan wajah aktif", "Creates {stacks} stack{} from {photos} of {scope}": "Membuat {stacks} tumpukan dari {photos} foto ({scope}){:.0}", "{n} selected photo{} · {pages} page{}": "{n} foto dipilih · {pages} halaman{:.0}{:.0}", - "{n} photo{} in view · {slides} slide{} · {time}": "{n} foto di tampilan · {slides} slide · {time}{:.0}{:.0}" + "{n} photo{} in view · {slides} slide{} · {time}": "{n} foto di tampilan · {slides} slide · {time}{:.0}{:.0}", + "{n} folder{} could not be read": "Folder yang tidak bisa dibaca: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 70999cc4f5..8805697868 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2374,5 +2374,6 @@ "Set up name suggestions…": "Siapkan saran nama…", "Top bar": "Bilah atas", "Tool strip": "Bilah alat", - "Bottom bar": "Bilah bawah" + "Bottom bar": "Bilah bawah", + "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 729c27a0f1..c3227a1aa4 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -320,5 +320,7 @@ "Panel layout could not be restored: {error}": "Non è stato possibile ripristinare la disposizione dei pannelli: {error}", "Panel move was not applied: {error}": "Lo spostamento del pannello non è stato applicato: {error}", "{name} is installed": "{name} è installato", - "{name} is installed and in use: face recognition is on": "{name} è installato e in uso: il riconoscimento dei volti è attivo" + "{name} is installed and in use: face recognition is on": "{name} è installato e in uso: il riconoscimento dei volti è attivo", + "{n} folder{} could not be read": "Cartelle non leggibili: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index cf5082aba1..617b0d9fea 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2567,5 +2567,6 @@ "Unit": "Unità", "Top bar": "Barra superiore", "Tool strip": "Barra degli strumenti", - "Bottom bar": "Barra inferiore" + "Bottom bar": "Barra inferiore", + "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index b25ef53978..2cf2c0f83a 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -96,6 +96,8 @@ "{name} On": "{name}を有効にする", "{name} — double-click to reset it": "{name}:ダブルクリックでリセット", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n}件の変更{:.0}をディスクに保存できません:{e}\n自動で再試行します。終了すると変更が失われます{:.0}", + "{n} file{} skipped (not a supported photo type)": "スキップしたファイル(非対応の写真形式):{n}個{:.0}", + "{n} folder{} could not be read": "読み取れなかったフォルダー:{n}個{:.0}", "{n} found · {sel} selected": "{n}枚検出・{sel}枚選択", "{n} photos": "{n}枚", "{n} photos in {} are hidden by the filters above": "{}の{n}枚は上のフィルターで非表示になっています", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 3a9c49e79a..9178aad528 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1935,6 +1935,7 @@ "Metadata read": "メタデータ読み込み", "Failed": "失敗", "Stopped": "停止しました", + "Stopped at the scan limit: there may be more photos": "スキャンの上限で停止しました。ほかにも写真がある可能性があります", "Stopped by an error (see the log)": "エラーで停止しました(ログを参照)", "Not saved": "保存されていません", "A folder is being synchronized": "フォルダを同期中です", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 612178c0e8..c058aa9b04 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -323,5 +323,7 @@ "Panel layout could not be restored: {error}": "პანელების განლაგების აღდგენა ვერ მოხერხდა: {error}", "Panel move was not applied: {error}": "პანელის გადატანა არ შესრულდა: {error}", "{name} is installed": "{name} დაინსტალირებულია", - "{name} is installed and in use: face recognition is on": "{name} დაინსტალირებულია და გამოიყენება: სახეების ამოცნობა ჩართულია" + "{name} is installed and in use: face recognition is on": "{name} დაინსტალირებულია და გამოიყენება: სახეების ამოცნობა ჩართულია", + "{n} folder{} could not be read": "საქაღალდეები, რომლებიც ვერ წაიკითხა: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index e3a773e93f..e7e3e6e9c5 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3670,5 +3670,6 @@ "Top bar": "ზედა ზოლი", "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", + "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index e5d3e8d068..3ca9d0503d 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -320,5 +320,7 @@ "Panel layout could not be restored: {error}": "Nie udało się przywrócić układu paneli: {error}", "Panel move was not applied: {error}": "Przeniesienie panelu nie zostało zastosowane: {error}", "{name} is installed": "{name} jest zainstalowany", - "{name} is installed and in use: face recognition is on": "{name} jest zainstalowany i używany: rozpoznawanie twarzy jest włączone" + "{name} is installed and in use: face recognition is on": "{name} jest zainstalowany i używany: rozpoznawanie twarzy jest włączone", + "{n} folder{} could not be read": "Nie udało się odczytać folderów: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 44719aacbf..27eca8dfc1 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2325,5 +2325,6 @@ "Set up name suggestions…": "Skonfiguruj propozycje imion…", "Top bar": "Górny pasek", "Tool strip": "Pasek narzędzi", - "Bottom bar": "Dolny pasek" + "Bottom bar": "Dolny pasek", + "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 83d5a37518..5ac3194d78 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -121,6 +121,8 @@ "{name} On": "{name} ativado", "{name} — double-click to reset it": "{name} — clique duas vezes para redefinir", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} alteração{:.0} salva na memória mas não gravada no disco: {e}\nO LightCraft tenta novamente automaticamente; encerrar agora perderia {}.", + "{n} file{} skipped (not a supported photo type)": "Arquivos ignorados (tipo de foto sem suporte): {n}{:.0}", + "{n} folder{} could not be read": "Pastas que não puderam ser lidas: {n}{:.0}", "{n} found · {sel} selected": "{n} encontradas · {sel} selecionadas", "{n} photos": "{n} fotos", "{n} photos in {} are hidden by the filters above": "{n} fotos em {} estão ocultas pelos filtros acima", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 47c8098394..82d695bba8 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1933,6 +1933,7 @@ "Metadata read": "Metadados lidos", "Failed": "Com falha", "Stopped": "Interrompido", + "Stopped at the scan limit: there may be more photos": "Parou no limite da verificação: pode haver mais fotos", "Stopped by an error (see the log)": "Interrompido por um erro (veja o log)", "Not saved": "Não salvo", "A folder is being synchronized": "Uma pasta está sendo sincronizada", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 02f8126d96..0bcc2d98f8 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -166,6 +166,8 @@ "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "Изменений не удалось записать на диск: {n}{0:.0}: {e}\nЕсли выйти сейчас, они будут потеряны.{1:.0}", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "Не записано на диск, хранится только в памяти (изменений: {n}): {e}\nLightCraft повторяет попытку автоматически; при выходе сейчас они будут потеряны.{:.0}{:.0}", "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "Изменений сохранено в памяти, но не записано на диск: {n}{:.0}: {e} — LightCraft повторит попытку", + "{n} file{} skipped (not a supported photo type)": "Пропущено файлов (неподдерживаемый тип фото): {n}{:.0}", + "{n} folder{} could not be read": "Папок, которые не удалось прочитать: {n}{:.0}", "{n} found · {sel} selected": "Найдено: {n} · выбрано: {sel}", "{n} photos": "Фото: {n}", "{n} photos in {} are hidden by the filters above": "Фильтры выше скрывают фото в разделе «{}»: {n}", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 4bec3def29..a34312643d 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1862,6 +1862,7 @@ "Metadata read": "Метаданные прочитаны", "Failed": "Ошибки", "Stopped": "Остановлено", + "Stopped at the scan limit: there may be more photos": "Остановлено на пределе сканирования: возможно, есть другие фото", "Stopped by an error (see the log)": "Остановлено из-за ошибки (см. журнал)", "Not saved": "Не сохранено", "A folder is being synchronized": "Папка синхронизируется", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 7d40388d1b..d6619228aa 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -320,5 +320,7 @@ "{name} is installed and in use: face recognition is on": "{name} är installerad och används: ansiktsigenkänning är på", "Creates {stacks} stack{} from {photos} of {scope}": "Skapar staplar: {stacks} · foton: {photos} av {scope}{:.0}", "{n} selected photo{} · {pages} page{}": "Markerade foton: {n} · sidor: {pages}{:.0}{:.0}", - "{n} photo{} in view · {slides} slide{} · {time}": "Foton i vyn: {n} · bilder: {slides} · {time}{:.0}{:.0}" + "{n} photo{} in view · {slides} slide{} · {time}": "Foton i vyn: {n} · bilder: {slides} · {time}{:.0}{:.0}", + "{n} folder{} could not be read": "Mappar som inte gick att läsa: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index f88ce066d7..df2b0859ae 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2463,5 +2463,6 @@ "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Knappen Taggar visar platshållare för mallen, till exempel {date} eller {seq}. Varje fil byter namn på disken tillsammans med sin XMP-sidofil; ett namn som redan finns får -1, -2…", "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", - "Bottom bar": "Nedre fältet" + "Bottom bar": "Nedre fältet", + "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 1bdab6dc34..70dae2280f 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -161,6 +161,8 @@ "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "Змін не вдалося записати на диск: {n}{0:.0}: {e}\nЯкщо вийти зараз, їх буде втрачено.{1:.0}", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "Змін збережено в пам’яті, але не записано на диск: {n}{:.0}: {e}\nLightCraft повторює спроби автоматично; вихід зараз призведе до їхньої втрати.{:.0}", "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "Змін збережено в пам’яті, але не записано на диск: {n}{:.0}: {e} — LightCraft повторить спробу", + "{n} file{} skipped (not a supported photo type)": "Пропущено файлів (непідтримуваний тип фото): {n}{:.0}", + "{n} folder{} could not be read": "Папок, які не вдалося прочитати: {n}{:.0}", "{n} found · {sel} selected": "Знайдено: {n} · вибрано: {sel}", "{n} photos": "Фото: {n}", "{n} photos in {} are hidden by the filters above": "Фільтри вище приховують фото в «{}»: {n}", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index a2c3c9ea0d..5980811b38 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2116,6 +2116,7 @@ "Metadata read": "Метадані прочитано", "Failed": "Помилки", "Stopped": "Зупинено", + "Stopped at the scan limit: there may be more photos": "Зупинено на межі сканування: можливо, є й інші фото", "Stopped by an error (see the log)": "Зупинено через помилку (див. журнал)", "Not saved": "Не збережено", "A folder is being synchronized": "Тека синхронізується", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index dbf1d28db5..a3a944ce39 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -317,5 +317,7 @@ "Panel layout could not be restored: {error}": "Không thể khôi phục bố cục bảng: {error}", "Panel move was not applied: {error}": "Việc di chuyển bảng chưa được áp dụng: {error}", "{name} is installed": "{name} đã được cài đặt", - "{name} is installed and in use: face recognition is on": "{name} đã được cài đặt và đang dùng: nhận diện khuôn mặt đã bật" + "{name} is installed and in use: face recognition is on": "{name} đã được cài đặt và đang dùng: nhận diện khuôn mặt đã bật", + "{n} folder{} could not be read": "Thư mục không đọc được: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index c0d3bfdbfb..95369fa1f9 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2688,5 +2688,6 @@ "Set up name suggestions…": "Thiết lập gợi ý tên…", "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", - "Bottom bar": "Thanh dưới cùng" + "Bottom bar": "Thanh dưới cùng", + "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 900d30b428..b81b358848 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -96,6 +96,8 @@ "{name} On": "已开启 {name}", "{name} — double-click to reset it": "{name} — 双击可重置", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} 项更改已保存在内存中,但尚未写入磁盘:{e}\nLightCraft 会自动重试;现在退出将丢失这些更改。{0:.0}{1:.0}", + "{n} file{} skipped (not a supported photo type)": "已跳过的文件(不是支持的照片类型):{n} 个{:.0}", + "{n} folder{} could not be read": "无法读取的文件夹:{n} 个{:.0}", "{n} found · {sel} selected": "找到 {n} 张 · 已选 {sel} 张", "{n} photos": "{n} 张照片", "{n} photos in {} are hidden by the filters above": "{0} 中的 {n} 张照片被上方的过滤器隐藏", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index c7201b9a56..995a204f4f 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1927,6 +1927,7 @@ "Metadata read": "已读取元数据", "Failed": "失败", "Stopped": "已停止", + "Stopped at the scan limit: there may be more photos": "已在扫描上限处停止:可能还有更多照片", "Stopped by an error (see the log)": "因错误而停止(见日志)", "Not saved": "未保存", "A folder is being synchronized": "正在同步文件夹", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index a451e955d5..fc93b2b603 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -117,6 +117,8 @@ "{name} On": "開啟{name}", "{name} — double-click to reset it": "{name} — 按兩下可重設", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} 項變更{:.0}已保留在記憶體,但尚未寫入磁碟:{e}\nLightCraft 會自動重試;現在結束程式會遺失{}。", + "{n} file{} skipped (not a supported photo type)": "已略過的檔案(不是支援的照片類型):{n} 個{:.0}", + "{n} folder{} could not be read": "無法讀取的資料夾:{n} 個{:.0}", "{n} found · {sel} selected": "找到 {n} 張 · 已選取 {sel} 張", "{n} photos": "{n} 張照片", "{n} photos in {} are hidden by the filters above": "{}中的 {n} 張照片被上方篩選條件隱藏", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 3b75e1ab6e..d8b6d143b0 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1933,6 +1933,7 @@ "Metadata read": "已讀取中繼資料", "Failed": "失敗", "Stopped": "已停止", + "Stopped at the scan limit: there may be more photos": "已在掃描上限處停止:可能還有更多照片", "Stopped by an error (see the log)": "因錯誤而停止(請見記錄)", "Not saved": "未儲存", "A folder is being synchronized": "正在同步資料夾", diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index c927608e01..4336e5e82f 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -3,10 +3,11 @@ //! a grid of thumbnails with checkboxes (duplicates marked and unchecked; Shift-click sets a //! range), the destination (add in place / copy or move into the library's `Originals/` or a //! chosen folder, filed by day, by month, into one folder or by a custom folder template, -//! optionally renamed), an album (existing or new), a preset and keywords to apply. Importing -//! runs on a worker thread (files are probed, copied or moved there) and its batches join the -//! catalog between frames, with a row and ✕ in the activity stack (issue #345); the whole import is -//! one undo step. +//! optionally renamed), an album (existing or new), a preset and keywords to apply. When the scan +//! left something out (a walk cut at its limit, folders it couldn't read, files that are not +//! photos) one line under the count says so ([`scan_note`]). Importing runs on a worker thread +//! (files are probed, copied or moved there) and its batches join the catalog between frames, with +//! a row and ✕ in the activity stack (issue #345); the whole import is one undo step. use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; use lightcraft_engine::import::{ @@ -28,6 +29,7 @@ mod task; #[cfg(test)] pub(crate) use body::grid_height; +pub(crate) use body::scan_note; #[cfg(test)] pub(crate) use body::thumb_edge; #[cfg(test)] @@ -80,6 +82,14 @@ pub struct ImportDialog { /// What to do with those: `restore` (the default: the photo comes back with its edits), `fresh` /// (imported as a new photo, the old record deleted) or "" (leave them) — the `onDeleted` param. pub on_deleted: String, + /// The scan's folder walk stopped at a depth or entry limit: there may be more photos than the + /// review lists ([`ScanOutput::truncated`]; `scanLimited` in the `library.importPreview` reply). + pub scan_limited: bool, + /// Folders the scan couldn't list ([`ScanOutput::unreadable`]). + pub unreadable: usize, + /// Files in the scanned folders that are not a supported photo type, XMP sidecars not counted + /// ([`ScanOutput::unsupported`]). + pub unsupported: usize, /// The candidate clicked last: where a Shift-click range starts ([`ImportDialog::click`]). #[serde(skip)] pub last_clicked: Option, diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index 61e0bfb1bd..d461d690ab 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -78,6 +78,24 @@ pub(super) fn dup_counts(d: &ImportDialog) -> (usize, usize, usize) { (dups, in_source, trashed) } +/// The one line that says what the scan left out, for the review's header: a folder walk that +/// stopped at its limit, folders it couldn't read, files that are not a supported photo type. +/// `None` when it left nothing out (the review then shows no line at all). +pub(crate) fn scan_note(d: &ImportDialog) -> Option { + let plural = |n: usize| if n == 1 { "" } else { "s" }; + let mut parts: Vec = Vec::new(); + if d.scan_limited { + parts.push(crate::i18n::tr("Stopped at the scan limit: there may be more photos").to_string()); + } + if d.unreadable > 0 { + parts.push(crate::i18n::tr_format!("{n} folder{} could not be read", plural(d.unreadable), n = d.unreadable)); + } + if d.unsupported > 0 { + parts.push(crate::i18n::tr_format!("{n} file{} skipped (not a supported photo type)", plural(d.unsupported), n = d.unsupported)); + } + (!parts.is_empty()).then(|| parts.join(" · ")) +} + /// The dialog body: options, then the candidate grid. pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { let t = Tokens::get(ui.ctx()); @@ -107,6 +125,11 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { } }); }); + // what the scan left out, when it left something out + if let Some(note) = scan_note(d) { + let r = ui.label(egui::RichText::new(note).color(t.caution).small()); + register(ui, "label:importScanNote", r.rect); + } // with more than one file type: a toggle per type checks or unchecks all of its files let types = d.file_types(); if types.len() > 1 { diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index c82f67123c..f4d22079a4 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -239,7 +239,13 @@ pub fn browse(app: &mut LightcraftApp, path: &str, subfolders: Option) -> let candidates = queue.iter().cloned().map(|path| lightcraft_engine::import::ImportCandidate { path, ..Default::default() }).chain(known).collect(); // the probes of earlier scans go back to the session with the result, for the import that follows - let _ = tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { candidates, probes: input.take_probes() })); + let _ = tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { + candidates, + probes: input.take_probes(), + truncated: false, + unreadable: 0, + unsupported: 0, + })); }; #[cfg(not(target_arch = "wasm32"))] std::thread::spawn(job); @@ -360,11 +366,19 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { return; } if out.candidates.is_empty() { - app.toast(ctx, crate::i18n::tr("No photos found")); + // (what the scan left out is said here too: a scan that found no photos may have had folders it + // could not read, or files that are not photos, and the note is the same one the review shows) + let left_out = ImportDialog { scan_limited: out.truncated, unreadable: out.unreadable, unsupported: out.unsupported, ..Default::default() }; + let text = match super::scan_note(&left_out) { + Some(note) => format!("{} · {note}", crate::i18n::tr("No photos found")), + None => crate::i18n::tr("No photos found").to_string(), + }; + app.toast(ctx, text); return; } app.renderer.forget_imports(); let mut d = ImportDialog::new(out.candidates); + (d.scan_limited, d.unreadable, d.unsupported) = (out.truncated, out.unreadable, out.unsupported); let trashed = d .candidates .iter() diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 08094f8410..a9f8b72cba 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -40,6 +40,7 @@ mod grid; mod grid_drag; mod guided_guides; mod histogram_drag; +mod import_scan_note; mod import_thumbnails; mod info_dialogs; mod keymap; diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index 6136ccf93f..ad661e9f19 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -1198,7 +1198,14 @@ fn auto_import_waits_for_a_browse_that_starts_during_its_listing() { assert!(h.app.import.is_none(), "no Auto Import for the browse to replace"); // the browse finds one photo of its own and imports it let found = ImportCandidate { path: dir.path("trip/a.png"), ..Default::default() }; - tx.send(crate::import::ScanEnd::Done(ScanOutput { candidates: vec![found], probes: Default::default() })).unwrap(); + tx.send(crate::import::ScanEnd::Done(ScanOutput { + candidates: vec![found], + probes: Default::default(), + truncated: false, + unreadable: 0, + unsupported: 0, + })) + .unwrap(); drop(tx); assert!(h.step_until(T, |h| h.app.import.is_some()), "the browse starts its import"); assert!(h.step_until(T, |h| h.app.import.is_none()), "and it ends"); diff --git a/crates/ui-egui/src/tests/import_scan_note.rs b/crates/ui-egui/src/tests/import_scan_note.rs new file mode 100644 index 0000000000..f0cf4bf816 --- /dev/null +++ b/crates/ui-egui/src/tests/import_scan_note.rs @@ -0,0 +1,242 @@ +//! The import review says what its scan left out: one line, and only when it left something out. +//! +//! * Files in the folder that are not photos (a text file beside the pictures): the review lists +//! the pictures and says how many files were skipped. +//! * A folder tree deeper than a scan goes: the review says that there may be more photos. +//! * A folder of pictures only: no line at all. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde_json::json; + +use crate::dialogs::import::{ImportDialog, scan_note}; +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +const STOPPED: &str = "Stopped at the scan limit: there may be more photos"; + +/// A scratch folder that goes away with the test, however it ends. +struct Scratch(PathBuf); + +impl Scratch { + fn new(tag: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("lc-ui-scan-note-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn write_png(path: &Path, seed: u8) { + let (w, h) = (24usize, 16usize); + let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 9) as u8, (i / w * 13) as u8, seed, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); +} + +fn headless() -> Headless { + let app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services { png: None, ..Default::default() }); + Headless::new(app, [1300.0, 900.0], 1.0) +} + +/// File → Import from Folder… for `dir`, and wait for the review to open. +fn open_review(h: &mut Headless, dir: &Scratch) { + let r = h.request("engine.execute", json!({"command": "file.addFolder", "params": {"path": dir.0.to_string_lossy()}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.step_until(T, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "no import review: {:?}", h.app.ui.dialog); +} + +fn review(h: &mut Headless) -> &mut ImportDialog { + let Some(Dialog::Import { opts }) = &mut h.app.ui.dialog else { panic!("no import review") }; + opts +} + +/// The review painted a text that is exactly `line`. +fn shows(h: &Headless, line: &str) -> bool { + h.painted_text().iter().any(|t| t == line) +} + +/// The review painted any of the scan's notes. +fn shows_any_note(h: &Headless) -> bool { + h.painted_text().iter().any(|t| t.contains(STOPPED) || t.contains("could not be read") || t.contains("skipped (not a supported photo type)")) +} + +fn has_note_widget(h: &mut Headless) -> bool { + h.request("ui.widgets", json!({}), T).to_string().contains("label:importScanNote") +} + +/// A text file beside the pictures: the review lists the pictures, and says one file was skipped. +#[test] +fn the_review_says_how_many_files_were_skipped() { + let dir = Scratch::new("skipped"); + write_png(&dir.0.join("a.png"), 1); + write_png(&dir.0.join("trip").join("b.png"), 2); + std::fs::write(dir.0.join("notes.txt"), b"not a photo").unwrap(); + let mut h = headless(); + open_review(&mut h, &dir); + let d = review(&mut h); + assert_eq!(d.candidates.len(), 2); + assert_eq!((d.scan_limited, d.unreadable, d.unsupported), (false, 0, 1)); + h.step(); + assert!(shows(&h, "1 file skipped (not a supported photo type)"), "{:?}", h.painted_text()); + assert!(has_note_widget(&mut h), "the line is a registered widget"); +} + +/// Nothing to import but a file that is not a photo: no review opens, and the message says why +/// nothing was found, the same skipped count the review would have shown. +#[test] +fn an_empty_scan_says_what_it_left_out() { + let dir = Scratch::new("empty-skipped"); + std::fs::write(dir.0.join("notes.txt"), b"not a photo").unwrap(); + let mut h = headless(); + assert_eq!(scan_empty_folder(&mut h, &dir), "No photos found · 1 file skipped (not a supported photo type)"); + assert!(!matches!(h.app.ui.dialog, Some(Dialog::Import { .. })), "no review for a scan with no photos"); +} + +/// A folder with nothing in it: the plain message, as before. +#[test] +fn an_empty_folder_keeps_the_plain_message() { + let dir = Scratch::new("empty"); + let mut h = headless(); + assert_eq!(scan_empty_folder(&mut h, &dir), "No photos found"); +} + +/// File → Import from Folder… for `dir` (no photos in it): the message the scan leaves. +fn scan_empty_folder(h: &mut Headless, dir: &Scratch) -> String { + let r = h.request("engine.execute", json!({"command": "file.addFolder", "params": {"path": dir.0.to_string_lossy()}}), T); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.step_until(SETTLE, |h| h.app.ui.toast.is_some()), "no message: {:?}", h.app.ui.toast); + h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default() +} + +/// XMP sidecars beside the pictures are read with them, so they are not "skipped": no note for +/// them, but a text file in the same folder still gets its line. +#[test] +fn xmp_sidecars_do_not_make_the_review_say_files_were_skipped() { + let dir = Scratch::new("sidecars"); + write_png(&dir.0.join("a.png"), 1); + std::fs::write(dir.0.join("a.xmp"), b"x").unwrap(); + std::fs::write(dir.0.join("b.XMP"), b"x").unwrap(); + let mut h = headless(); + open_review(&mut h, &dir); + let d = review(&mut h); + assert_eq!((d.candidates.len(), d.scan_limited, d.unreadable, d.unsupported), (1, false, 0, 0)); + h.step(); + assert!(!shows_any_note(&h), "{:?}", h.painted_text()); + assert!(!has_note_widget(&mut h)); + + std::fs::write(dir.0.join("notes.txt"), b"not a photo").unwrap(); + h.app.ui.dialog = None; + open_review(&mut h, &dir); + assert_eq!(review(&mut h).unsupported, 1, "only the text file"); + h.step(); + assert!(shows(&h, "1 file skipped (not a supported photo type)"), "{:?}", h.painted_text()); +} + +/// A tree deeper than a scan goes: the review says that there may be more photos. +#[test] +fn the_review_says_when_the_scan_stopped_at_its_limit() { + let dir = Scratch::new("deep"); + write_png(&dir.0.join("top.png"), 1); + let mut deepest = dir.0.clone(); + for _ in 0..lightcraft_engine::walk::MAX_DEPTH { + deepest = deepest.join("d"); + } + std::fs::create_dir_all(&deepest).unwrap(); + let mut h = headless(); + open_review(&mut h, &dir); + let d = review(&mut h); + assert_eq!((d.candidates.len(), d.scan_limited, d.unreadable, d.unsupported), (1, true, 0, 0)); + h.step(); + assert!(shows(&h, STOPPED), "{:?}", h.painted_text()); +} + +/// Nothing left out: no line, and no widget for it. +#[test] +fn the_review_has_no_note_when_the_scan_left_nothing_out() { + let dir = Scratch::new("clean"); + write_png(&dir.0.join("a.png"), 1); + write_png(&dir.0.join("trip").join("b.png"), 2); + let mut h = headless(); + open_review(&mut h, &dir); + let d = review(&mut h); + assert_eq!((d.candidates.len(), d.scan_limited, d.unreadable, d.unsupported), (2, false, 0, 0)); + h.step(); + assert!(!shows_any_note(&h), "{:?}", h.painted_text()); + assert!(!has_note_widget(&mut h)); +} + +/// The line follows the counters while the review is open, and is written in the language in use. +#[test] +fn the_note_follows_the_counters_and_the_language() { + let dir = Scratch::new("follow"); + write_png(&dir.0.join("a.png"), 1); + let mut h = headless(); + open_review(&mut h, &dir); + assert!(!shows_any_note(&h)); + + let all = format!("{STOPPED} · 2 folders could not be read · 3 files skipped (not a supported photo type)"); + { + let d = review(&mut h); + (d.scan_limited, d.unreadable, d.unsupported) = (true, 2, 3); + } + h.step(); + h.step(); + assert!(shows(&h, &all), "{:?}", h.painted_text()); + + { + let d = review(&mut h); + (d.scan_limited, d.unreadable, d.unsupported) = (false, 1, 1); + } + h.step(); + h.step(); + assert!(shows(&h, "1 folder could not be read · 1 file skipped (not a supported photo type)"), "{:?}", h.painted_text()); + + { + let d = review(&mut h); + (d.scan_limited, d.unreadable, d.unsupported) = (true, 1, 1); + } + assert_eq!(h.request("engine.execute", json!({"command": "app.language.german"}), T)["ok"], true); + h.settle(SETTLE); + let german = "Am Suchlimit angehalten: Es gibt möglicherweise weitere Fotos · Ordner, die nicht gelesen werden konnten: 1 · Übersprungene Dateien (kein unterstützter Fototyp): 1"; + assert!(shows(&h, german), "{:?}", h.painted_text()); + assert_eq!(h.request("engine.execute", json!({"command": "app.language.english"}), T)["ok"], true); + + { + let d = review(&mut h); + (d.scan_limited, d.unreadable, d.unsupported) = (false, 0, 0); + } + h.step(); + h.step(); + assert!(!shows_any_note(&h), "back to nothing left out: {:?}", h.painted_text()); +} + +/// The wording, one part per thing left out, joined into one line; singular and plural. +#[test] +fn the_note_names_each_thing_that_was_left_out() { + let note = |scan_limited, unreadable, unsupported| scan_note(&ImportDialog { scan_limited, unreadable, unsupported, ..Default::default() }); + assert_eq!(note(false, 0, 0), None); + assert_eq!(note(true, 0, 0).as_deref(), Some(STOPPED)); + assert_eq!(note(false, 1, 0).as_deref(), Some("1 folder could not be read")); + assert_eq!(note(false, 4, 0).as_deref(), Some("4 folders could not be read")); + assert_eq!(note(false, 0, 1).as_deref(), Some("1 file skipped (not a supported photo type)")); + assert_eq!(note(false, 0, 12).as_deref(), Some("12 files skipped (not a supported photo type)")); + assert_eq!( + note(true, 2, 2).as_deref(), + Some(format!("{STOPPED} · 2 folders could not be read · 2 files skipped (not a supported photo type)").as_str()) + ); +} diff --git a/crates/ui-egui/src/tests/scan_probes.rs b/crates/ui-egui/src/tests/scan_probes.rs index 04c7ad10d0..a8a5bf116f 100644 --- a/crates/ui-egui/src/tests/scan_probes.rs +++ b/crates/ui-egui/src/tests/scan_probes.rs @@ -68,7 +68,14 @@ fn a_scan_closed_with_its_cross_hands_back_its_probes_when_the_worker_ends() { h.step(); assert!(h.app.scan.is_none(), "✕ closes the scan at once"); // the worker ends later, with the probes it took - tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { candidates: Vec::new(), probes: probes() })).unwrap(); + tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { + candidates: Vec::new(), + probes: probes(), + truncated: false, + unreadable: 0, + unsupported: 0, + })) + .unwrap(); assert!(h.step_until(T, kept), "the probes came back"); assert!(h.app.ui.dialog.is_none(), "no review opened"); assert!(!failed_toast(&h)); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index e8c0e1a709..ef39208967 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -69,7 +69,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:view.importThumbSize`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/dialogs/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with a remembered 80–320 pt thumbnail-size slider (default 116, independent of the library grid), density-aware previews capped at 1024 px and retention limited to nearby cells; tiny sources are tried once per requested size bucket; renderable raws use a sharper render when the camera JPEG is undersized, retaining the JPEG for preview-only raws or an unavailable/failed render; the pre-import loupe and keyboard culling remain open under #2056; thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/widgets/album_picker.rs`, `crates/ui-egui/src/tests/album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step; when a Copy rename sequence runs out, remaining files are reported as failed and earlier completed transfers stay accounted for. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests/import.rs`). An import (and a scan of a folder scanned before) checks that each file a scan already probed is as it was by asking the disk about up to 16 files at a time (an import batch's files, at most), not one after another (`stat_all`, `crates/engine/src/import/files.rs`), and looks up the sidecars of a batch's photos the same way (`sidecars_of`); on a network share each file was a round trip | +| LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:view.importThumbSize`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/dialogs/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with a remembered 80–320 pt thumbnail-size slider (default 116, independent of the library grid), density-aware previews capped at 1024 px and retention limited to nearby cells; tiny sources are tried once per requested size bucket; renderable raws use a sharper render when the camera JPEG is undersized, retaining the JPEG for preview-only raws or an unavailable/failed render; the pre-import loupe and keyboard culling remain open under #2056; thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/widgets/album_picker.rs`, `crates/ui-egui/src/tests/album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step; when a Copy rename sequence runs out, remaining files are reported as failed and earlier completed transfers stay accounted for. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests/import.rs`). An import (and a scan of a folder scanned before) checks that each file a scan already probed is as it was by asking the disk about up to 16 files at a time (an import batch's files, at most), not one after another (`stat_all`, `crates/engine/src/import/files.rs`), and looks up the sidecars of a batch's photos the same way (`sidecars_of`); on a network share each file was a round trip When the scan left something out, one line under the count says so: the folder walk stopped at its depth or entry limit (“Stopped at the scan limit: there may be more photos”), folders it could not read, and files in the folders that are not a supported photo type (XMP sidecars, which the import reads with their photos, and hidden files are never counted; a file named on its own is always tried); nothing is shown when nothing was left out. `library.importPreview` returns the same as `scanLimited` and `skipped` (`unreadable`, `unsupported`). Browse Folder, Find Missing Photos and the command-line / MCP folder expansion walk with the same limits but do not report these counts (`crates/engine/src/walk.rs`, `crates/engine/src/import.rs`) | | LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → the import review), `crates/ui-egui/src/drop_overlay.rs`, `crates/ui-egui/src/tests/drop_import.rs` | while files are dragged over the window a veil and a card say what dropping does (review N items for import, import N presets, open the face model; a note to close the open dialog first when one is open); photos and folders open the import review as File ▸ Import does (Settings ▸ Import ▸ Import dropped files without review imports them at once; the web build always does); with no library open on the desktop (the launch list, a library that couldn't open) photos wait for the library opened and presets are refused, and the card says so; a drop while a dialog is open (also in the web build) or while an import is running is refused with a toast, and the card says so; a finished scan waits for an open dialog to close before its review opens; the control channel's `ui.dropFiles` hovers or drops files for scripts; dropping onto a specific album not supported | | LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests/import.rs` | | | LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/dialogs/import.rs`) | @@ -923,6 +923,8 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-13 | minor | KEY-SLIDER-RESET: hovering a slider's name or thumb says a double-click resets it; a double-click on the thumb is one undo step, not two; a disabled slider's name doesn't reset it (issue #1436); status unchanged (✅) | | 2026-10-20 | patch | LR-MASK-BRUSH: extreme segments skip intermediate dabs; ordinary spacing and endpoints preserved; status unchanged (🟡) | | 2026-10-12 | minor | LR-META-XMP: bounded complete-APP1 manual JPEG reread, fail-closed sidecar precedence and scoped regression coverage; LR-META-EXIF-FULL: reuse loaded bytes; statuses unchanged | +| 2026-10-13 | minor | LR-IMP-ADD-DIALOG: the import review (and `library.importPreview`) says when its folder scan stopped at the walk limit, could not read folders or skipped files that are not a supported photo type; no walk behaviour changes; status unchanged (✅) | +| 2026-10-13 | minor | LR-IMP-ADD-DIALOG: the import review (and `library.importPreview`) says when its folder scan stopped at the walk limit, could not read folders or skipped files that are not a supported photo type (XMP sidecars are not counted); no walk behaviour changes; status unchanged (✅) | | 2026-10-11 | minor | LR-MERGE-HDR: HDR and panorama merges of raws without colour matrices (CR2, NEF, ARW…) write the colour they open with as DNG tags (issue #965); status unchanged | | 2026-10-12 | minor | LR-META-XMP: Read Metadata from File no longer auto-writes the sidecar it has just read, which added `lc:settings` and hid another app's later `crs:` edits (#934); status unchanged (✅) | | 2026-10-12 | patch | LR-IMP-CAMERA-COVERAGE: CR2 white level from the active area, not the saturated masked rows above it (issue #1272); status unchanged (🟡) | From e50db334530c0e919fb0afbf0c637fc40a40b2e4 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 22:32:41 +0200 Subject: [PATCH 11/24] Cut edited thumbnails from the decoded source, not the file (#3810) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Cut edited thumbnails from the decoded source, not the file In Detail view the decoded source of the photo on screen is held at full size, but the thumbnail branch of `source_ref_plain` only looks for a preview-level source, so each edit re-queued a thumbnail that decoded the original again —1.4 GB of gate usage for one 489 MB file, matching the reported stall on the SMB share. When building a thumbnail job, reuse the photo's decoded source at whatever level it is cached (preview or full), fitting it to the thumbnail's edge, so an edited photo's thumbnail no longer re-reads the original file while its source is already in memory. Test: a_thumbnail_is_cut_from_the_decoded_full_source failed before the change and passes after. * Reuse decoded sources for thumbnail rendering Assisted-by: OpenAI Codex * Web worker: box the fitted source, as SourceRef::Fit holds it Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- apps/lightcraft-web/src/wire.rs | 15 ++++++++++++++- crates/engine/src/media/cache.rs | 10 +++++++--- crates/engine/src/media/tests.rs | 16 ++++++++++++++++ 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/apps/lightcraft-web/src/wire.rs b/apps/lightcraft-web/src/wire.rs index bad3507783..37246ecd80 100644 --- a/apps/lightcraft-web/src/wire.rs +++ b/apps/lightcraft-web/src/wire.rs @@ -33,6 +33,9 @@ pub struct WireJob { pub origin: Source, /// Decode the source at most this long. pub max_edge: usize, + /// Resize an already decoded source exactly as the engine's cached-source path does. + #[serde(default)] + pub fit_edge: Option, pub raw: bool, #[serde(default)] pub relative_wb: bool, @@ -67,7 +70,8 @@ impl WireJob { /// `view`: the slot name, for jobs that keep a stage cache. pub fn from_job(job: &RenderJob, thumb_cached: bool, view: &str) -> WireJob { let max_edge = match &job.source { - SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } | SourceRef::Fit { max_edge, .. } => *max_edge, + SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } => *max_edge, + SourceRef::Fit { from, .. } => from.image.width.max(from.image.height), SourceRef::Loaded(img) => img.image.width.max(img.image.height), SourceRef::Smart { .. } => 2560, }; @@ -77,6 +81,10 @@ impl WireJob { level: job.level, origin: job.origin.clone(), max_edge, + fit_edge: match &job.source { + SourceRef::Fit { max_edge, .. } => Some(*max_edge), + _ => None, + }, raw: job.info.raw, relative_wb: job.info.relative_wb, legacy_relative_wb: job.info.legacy_relative_wb, @@ -196,6 +204,10 @@ impl WorkerCore { src } }; + let src = match job.fit_edge { + Some(max_edge) => SourceRef::Fit { from: Box::new(src), max_edge }.load_source()?, + None => src, + }; let info = src.info_or(job.info()); let mut rendered = match &job.stages { Some(view) => { @@ -472,6 +484,7 @@ mod tests { level: SourceLevel::Thumb, origin, max_edge: 512, + fit_edge: None, raw: false, relative_wb: false, legacy_relative_wb: false, diff --git a/crates/engine/src/media/cache.rs b/crates/engine/src/media/cache.rs index acba8b85be..9d74dcf3e3 100644 --- a/crates/engine/src/media/cache.rs +++ b/crates/engine/src/media/cache.rs @@ -344,13 +344,17 @@ impl MediaCache { { 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 + // a thumbnail of a photo whose preview or full source is decoded (the one in the loupe) is cut from it; not // 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).filter(|b| b.fits_outliers(outliers)) - && (big.camera_profile == wanted.as_ref().map(|(tag, _)| tag.clone()) || (big.from_proxy && self.original_offline(p))) + && let Some(big) = [SourceLevel::Preview, SourceLevel::Full].into_iter().find_map(|level| { + self.get_source(p.id, level).filter(|b| { + b.fits_outliers(outliers) + && (b.camera_profile.as_deref() == wanted.as_ref().map(|(tag, _)| tag.as_str()) || (b.from_proxy && self.original_offline(p))) + }) + }) { return SourceRef::Fit { from: Box::new(big), max_edge: level.max_edge() }; } diff --git a/crates/engine/src/media/tests.rs b/crates/engine/src/media/tests.rs index 0db6e0a958..4790a409b0 100644 --- a/crates/engine/src/media/tests.rs +++ b/crates/engine/src/media/tests.rs @@ -644,3 +644,19 @@ fn an_export_develops_from_a_source_twice_its_size() { } assert_eq!(s.render_job(id, 1600, 1600, false, true).unwrap().level, SourceLevel::Preview, "a view keeps the preview"); } + +#[test] +fn a_thumbnail_is_cut_from_the_decoded_full_source() { + let mut s = crate::Session::new(); + let p = Photo::new(PhotoId(1), Source::File { path: "/nowhere/a.ARW".into() }, "a.ARW", "ARW", 2400, 1600, ""); + s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(p.clone()) }).unwrap(); + s.media.insert(p.id, SourceLevel::Full, Arc::new(Rgb32f::from_fn(2400, 1600, |x, _| [x as f32 / 2400.0, 0.5, 0.25]))); + let job = s.thumb_job(p.id, 512).unwrap(); + assert!(matches!(job.source, SourceRef::Fit { .. })); + let r = job.run(); + let thumb = r.rendered.as_ref().unwrap(); + assert_eq!((thumb.image.width, thumb.image.height), (512, 341)); + s.accept(&r); + let cached = s.media.get(p.id, SourceLevel::Thumb).unwrap(); + assert_eq!((cached.width, cached.height), (512, 341), "a thumbnail-sized source is kept, not the full source"); +} From 476f9ee86a5ef061eb661890a52a9460a0696433 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 22:42:07 +0200 Subject: [PATCH 12/24] catalog: history steps and versions share segmentation grids (#2154) (#2203) * catalog: history steps and versions share segmentation grids (#2154) Every history step stored its own copy of each segmentation grid, so a photo with AI masks rewrote every unchanged grid (about 220 KB each) with every slider change: on a real library, 183.6 MB of a 187.8 MB catalog.snap was duplicated grids (830 copies of 126 distinct ones). Snapshots now keep each distinct grid once, in Catalog.grids (a new serialization detail, format v10), and the masks of the photo's settings, versions and history steps refer to it by index (SegMask.grid, with the data omitted). The table is built while the snapshot is written and is never held in the live catalog: Journal::open resolves the references back to inline data (Catalog::repair), so rendering, hash64, presets, XMP and log records are unchanged, and catalogs written before v10 load and are upgraded as before. A reference past the table (a damaged snapshot) is cleared and reported, rendering nothing. Measured on 90 history steps over one 1024x1024 grid: the snapshot drops every step's copy of the grid (1.29 MB -> 0.30 MB in the fixture; on the reporter's library, the grids shrink from 181.8 MB to the 25.9 MB of distinct grids). * catalog: the snapshot's shared grids cover the import look too (#2154) A photo's import look (Photo.import_look, the settings a user default preset gave the photo on import) can hold segmentation masks, and its grids can be the same grids that the develop settings, versions or history steps hold. The snapshot writer referred to such a grid by its table index, but the table was built from the other settings holders only and the load resolved only those, so the look's mask came back empty with a dangling reference. Photo::settings_holders lists every settings holder (develop settings, versions, history steps, import look). The writer builds the table from it and the load resolves references through the same list, so a holder added there is covered on both sides. New test import_look_masks_share_the_table_and_resolve_on_load: a look whose mask shares a grid with the develop settings and a history step, plus a grid only the look holds. It reloads exactly, and the table holds both grids once each. Before this change the look's mask came back as data "" with grid Some(0). * catalog: state what a snapshot copy shares (#2154) The snapshot writer copies the catalog to serialize it. Its photos are shared (Catalog.photos holds Arc), so the copy is a pointer per photo, not a deep copy; the comment said so without saying which tables are copied. It now lists them, and notes that the derived indexes start empty on the copy. * develop: a segmentation grid reference is written only by a snapshot (#2154) The inline serialization of a mask wrote its `grid` whenever one was set. A `grid` can be set in memory from a document: a mask given to a command (mask.update, develop.merge) or read from a preset goes through the derived Deserialize, and such a value stayed in the live catalog. The next snapshot wrote it inline, and on load the index resolved to whatever grid sat at that position in the new table, so a mask could take another mask's grid without a repair being reported. The same stray value also changed hash64 for identical settings. The inline form no longer writes `grid`, so it is the pre-v10 form again. Only the snapshot interner writes a reference, into the table it builds, so a snapshot cannot hold an index that points elsewhere. New tests: stray_grid_is_never_written_outside_the_interner (develop) and stray_grid_from_a_document_is_not_written_as_a_reference (catalog: a stray reference is not resolved to another photo's grid after a reload). Both failed before this change: the first wrote "grid":3, the second loaded photo one's grid into photo two. * Address review for pull request 2203 * Format the files this pull request changes * catalog: don't clone a grid that is already in the snapshot's table The snapshot's grid interning indexed with `entry(m.data.clone())`: the whole grid was copied before the map said whether it was already there, so every history step that repeats a mask's grid paid a needless allocation and copy on the snapshot path. The lookup is borrowed now (`contains_key`), and a grid is cloned (into the pool and the table) only when it is new, in the same first-appearance order. The background snapshot also held two catalogs: `snapshot_in_background` clones the catalog for the worker, and `write_snapshot` cloned it again to attach the grid pool. The writer now takes the catalog by value and the background path hands over its copy, so a snapshot in flight holds one catalog; the synchronous path keeps its own single clone. Not observable in behaviour: the grid tests and the catalog suite pass unchanged. * Tests: the hostile-mask test names the new grid field Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/catalog/src/journal.rs | 54 ++- crates/catalog/src/lib.rs | 45 +++ crates/catalog/src/model.rs | 17 + crates/catalog/src/tests_format_version.rs | 5 +- crates/catalog/src/tests_grids.rs | 392 +++++++++++++++++++++ crates/develop/src/lib.rs | 2 +- crates/develop/src/segmask.rs | 123 ++++++- crates/develop/src/settings.rs | 66 ++++ crates/engine/src/segment.rs | 2 +- crates/pipeline/src/mask_space.rs | 4 +- crates/pipeline/src/masks/tests.rs | 7 +- 11 files changed, 702 insertions(+), 15 deletions(-) create mode 100644 crates/catalog/src/tests_grids.rs diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index c236da0144..75ec07e59f 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -25,6 +25,12 @@ //! - a bad record **followed by good ones** is real damage: replay stops there, the log is kept //! as `catalog.log.damaged-`, and a fresh snapshot is written so the library stays usable. //! +//! Segmentation grids are shared within a snapshot (issue #2154): each distinct grid is written +//! once into `Catalog.grids` and the masks of the photo's develop settings, versions, history +//! steps and import look refer to it by index, so an unchanged mask no longer repeats with every +//! history step. The table lives only in the snapshot file; log records keep the full grids +//! inline. +//! //! **Background compaction** ([`Journal::snapshot_in_background`], when the store offers a //! [`Store::background_writer`]): a worker thread writes the snapshot of a copy of the catalog at //! op `N` while appends go on (durably, as always) to the same log. Once the snapshot is durable, @@ -57,6 +63,7 @@ //! | 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` | +//! | 12 | history steps and versions share segmentation grids (#2154) | `Catalog.grids`, `SegMask.grid` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -81,7 +88,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 = 11; +pub const VERSION: u32 = 12; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] @@ -342,8 +349,19 @@ fn resync(line: &[u8], last: u64) -> Option<(usize, (u64, Op))> { /// Write `catalog.snap` for the state after op `seq`, streaming the JSON into the store (no /// whole-file string). The bytes are exactly /// `{"format":"lightcraft-catalog","version":1,"seq":N,"catalog":}\n`, -/// as before streaming. Fills in the serialise / write+sync times and the size. +/// as before streaming. Each distinct segmentation grid of the photos' settings holders (see +/// `Photo::settings_holders`) is written once (`Catalog.grids`), with the masks referring to it +/// by index, so an unchanged mask does not repeat with every history step (issue #2154). Fills +/// in the serialise / write+sync times and the size. fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io::Result { + write_snapshot_owned(store, seq, catalog.clone()) +} + +/// The same write, taking the catalog by value: the background path hands over the copy it +/// already made, so a snapshot in flight holds one catalog, not two ([`Catalog::clone`] copies +/// the photo pointers and the small tables, and the derived indexes start empty — real work on a +/// large library). +fn write_snapshot_owned(store: &mut dyn Store, seq: u64, mut snapshot: Catalog) -> std::io::Result { let t0 = web_time::Instant::now(); let mut serialize_ms = 0.0; let bytes = store.write_atomic_with(SNAPSHOT, &mut |w| { @@ -353,7 +371,35 @@ fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io // 1 MiB chunks go through the store's `dyn Write` let mut b = std::io::BufWriter::with_capacity(1 << 20, w); write!(b, "{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":{seq},\"catalog\":")?; - serde_json::to_writer(&mut b, catalog).map_err(std::io::Error::other)?; + // The shared grids, in first-appearance order. The pool is a serialization detail: + // `snapshot` itself is never modified (log records, presets and XMP stay inline). + let mut pool: Vec = Vec::new(); + let mut index: std::collections::HashMap = std::collections::HashMap::new(); + { + let mut see = |s: &lightcraft_develop::DevelopSettings| { + s.visit_seg_masks(&mut |m| { + // borrowed lookup: a grid every history step shares is not cloned just to + // find it already indexed (only a new grid is copied, into pool and table) + if !m.data.is_empty() && !index.contains_key(m.data.as_str()) { + index.insert(m.data.clone(), pool.len() as u32); + pool.push(m.data.clone()); + } + }); + }; + for p in snapshot.photos.values() { + for settings in p.settings_holders() { + see(settings); + } + } + } + snapshot.grids = pool; + match lightcraft_develop::with_grid_interner(index, || serde_json::to_writer(&mut b, &snapshot)) { + // no interner can be active here (snapshot writes don't nest), so `None` is a bug: + // fail the write rather than store a truncated or reference-less snapshot + Some(Ok(())) => {} + Some(Err(e)) => return Err(std::io::Error::other(e)), + None => return Err(std::io::Error::other("nested grid interner while writing a snapshot")), + } b.write_all(b"}\n")?; b.flush()?; serialize_ms = ms_since(t); @@ -640,7 +686,7 @@ impl Journal { let Some(mut writer) = self.store.background_writer() else { return self.snapshot(catalog) }; let copy = catalog.clone(); let seq = self.seq; - let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot(writer.as_mut(), seq, ©)); + let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot_owned(writer.as_mut(), seq, copy)); let worker = match spawned { Ok(w) => w, Err(e) => { diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index a892943c9f..5a82d2a67d 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -289,6 +289,13 @@ pub struct Catalog { /// What the library keeps about its folders (folder identity → record), see [`folders`]. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] folder_records: BTreeMap, + /// Segmentation grids shared by this snapshot's masks: each distinct grid's data once, in + /// first-appearance order, referenced by index from the masks ([`lightcraft_develop::\ + /// SegMask::grid`] is a position here). A serialization detail of snapshots + /// ([`journal`]): never held in the live catalog — [`Catalog::repair`] resolves the + /// references and clears the table when a snapshot is read. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + grids: Vec, /// Increments on every applied op, and when a batch fails and its rollback cannot undo it whole (the catalog /// changed, so what is keyed by the revision is out of date). #[serde(skip)] @@ -367,6 +374,25 @@ impl std::fmt::Debug for PlansMemo { } } +/// Resolves the shared-grid references of one settings holder (see [`Photo::settings_holders`]) +/// against a snapshot's grid table: each referenced mask takes its +/// grid's data and the reference is cleared. A reference past the table (a damaged snapshot) +/// leaves the mask empty — it renders nothing, like any other damaged grid. Data present on the +/// mask itself wins over a stray reference. Returns the dangling count added to `dangling`. +fn resolve_grids(settings: &mut Arc, grids: &[String], dangling: usize) -> usize { + let mut dangling = dangling; + Arc::make_mut(settings).visit_seg_masks_mut(&mut |m| { + if let Some(i) = m.grid.take() { + match (m.data.is_empty(), grids.get(i as usize)) { + (true, Some(data)) => m.data = data.clone(), + (true, None) => dangling += 1, + (false, _) => {} + } + } + }); + dangling +} + /// A short memory of what the latest ops changed, so that what is derived from the catalog (the grid's list) can /// follow a small edit without being worked out again from every photo. #[derive(Clone, Debug, Default)] @@ -1192,6 +1218,23 @@ impl Catalog { /// wrote). pub fn repair(&mut self) -> Vec { let mut changed = Vec::new(); + // Segmentation grids shared by the snapshot this was read from (issue #2154): each + // reference takes its grid's data, and the table is not kept — a live catalog always + // stores the data inline, so masks render and serialize without the snapshot's table. + // Resolving is the normal way a snapshot in this format reads (not reported); a + // reference past the table is damage and is reported — that includes a reference into + // an empty table, which is always dangling, so the table being empty does not skip it. + let grids = std::mem::take(&mut self.grids); + let mut dangling = 0usize; + for p in self.photos.values_mut() { + let photo = Arc::make_mut(p); + for settings in photo.settings_holders_mut() { + dangling = resolve_grids(settings, &grids, dangling); + } + } + if dangling > 0 { + changed.push(format!("{dangling} segmentation grid reference(s) pointed past the shared table: cleared")); + } for (id, p) in self.photos.iter_mut() { if p.id != *id { changed.push(format!("photo {} was filed as {}", p.id.0, id.0)); @@ -1488,6 +1531,8 @@ mod tests_folders; #[cfg(test)] mod tests_format_version; #[cfg(test)] +mod tests_grids; +#[cfg(test)] mod tests_index; #[cfg(test)] mod tests_journal; diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 5bd0371848..cc28609941 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -439,6 +439,23 @@ impl Photo { pub fn relative_wb(&self) -> bool { self.develops_raw() && relative_wb_camera(&self.format, &self.meta.camera) } + /// Every settings holder of this photo that can carry segmentation grids: the develop + /// settings, the versions', the history steps' and the import look. A snapshot's shared grid + /// table ([`crate::Catalog`]'s `grids`) covers all of them, so a new holder belongs here. + pub(crate) fn settings_holders(&self) -> impl Iterator> { + std::iter::once(&self.develop) + .chain(self.versions.iter().map(|v| &v.settings)) + .chain(self.history.iter().map(|h| &h.settings)) + .chain(self.import_look.iter()) + } + /// [`Photo::settings_holders`] with mutable access (resolving a snapshot's grid references). + pub(crate) fn settings_holders_mut(&mut self) -> impl Iterator> { + let Photo { develop, versions, history, import_look, .. } = self; + std::iter::once(develop) + .chain(versions.iter_mut().map(|v| &mut v.settings)) + .chain(history.iter_mut().map(|h| &mut h.settings)) + .chain(import_look.as_mut()) + } /// The develop settings import gave this photo: [`Photo::camera_defaults`], or the user's /// default preset applied on top of them ([`Photo::import_look`]). Like the camera defaults, /// in the photo's own rendering process. diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index ada4138307..612ee4586b 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -238,8 +238,9 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v11: `EmbeddedLens.source` (v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`). - const NEWEST_FIELDS: u32 = 11; + /// v12: `Catalog.grids` and `SegMask.grid`, shared by a snapshot's masks (#2154) (v11: `EmbeddedLens.source`; v10: `Mask.on_photo`; v9: + /// `Photo.preview_checked` and `Op::SetContent.preview_checked`). + const NEWEST_FIELDS: u32 = 12; 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"); } diff --git a/crates/catalog/src/tests_grids.rs b/crates/catalog/src/tests_grids.rs new file mode 100644 index 0000000000..54289565fb --- /dev/null +++ b/crates/catalog/src/tests_grids.rs @@ -0,0 +1,392 @@ +//! Issue #2154: a snapshot keeps each distinct segmentation grid once (`Catalog.grids`) and the +//! masks of the develop settings, versions, history steps and import look refer to it by index, +//! so an unchanged mask no longer repeats with every history step. In-memory catalogs and log +//! records always hold the grids inline; older catalogs (inline everywhere) load and are upgraded. + +use std::sync::Arc; + +use lightcraft_develop::{DevelopSettings, Mask, MaskComponent, MaskOp, MaskShape, SegMask}; + +use crate::journal::{LOG, SNAPSHOT, VERSION}; +use crate::*; + +fn snapshot_version(m: &MemStore) -> u64 { + let v: serde_json::Value = serde_json::from_slice(&m.get(SNAPSHOT).unwrap()).unwrap(); + v["version"].as_u64().unwrap() +} + +fn open(m: &MemStore) -> (Journal, Catalog, LoadReport) { + Journal::open(Box::new(m.clone())).unwrap() +} + +/// Develop settings with one AI mask over an object segmentation. +fn settings_with_seg(seg: SegMask, exposure: f64) -> DevelopSettings { + let mut s = DevelopSettings::default(); + s.light.exposure = exposure; + s.masks.push(Mask { + id: 1, + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Object { + hint: vec![lightcraft_geom::Point::new(0.5, 0.5)], + exclude: vec![], + seg: Some(seg), + detail: vec![], + edge: 0.0, + }, + }], + ..Default::default() + }); + s +} + +/// One mask (`id`) whose only component is an Object segmentation `seg`. +fn object_mask(id: u32, seg: SegMask) -> Mask { + Mask { + id, + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Object { + hint: vec![lightcraft_geom::Point::new(0.5, 0.5)], + exclude: vec![], + seg: Some(seg), + detail: vec![], + edge: 0.0, + }, + }], + ..Default::default() + } +} + +/// A catalog of one photo whose history is `steps` slider edits over the same mask, plus the +/// ops that built it (each step is one `SetDevelop` + one `PushHistory`, as the engine commits +/// an edit) and the shared grid's bytes. +fn masked_catalog(steps: usize) -> (Catalog, Vec, PhotoId, String) { + let seg = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]); + let blob = seg.data.clone(); + let mut c = Catalog::new(); + let id = c.alloc_photo_id(); + let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::File { path: "/p/1.jpg".into() }, "1.jpg", "JPEG", 60, 40, "2026-01-01")) }; + c.apply(add.clone()).unwrap(); + let mut ops = vec![add]; + for i in 1..=steps { + let settings = Arc::new(settings_with_seg(seg.clone(), f64::from(i as u32) * 0.1)); + let op = Op::Batch { + ops: vec![ + Op::SetDevelop { id, settings: settings.clone(), label: "Exposure".into(), edited: Some(format!("t{i}")) }, + Op::PushHistory { id, step: HistoryStep { label: "Exposure".into(), settings } }, + ], + }; + c.apply(op.clone()).unwrap(); + ops.push(op); + } + (c, ops, id, blob) +} + +/// N history steps over one mask store the grid exactly once and load back identical. +#[test] +fn snapshot_deduplicates_shared_grid() { + let (live, ops, id, blob) = masked_catalog(20); + let m = MemStore::new(); + let (mut j, _, report) = open(&m); + assert!(report.created); + j.append(&ops).unwrap(); + j.snapshot(&live).unwrap(); + drop(j); + + let snap_bytes = m.get(SNAPSHOT).unwrap(); + let body = std::str::from_utf8(&snap_bytes).unwrap(); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + assert_eq!(body.match_indices(&blob).count(), 1, "the grid is stored once for every step that shares it"); + let v: serde_json::Value = serde_json::from_str(body).unwrap(); + assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 1); + + let (_, loaded, report) = open(&m); + assert_eq!((report.replayed, report.upgraded_from, report.repaired.len()), (0, None, 0)); + assert_eq!(loaded.to_snapshot(), live.to_snapshot()); + let p = loaded.photo(id).unwrap(); + assert_eq!(p.history.len(), 20); + for h in &p.history { + let MaskShape::Object { seg: Some(seg), .. } = &h.settings.masks[0].components[0].shape else { panic!("an Object mask") }; + assert_eq!((seg.data.as_str(), seg.grid), (blob.as_str(), None), "every step's grid is back inline"); + } +} + +/// A catalog written before the shared table (grids inline everywhere, format v9) loads as it +/// was and its upgrade rewrite deduplicates. +#[test] +fn v9_catalog_with_inline_grids_loads_and_is_upgraded() { + let (live, _, _, blob) = masked_catalog(3); + let body = live.to_snapshot(); + assert!(body.contains(&blob), "a live catalog stores its grids inline"); + let m = MemStore::new(); + m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":9,\"seq\":2,\"catalog\":{body}}}\n").into_bytes()); + let (_, loaded, report) = open(&m); + assert_eq!((report.replayed, report.upgraded_from), (0, Some(9))); + assert_eq!(loaded.to_snapshot(), live.to_snapshot()); + // rewritten in this format before anything is appended, with the grid once + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + let rewritten_bytes = m.get(SNAPSHOT).unwrap(); + let rewritten = std::str::from_utf8(&rewritten_bytes).unwrap(); + assert_eq!(rewritten.match_indices(&blob).count(), 1); + assert!(rewritten.contains("\"grids\":["), "the shared table is in the file"); +} + +/// The op log is not deduplicated: every record keeps the grids inline (a log never carries the +/// shared table), and replaying it rebuilds the same state. +#[test] +fn log_records_keep_their_grids_inline() { + let (live, ops, _, blob) = masked_catalog(2); + let m = MemStore::new(); + let (mut j, _, _) = open(&m); + j.append(&ops).unwrap(); + drop(j); // no snapshot: the log holds the whole state + let log_bytes = m.get(LOG).unwrap(); + let log = std::str::from_utf8(&log_bytes).unwrap(); + assert_eq!(log.match_indices(&blob).count(), 4, "two edits, SetDevelop + PushHistory each, inline"); + let (_, loaded, report) = open(&m); + assert_eq!(report.replayed, 3, "the photo and the two edits"); + assert_eq!(loaded.to_snapshot(), live.to_snapshot()); +} + +/// A reference that points past the shared table is cleared (the mask renders nothing, like any +/// damaged grid); a good reference resolves back to the full grid. +#[test] +fn shared_grid_references_resolve_or_are_repaired() { + let (live, _, id, blob) = masked_catalog(1); + let inline = live.to_snapshot(); + + // a damaged snapshot: the develop mask refers past the one-entry table + let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":7", 1); + let m = MemStore::new(); + m.set( + SNAPSHOT, + format!( + "{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"dHdv\"],{} }} }}\n", + &body[1..body.len() - 1] + ) + .into_bytes(), + ); + let (_, damaged, report) = open(&m); + assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired); + assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired); + let p = damaged.photo(id).unwrap(); + let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") }; + assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared, never a crash"); + // the history step's inline grid is untouched + let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") }; + assert_eq!(seg.data, blob); + + // a good reference resolves (the normal way a snapshot in this format reads, so it is not + // reported as a repair): the mask reads exactly as it was written + let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1); + let m = MemStore::new(); + m.set( + SNAPSHOT, + format!( + "{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"{blob}\"],{} }} }}\n", + &body[1..body.len() - 1] + ) + .into_bytes(), + ); + let (_, resolved, report) = open(&m); + assert_eq!(report.repaired, Vec::::new(), "{:?}", report.repaired); + assert_eq!(resolved.to_snapshot(), live.to_snapshot()); +} + +/// The background snapshot path shares the grids too (the interner is per thread). +#[test] +fn background_snapshot_deduplicates_shared_grid() { + let (live, ops, _, blob) = masked_catalog(5); + let mut m = MemStore::new(); + m.background = true; + let (mut j, _, _) = open(&m); + j.append(&ops).unwrap(); + j.snapshot_in_background(&live).unwrap(); + j.wait().unwrap(); + drop(j); + let snap_bytes = m.get(SNAPSHOT).unwrap(); + let body = std::str::from_utf8(&snap_bytes).unwrap(); + assert_eq!(body.match_indices(&blob).count(), 1); + let (_, loaded, _) = open(&m); + assert_eq!(loaded.to_snapshot(), live.to_snapshot()); +} + +/// A version (not only history steps) shares the grid: one photo with a snapshot version and a +/// history step over the same mask stores the grid once. +#[test] +fn versions_share_the_grid_too() { + let seg = SegMask::from_logits(32, &vec![1.0f32; 32 * 32]); + let blob = seg.data.clone(); + let id = PhotoId(1); + let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 0 }, "d.jpg", "JPEG", 60, 40, "2026-01-01")) }; + let settings = Arc::new(settings_with_seg(seg, 0.5)); + let versions = + Op::SetVersions { id, versions: vec![Version { name: "v".into(), created: "2026-01-01".into(), settings: settings.clone(), auto: false }] }; + let history = Op::PushHistory { id, step: HistoryStep { label: "e".into(), settings } }; + let mut live = Catalog::new(); + for op in [&add, &versions, &history] { + live.apply(op.clone()).unwrap(); + } + let m = MemStore::new(); + let (mut j, _, _) = open(&m); + j.append(&[add, versions, history]).unwrap(); + j.snapshot(&live).unwrap(); + drop(j); + let snap_bytes = m.get(SNAPSHOT).unwrap(); + let body = std::str::from_utf8(&snap_bytes).unwrap(); + assert_eq!(body.match_indices(&blob).count(), 1, "the version and the step share the grid"); + let (_, loaded, _) = open(&m); + assert_eq!(loaded.to_snapshot(), live.to_snapshot()); +} + +/// The import look (`Photo.import_look`, the settings a default preset gave the photo on import) +/// can hold AI masks, and their grids can be grids the develop settings or a history step hold. +/// Every settings holder shares the snapshot's table, so the look's masks are referenced and +/// resolved on load like the others; a grid only the look holds is in the table too. +#[test] +fn import_look_masks_share_the_table_and_resolve_on_load() { + let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]); + let look_only = SegMask::from_logits(64, &vec![-0.5f32; 64 * 64]); + let mut look = DevelopSettings::default(); + look.masks.push(object_mask(1, shared.clone())); + look.masks.push(object_mask(2, look_only.clone())); + let mut edit = DevelopSettings::default(); + edit.light.exposure = 0.7; + edit.masks.push(object_mask(1, shared.clone())); + let edit = Arc::new(edit); + + let id = PhotoId(1); + let mut photo = Photo::new(id, Source::File { path: "/p/2.jpg".into() }, "2.jpg", "JPEG", 60, 40, "2026-01-01"); + photo.develop = edit.clone(); + photo.import_look = Some(Arc::new(look)); + photo.history.push(HistoryStep { label: "Exposure".into(), settings: edit }); + let add = Op::AddPhoto { photo: Box::new(photo) }; + let mut live = Catalog::new(); + live.apply(add.clone()).unwrap(); + + let m = MemStore::new(); + let (mut j, _, _) = open(&m); + j.append(&[add]).unwrap(); + j.snapshot(&live).unwrap(); + drop(j); + let snap_bytes = m.get(SNAPSHOT).unwrap(); + let body = std::str::from_utf8(&snap_bytes).unwrap(); + assert_eq!(body.match_indices(&shared.data).count(), 1, "the grid of the look and of the edit is stored once"); + assert_eq!(body.match_indices(&look_only.data).count(), 1); + + let (_, loaded, report) = open(&m); + assert_eq!(report.repaired, Vec::::new(), "{:?}", report.repaired); + let p = loaded.photo(id).unwrap(); + let look_masks = &p.import_look.as_ref().unwrap().masks; + assert_eq!(look_masks.len(), 2); + for (mask, want) in look_masks.iter().zip([&shared, &look_only]) { + let MaskShape::Object { seg: Some(seg), .. } = &mask.components[0].shape else { panic!("an Object mask") }; + assert_eq!((seg.data.as_str(), seg.grid), (want.data.as_str(), None), "the look's grid is back inline"); + } + assert_eq!(loaded.to_snapshot(), live.to_snapshot()); + let v: serde_json::Value = serde_json::from_str(body).unwrap(); + assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 2, "one table entry per distinct grid, the look's included"); +} + +/// A `grid` that arrives from a document (a command's mask JSON, a preset, a merged partial) is +/// not a reference and is never written as one: a snapshot must not resolve it to another mask's +/// grid. Here photo two's mask carries `grid: 0` with empty data, while photo one's grid is the +/// table's entry 0; before the fix the inline form wrote `"grid":0` and the load filled photo two +/// with photo one's grid. +#[test] +fn stray_grid_from_a_document_is_not_written_as_a_reference() { + let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]); + let stray: SegMask = serde_json::from_str(r#"{"side":64,"data":"","grid":0}"#).unwrap(); + assert_eq!(stray.grid, Some(0), "a document can set grid"); + let mut stray_settings = DevelopSettings::default(); + stray_settings.masks.push(object_mask(1, stray)); + + let (one, two) = (PhotoId(1), PhotoId(2)); + let photo = |id: PhotoId, name: &str| Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01"); + let ops = [ + Op::AddPhoto { photo: Box::new(photo(one, "1.jpg")) }, + Op::SetDevelop { id: one, settings: Arc::new(settings_with_seg(shared.clone(), 0.2)), label: "Exposure".into(), edited: Some("t1".into()) }, + Op::AddPhoto { photo: Box::new(photo(two, "2.jpg")) }, + Op::SetDevelop { id: two, settings: Arc::new(stray_settings), label: "Edit".into(), edited: Some("t2".into()) }, + ]; + let mut live = Catalog::new(); + for op in &ops { + live.apply(op.clone()).unwrap(); + } + + let m = MemStore::new(); + let (mut j, _, _) = open(&m); + j.append(&ops).unwrap(); + j.snapshot(&live).unwrap(); + drop(j); + let (_, loaded, report) = open(&m); + assert_eq!(report.repaired, Vec::::new(), "{:?}", report.repaired); + let MaskShape::Object { seg: Some(seg), .. } = &loaded.photo(two).unwrap().develop.masks[0].components[0].shape else { panic!("an Object mask") }; + assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the stray reference is not resolved to photo one's grid"); + assert_eq!(loaded.to_snapshot(), live.to_snapshot()); +} + +/// A snapshot whose shared grid table is empty (`grids: []`) but whose masks still refer into +/// it: the table being empty must not skip the repair. A reference past an empty table is +/// dangling, so it is cleared (the mask renders nothing, like any other damaged grid), the +/// repair is reported, and a mask that carries its own grid inline is left untouched. +#[test] +fn empty_shared_grid_table_clears_dangling_references() { + let (live, _, id, blob) = masked_catalog(1); + let inline = live.to_snapshot(); + + // a damaged snapshot: an empty table, but the develop mask still refers to entry 0 + let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1); + let m = MemStore::new(); + m.set( + SNAPSHOT, + format!( + "{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[],{} }} }}\n", + &body[1..body.len() - 1] + ) + .into_bytes(), + ); + let (_, damaged, report) = open(&m); + assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired); + assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired); + let p = damaged.photo(id).unwrap(); + let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") }; + assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with an empty table"); + + // the history step carries its grid inline: nothing there to resolve, left as it was + let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") }; + assert_eq!(seg.data, blob, "the history step's inline grid is untouched"); +} + +/// A snapshot that omits the shared grid table entirely (no `grids` key) but whose masks still +/// refer into it: an absent table deserializes to an empty Vec, so a reference past it is +/// dangling and is cleared and reported, just like the empty-table case. +#[test] +fn omitted_shared_grid_table_clears_dangling_references() { + let (live, _, id, blob) = masked_catalog(1); + let inline = live.to_snapshot(); + + // a damaged snapshot: no table at all, but the develop mask still refers to entry 0 + let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1); + let m = MemStore::new(); + m.set( + SNAPSHOT, + format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{{} }} }}\n", &body[1..body.len() - 1]) + .into_bytes(), + ); + let (_, damaged, report) = open(&m); + assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired); + assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired); + let p = damaged.photo(id).unwrap(); + let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") }; + assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with no table"); + + // the history step carries its grid inline: nothing there to resolve, left as it was + let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") }; + assert_eq!(seg.data, blob, "the history step's inline grid is untouched"); +} diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index 324fe29a02..cb5acab6f5 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -13,7 +13,7 @@ pub mod settings; pub use controls::{CONTROLS, ControlSpec, Section, Track}; pub use presets::{Preset, SettingsGroup, apply_partial, extract_groups}; -pub use segmask::SegMask; +pub use segmask::{SegMask, with_grid_interner}; pub use settings::*; use serde_json::Value; diff --git a/crates/develop/src/segmask.rs b/crates/develop/src/segmask.rs index de0aede09d..298a53b033 100644 --- a/crates/develop/src/segmask.rs +++ b/crates/develop/src/segmask.rs @@ -1,6 +1,9 @@ //! Model segmentations stored with a mask ([`SegMask`]), so rendering never needs the model. -use serde::{Deserialize, Serialize}; +use std::cell::RefCell; +use std::collections::HashMap; + +use serde::{Deserialize, Serialize, Serializer}; /// Logits are stored in steps of 1/`SCALE`, clamped to ±127/`SCALE` (≈ ±15.9: a sigmoid of /// 1 − 1.2e-7, i.e. fully in or out). @@ -13,15 +16,26 @@ pub const MAX_SIDE: usize = 1024; /// normalized `((x + 0.5) / side, (y + 0.5) / side)`), quantized to `i8`, deflated and base64 /// encoded. Coverage at a point is the sigmoid of the bilinearly sampled logit, so edges stay /// smooth at any output size. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Deserialize)] pub struct SegMask { pub side: u32, + /// The grid's bytes (quantized, deflated, base64), unless this is a reference into the + /// snapshot's shared grid table (`grid` is set and `data` is empty). + #[serde(default)] pub data: String, /// The part of the image the grid covers, normalized `[x0, y0, x1, y1]` (`None` = all of /// it). A zoomed-in pass over one object covers just its surroundings, at a higher /// resolution than a pass over the whole photo. #[serde(default, skip_serializing_if = "Option::is_none")] pub rect: Option<[f64; 4]>, + /// Index into the catalog snapshot's shared grid table (`Catalog::grids`) this mask refers + /// to instead of carrying its own `data`. A serialization detail of snapshots only: the + /// snapshot writer sets it (through the interner, into its own table), `Catalog::repair` + /// resolves it when a snapshot is read, and no other serialization writes it. A `grid` that + /// arrives from any other document (a command, a preset, XMP, a log record) is read but + /// never written back, so it cannot point a snapshot at another mask's grid. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub grid: Option, } impl SegMask { @@ -29,7 +43,7 @@ impl SegMask { pub fn from_logits(side: usize, logits: &[f32]) -> SegMask { let q: Vec = logits.iter().take(side * side).map(|l| ((l * SCALE).round().clamp(-127.0, 127.0) as i8) as u8).collect(); let z = miniz_oxide::deflate::compress_to_vec(&q, 8); - SegMask { side: side as u32, data: base64_encode(&z), rect: None } + SegMask { side: side as u32, data: base64_encode(&z), rect: None, grid: None } } /// From `side × side` logits over the part `rect` of the image. @@ -55,6 +69,63 @@ impl SegMask { } } +// The grid table a snapshot serialization refers to: each distinct grid's data → its index. +thread_local! { + static INTERNER: RefCell>> = const { RefCell::new(None) }; +} + +/// Serializes masks as references into a shared grid table (`grid` = index, `data` omitted) +/// while `f` runs, one thread at a time (snapshot writes). Nested calls are ignored (`None`): +/// the outermost writer owns the table. +pub fn with_grid_interner(map: HashMap, f: impl FnOnce() -> T) -> Option { + INTERNER.with(|i| { + if i.borrow().is_some() { + return None; + } + struct Guard; + impl Drop for Guard { + fn drop(&mut self) { + INTERNER.with(|j| *j.borrow_mut() = None); + } + } + *i.borrow_mut() = Some(map); + let _guard = Guard; + Some(f()) + }) +} + +impl Serialize for SegMask { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeMap; + // While a snapshot is being written with a shared grid table, a mask whose exact bytes + // are in the table refers to it by index instead of repeating the blob (issue #2154). + if !self.data.is_empty() + && let Some(id) = INTERNER.with(|i| i.borrow().as_ref().and_then(|m| m.get(&self.data).copied())) + { + let len = if self.rect.is_some() { 3 } else { 2 }; + let mut map = serializer.serialize_map(Some(len))?; + map.serialize_entry("side", &self.side)?; + map.serialize_entry("grid", &id)?; + if let Some(rect) = self.rect { + map.serialize_entry("rect", &rect)?; + } + return map.end(); + } + // Without a table hit: exactly the pre-v10 derived form (field order and skips included), + // so every serialization that doesn't dedup keeps its bytes (`hash64`, cache keys). `grid` + // is never written here: a value read from some document is dropped on save, and only the + // interner above can write a reference (into the table of the snapshot being written). + let len = 2 + usize::from(self.rect.is_some()); + let mut map = serializer.serialize_map(Some(len))?; + map.serialize_entry("side", &self.side)?; + map.serialize_entry("data", &self.data)?; + if let Some(rect) = self.rect { + map.serialize_entry("rect", &rect)?; + } + map.end() + } +} + /// Most zoomed-in detail patches one AI mask component keeps (the app makes one; each costs a /// decode per render, so a hostile document can't make rendering explode). pub const MAX_DETAIL: usize = 4; @@ -189,7 +260,51 @@ mod tests { assert!(m.logits().is_none(), "size mismatch"); m.side = 100_000; assert!(m.logits().is_none(), "absurd size"); - assert!(SegMask { side: 8, data: "not base64 !".into(), rect: None }.logits().is_none()); + assert!(SegMask { side: 8, data: "not base64 !".into(), rect: None, grid: None }.logits().is_none()); assert!(SegMask { rect: Some([0.5, 0.0, 0.2, 1.0]), ..SegMask::from_logits(2, &[0.0; 4]) }.bounds().is_none()); } + + /// A `grid` read from a document is never written outside the snapshot interner, with or + /// without data: the bytes stay the pre-v10 form, so `hash64` and cache keys don't depend on + /// a stray value (issue #2154). + #[test] + fn stray_grid_is_never_written_outside_the_interner() { + let empty = SegMask { side: 4, data: String::new(), rect: None, grid: None }; + let stray = SegMask { grid: Some(3), ..empty.clone() }; + assert_eq!(serde_json::to_string(&stray).unwrap(), "{\"side\":4,\"data\":\"\"}"); + assert_eq!(serde_json::to_string(&stray).unwrap(), serde_json::to_string(&empty).unwrap()); + let with_data = SegMask { grid: Some(3), ..SegMask::from_logits(4, &[1.0; 16]) }; + assert!(!serde_json::to_string(&with_data).unwrap().contains("grid"), "no grid key outside the interner"); + } + + /// Without the snapshot interner the JSON is exactly the derived form it always was; with + /// it, a pooled grid serializes as an index and the data is left to the table (issue #2154). + #[test] + fn serialization_refs_only_under_the_interner() { + let m = SegMask::from_logits(4, &[1.0; 16]); + let plain = serde_json::to_string(&m).unwrap(); + assert_eq!(plain, format!("{{\"side\":4,\"data\":\"{}\"}}", m.data), "no interner: unchanged bytes"); + let with_rect = SegMask { rect: Some([0.0, 0.0, 0.5, 0.5]), ..m.clone() }; + assert_eq!(serde_json::to_string(&with_rect).unwrap(), format!("{{\"side\":4,\"data\":\"{}\",\"rect\":[0.0,0.0,0.5,0.5]}}", m.data)); + + let mut table = std::collections::HashMap::new(); + table.insert(m.data.clone(), 3u32); + let referenced = with_grid_interner(table, || serde_json::to_string(&m).unwrap()).unwrap(); + assert_eq!(referenced, "{\"side\":4,\"grid\":3}", "pooled grid: an index, no data"); + // a grid the table doesn't hold, and an empty-data mask, stay inline + let other = SegMask::from_logits(2, &[0.0; 4]); + let mixed = with_grid_interner(std::collections::HashMap::new(), || serde_json::to_string(&other).unwrap()).unwrap(); + assert_eq!(mixed, format!("{{\"side\":2,\"data\":\"{}\"}}", other.data)); + // the interner is gone afterwards: serialization is inline again + assert_eq!(serde_json::to_string(&m).unwrap(), plain); + // nested calls are ignored: the outer writer keeps its table + let outer_table = std::collections::HashMap::from([(m.data.clone(), 0u32)]); + let nested = with_grid_interner(outer_table, || { + let inner_table = std::collections::HashMap::from([(other.data.clone(), 1u32)]); + (with_grid_interner(inner_table, || serde_json::to_string(&other).unwrap()), serde_json::to_string(&m).unwrap()) + }) + .unwrap(); + assert_eq!(nested.0, None, "the nested writer is refused"); + assert_eq!(nested.1, "{\"side\":4,\"grid\":0}"); + } } diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 55b851b3c2..9c2af1740c 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -1127,6 +1127,72 @@ impl Default for Mask { } } +impl DevelopSettings { + /// Calls `f` for every segmentation grid stored in these settings (the `seg` and `detail` + /// of Object and Prompt mask shapes). + pub fn visit_seg_masks(&self, f: &mut impl FnMut(&crate::SegMask)) { + for mask in &self.masks { + for component in &mask.components { + visit_shape(&component.shape, f); + } + } + } + + /// [`DevelopSettings::visit_seg_masks`] with mutable access (resolving references into a + /// snapshot's grid table). + pub fn visit_seg_masks_mut(&mut self, f: &mut impl FnMut(&mut crate::SegMask)) { + for mask in &mut self.masks { + for component in &mut mask.components { + visit_shape_mut(&mut component.shape, f); + } + } + } +} + +fn visit_shape(shape: &MaskShape, f: &mut impl FnMut(&crate::SegMask)) { + match shape { + MaskShape::Object { seg, detail, .. } => { + if let Some(seg) = seg { + f(seg); + } + for d in detail { + f(d); + } + } + MaskShape::Prompt { seg, detail, .. } => { + if let Some(seg) = seg { + f(seg); + } + for d in detail { + f(d); + } + } + _ => {} + } +} + +fn visit_shape_mut(shape: &mut MaskShape, f: &mut impl FnMut(&mut crate::SegMask)) { + match shape { + MaskShape::Object { seg, detail, .. } => { + if let Some(seg) = seg.as_mut() { + f(seg); + } + for d in detail { + f(d); + } + } + MaskShape::Prompt { seg, detail, .. } => { + if let Some(seg) = seg.as_mut() { + f(seg); + } + for d in detail { + f(d); + } + } + _ => {} + } +} + // --------------------------------------------------------------------------------------------- // Heal / remove / red eye diff --git a/crates/engine/src/segment.rs b/crates/engine/src/segment.rs index 53ee4a5f83..3f95c310bd 100644 --- a/crates/engine/src/segment.rs +++ b/crates/engine/src/segment.rs @@ -775,7 +775,7 @@ mod tests { fn no_region_for_nothing_or_most_of_the_photo() { assert!(detail_region(&seg_box(50, 0, 0, 0, 0), 1.0).is_none()); assert!(detail_region(&seg_box(50, 2, 2, 48, 48), 1.0).is_none()); - let damaged = SegMask { side: 50, data: "?".into(), rect: None }; + let damaged = SegMask { side: 50, data: "?".into(), rect: None, grid: None }; assert!(detail_region(&damaged, 1.0).is_none()); } } diff --git a/crates/pipeline/src/mask_space.rs b/crates/pipeline/src/mask_space.rs index 36b998ab5e..0d79e4d369 100644 --- a/crates/pipeline/src/mask_space.rs +++ b/crates/pipeline/src/mask_space.rs @@ -356,8 +356,8 @@ mod tests { m.components.push(comp(MaskShape::Object { hint: vec![Point::new(1e300, -1e300)], exclude: Vec::new(), - seg: Some(SegMask { side: 1024, data: "not base64".into(), rect: Some([f64::NAN, 0.0, 2.0, -1.0]) }), - detail: vec![SegMask { side: 0, data: String::new(), rect: None }], + seg: Some(SegMask { side: 1024, data: "not base64".into(), rect: Some([f64::NAN, 0.0, 2.0, -1.0]), grid: None }), + detail: vec![SegMask { side: 0, data: String::new(), rect: None, grid: None }], edge: 0.0, })); m.on_photo = false; diff --git a/crates/pipeline/src/masks/tests.rs b/crates/pipeline/src/masks/tests.rs index 3d0356e980..c97cd290e4 100644 --- a/crates/pipeline/src/masks/tests.rs +++ b/crates/pipeline/src/masks/tests.rs @@ -205,7 +205,12 @@ fn ai_shapes_without_a_segmentation_select_nothing() { for shape in [ MaskShape::Object { hint: vec![], exclude: vec![], seg: None, detail: vec![], edge: 0.0 }, MaskShape::Prompt { text: "sky".into(), seg: None, detail: vec![], edge: 0.0 }, - MaskShape::Prompt { text: "sky".into(), seg: Some(SegMask { side: 4, data: "damaged!".into(), rect: None }), detail: vec![], edge: 0.0 }, + MaskShape::Prompt { + text: "sky".into(), + seg: Some(SegMask { side: 4, data: "damaged!".into(), rect: None, grid: None }), + detail: vec![], + edge: 0.0, + }, ] { assert!(shape_alpha(&shape, &f, 30, 30, &img, &l, 0.0, None).data.iter().all(|v| *v == 0.0)); } From 84a6f5674c9ba937fdc89b891e34b45ee652d726 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 22:42:13 +0200 Subject: [PATCH 13/24] Give the pipeline one exact output size instead of re-fitting (#3749) * Give the pipeline one exact output size instead of re-fitting Export and the pipeline each compute the output size independently from two descriptions of the photo's shape, so an already-chosen export size can come back a pixel short when the pipeline re-fits against a reduced source whose aspect rounds differently. Add an exact output size to RenderRequest, make plan take it unchanged via an exact Frame::sized mode, drop the aspect-tolerance guard, and have export resolve one canonical size before calling the pipeline; add a unit test asserting plan returns the requested size unchanged when it matches the frame aspect. Test: plan_preserves_matching_box_size failed before the change and passes after. * Honor exact output dimensions for exports Assisted-by: OpenAI Codex * Export: an exact size does not stretch a source of another shape A raw whose decode failed can fall back to an embedded preview with a different aspect. The exact box now stands only against a proxy that differs by rounding. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- apps/lightcraft-web/src/wire.rs | 1 + crates/engine/src/export/prepare.rs | 13 +++++++-- crates/pipeline/src/geometry.rs | 2 +- crates/pipeline/src/lib.rs | 44 +++++++++++++++++++++++++++-- 4 files changed, 55 insertions(+), 5 deletions(-) diff --git a/apps/lightcraft-web/src/wire.rs b/apps/lightcraft-web/src/wire.rs index 37246ecd80..afdb8e0e9d 100644 --- a/apps/lightcraft-web/src/wire.rs +++ b/apps/lightcraft-web/src/wire.rs @@ -122,6 +122,7 @@ impl WireJob { RenderRequest { max_w: self.max_w, max_h: self.max_h, + exact_size: false, quality: if self.draft { Quality::Draft } else { Quality::Full }, apply_crop: self.apply_crop, overlay: lightcraft_engine::pipeline::Overlay::from_parts(self.overlay.0, self.overlay.1), diff --git a/crates/engine/src/export/prepare.rs b/crates/engine/src/export/prepare.rs index d71a60e0b7..56cc71a4a7 100644 --- a/crates/engine/src/export/prepare.rs +++ b/crates/engine/src/export/prepare.rs @@ -123,12 +123,21 @@ fn prepare_guarded( let label = p.file_name.clone(); let meta = export_metadata(p, &session.catalog, o); let gain_map = o.hdr_output() && o.format == ExportFormat::Jpeg; - let job = session.export_job(id, w, h, o.effective_space(), o.effective_depth())?; + let mut job = session.export_job(id, w, h, o.effective_space(), o.effective_depth())?; + job.request.exact_size = true; + job.key ^= 0x86e2_fadc_0917_b435; let weight = render_weight(full_px, long, job.level, w.saturating_mul(h)); if let Some(why) = too_big_for_memory((w, h), native_px, weight, crate::memory::total_ram()) { return Err(format!("{label}: {why}")); } - let hdr_job = if gain_map { Some(session.export_job(id, w, h, o.effective_space(), OutputDepth::F32Hdr)?) } else { None }; + let hdr_job = if gain_map { + let mut hdr = session.export_job(id, w, h, o.effective_space(), OutputDepth::F32Hdr)?; + hdr.request.exact_size = true; + hdr.key ^= 0x86e2_fadc_0917_b435; + Some(hdr) + } else { + None + }; (Work::Render(Box::new(RenderWork { job, hdr_job, meta, opts: o.clone() })), weight) } else { let lightcraft_catalog::Source::File { path } = &p.source else { diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index 1b4f5687f2..6cfbd6d9a0 100644 --- a/crates/pipeline/src/geometry.rs +++ b/crates/pipeline/src/geometry.rs @@ -210,7 +210,7 @@ impl Frame { let a = self.aspect(); let (mw, mh) = (max_w.max(1) as f64, max_h.max(1) as f64); // a box that is already this aspect up to rounding (an export size) is the size: fitting - // into it again rounds twice and can lose a pixel of the edge that was asked for + // into it again rounds twice and can lose a pixel of the edge that was asked for. if (mw - 0.5) / a <= mh + 0.5 && (mw + 0.5) / a >= mh - 0.5 { return (max_w.max(1), max_h.max(1)); } diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 5969447657..0c1b795ab1 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -138,6 +138,9 @@ pub struct RenderRequest { /// Output must fit in `max_w × max_h` (aspect preserved). pub max_w: usize, pub max_h: usize, + /// The box is the final export size, already fitted against the full-resolution photo. + /// Reduced decode proxies must not fit it a second time. + pub exact_size: bool, pub quality: Quality, /// Show the crop frame's content only (true) or the whole uncropped image (crop tool active). pub apply_crop: bool, @@ -199,6 +202,7 @@ impl RenderRequest { Self { max_w, max_h, + exact_size: false, quality: Quality::Full, apply_crop: true, overlay: Overlay::None, @@ -209,6 +213,20 @@ impl RenderRequest { display: None, } } + + /// Render to a final size calculated from the original photo, even from a rounded proxy. + pub fn exact(width: usize, height: usize) -> Self { + Self { exact_size: true, ..Self::fit(width, height) } + } + + /// The output size for `frame`. An exact box stands against a proxy that only rounds the photo's + /// shape differently; a source of another shape (a raw's embedded preview) is fitted, not stretched. + fn size(&self, frame: &geometry::Frame) -> (usize, usize) { + let fitted = frame.fit(self.max_w, self.max_h); + let exact = (self.max_w.max(1), self.max_h.max(1)); + let near = |a: usize, b: usize| a.abs_diff(b) <= b / 64 + 1; + if self.exact_size && near(fitted.0, exact.0) && near(fitted.1, exact.1) { exact } else { fitted } + } } pub struct Rendered { @@ -245,7 +263,7 @@ pub(crate) struct Prepared { /// Output size for a source of `src_w × src_h` under `s`, fitting `max_w × max_h`. pub fn output_size(src_w: usize, src_h: usize, s: &DevelopSettings, req: &RenderRequest) -> (usize, usize) { - geometry::Frame::new(src_w, src_h, s, req.apply_crop).fit(req.max_w, req.max_h) + req.size(&geometry::Frame::new(src_w, src_h, s, req.apply_crop)) } /// Size of the cropped output of a `src_w × src_h` source under `s` at the source's own resolution @@ -440,7 +458,7 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R } let s = &*settings; let frame = frame_for(src, info, s, req.apply_crop); - let (full_w, full_h) = frame.fit(req.max_w, req.max_h); + let (full_w, full_h) = req.size(&frame); // sizes and scale are those of the whole output; a window only narrows what is drawn let px_per_long = frame.px_per_long(full_w); let mut fixed_air = None; @@ -775,6 +793,28 @@ pub(crate) fn for_rows(data: &mut [T], w: usize, f: impl Fn(usize, &mut par_rows(data, w, f) } +/// `plan` must keep the output box the caller (export) already decided instead of +/// re-fitting it: `Frame::fit` passes a box through unchanged only when it matches +/// the *decoded* frame's aspect within rounding slack (geometry.rs:189-191), so a +/// reduced source whose aspect rounds differently (a 149 x 100 proxy of a 240 x 160 +/// photo) makes `plan` return a size a pixel off from the box (issue #1042). +#[cfg(test)] +#[test] +fn plan_preserves_matching_box_size() { + let src = Rgb32f::from_fn(149, 100, |_, _| [0.5; 3]); + let info = SourceInfo { native_long: Some(240), ..SourceInfo::default() }; + let s = DevelopSettings::default(); + let fitted = plan(&src, &info, &s, &RenderRequest::fit(240, 160)); + assert_eq!((fitted.w, fitted.h), (238, 160)); + let req = RenderRequest::exact(240, 160); + let p = plan(&src, &info, &s, &req); + assert_eq!((p.w, p.h), (240, 160)); + // an embedded preview of another shape keeps its shape: an exact box must not stretch it + let preview = Rgb32f::from_fn(120, 100, |_, _| [0.5; 3]); + let p = plan(&preview, &info, &s, &req); + assert_eq!((p.w, p.h), (192, 160)); +} + #[cfg(test)] mod tests; #[cfg(test)] From 7b99ed3903f9f305f0e5fd6fb12f705aec0c1adb Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 23:01:47 +0200 Subject: [PATCH 14/24] Presets change only the settings they name (fixes #2159) (#2207) * Presets compose on the photo's original state, not the visible edits (fixes #2159) Applying a preset deep-merged it into the photo's current settings, so a second preset inherited whatever an earlier one (or a manual edit) had put in the groups it styles, and its amount interpolated against the visible values: a B&W preset followed by a color one stayed black and white. Each group a preset covers is now computed on the photo's original state (its import settings) and replaces the photo's own, at any amount; groups the preset doesn't name, and the photo's pixel repairs (masks, spots, red eye), are kept. An unresolved profile reference still means "the photo keeps its own profile", and the built-in color presets now name their treatment, so applying one after a B&W preset brings the colors back. The UI's hover previews and thumbnails show the same composed result. * Presets change only the settings they name (#2159) The commit before this one computed each group a preset names on the photo's import state and replaced the whole group. A preset therefore also reset the settings it leaves out: Blacks under Bright & Airy, the mixer colours it does not name, and imported exposure, whites and blacks under Crisp Landscape. Now each setting a preset names is computed alone, from the photo's import look when a default preset recorded one, and otherwise from its current value, because sidecar and catalog imports record no import look and the camera defaults are then not their import state. Every other setting keeps the photo's value. Pixel repairs (masks, spots, red eye) compose on the photo's own values as before, and masks are still added by the preset. A color preset applied after a black and white one still restores the treatment and the settings it names. Amount 0 applies nothing to a photo without an import look. An unresolved profile reference leaves the photo's profile as it is. Each case has a test. * Document that presets change only the settings they name The presets row and the preset amount row of the parity checklist now describe the composition: each named setting is measured from the import look when one is recorded, otherwise from the photo's current value, and the settings a preset does not name keep their values. The revision history records the change; statuses are unchanged. * Test amount 0 on a setting the preset names The amount-0 test used a preset that does not name exposure, so it passed even when the original was the camera defaults. Bright & Airy names exposure, and the test now checks that the photo keeps its value at amount 0 for that setting. * Keep a preset's null in an option field, and never take one from the original A preset that writes null into an option setting (a crop aspect, where null means free) was dropped below full amount: the scaled patch removed every null, including the ones the preset wrote. At 100 % the same preset cleared the aspect, at 50 to 99 % the photo kept it. Now a null the preset writes applies from half amount up, as its other values do. A null in the original never changes the photo: below half amount such a setting is left out, so the photo keeps its own value. Numbers and other values behave as before. The null-removal step is gone, since the scaled patch no longer writes nulls for settings the amount does not reach. Tests: a preset null clears an option field from half amount up and leaves it below; an option that is unset in the original does not overwrite the photo's value. * Build a preset's scaling base only below full amount The presets panel asks for every visible row at 100 % on every frame, and on hover. Each of those calls serialized the photo's current settings and its original although, at 100 %, the preset's own values apply as they are and the original is not read. Compose now builds the scaling base only below 100 %. The engine also builds the import state, or copies the photo's settings, only below 100 %. Results are unchanged; the existing preset tests cover both paths. * Preserve preset baselines and allocate safe mask IDs Assisted-by: OpenAI Codex --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/develop/src/presets.rs | 326 +++++++++++++++++++++++++-- crates/engine/src/cmd/develop.rs | 8 +- crates/engine/src/presets.rs | 236 +++++++++++++++---- crates/ui-egui/src/panels/presets.rs | 9 +- docs/parity-checklist.md | 5 +- 5 files changed, 523 insertions(+), 61 deletions(-) diff --git a/crates/develop/src/presets.rs b/crates/develop/src/presets.rs index b69f2df460..a1072a89ac 100644 --- a/crates/develop/src/presets.rs +++ b/crates/develop/src/presets.rs @@ -1,8 +1,12 @@ //! Presets and copy/paste subsets. //! -//! A preset is a *partial* settings object (JSON) — only the groups it includes. Applying merges it -//! into the photo's settings; `amount` (0..200 %) interpolates numeric values between the current -//! settings and the preset's. Copy/paste/sync use the same group selection ([`SettingsGroup`]). +//! A preset is a *partial* settings object (JSON) — only the settings it names. Applying it changes +//! exactly the settings it names (a leaf: a number, a flag, a name; an array is one leaf): each is +//! computed from the photo's *original* state (its import settings, when known) and the preset's +//! value, and replaces the photo's value; every other setting keeps the photo's value (issue +//! #2159). `amount` (0..200 %) moves each named number between the original and the preset's +//! value. Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the +//! current settings as before. //! //! The rendering process ([`crate::ProcessVersion`]) is in no group: copy, paste, sync and presets //! made from a photo never carry it, so the photos they change keep their own. A partial that names @@ -191,6 +195,74 @@ pub fn apply_partial(s: &DevelopSettings, partial: &Value, amount: f64) -> Devel s.merged(&patch).unwrap_or_else(|_| s.clone()) } +/// Top-level settings keys that hold per-photo pixel repairs: a preset's named repairs compose on +/// the photo's own values instead of the original's (masks are added by [`Preset::apply_on`]), and +/// a preset without them leaves the photo's alone. +const REPAIR_KEYS: [&str; 3] = ["masks", "spots", "red_eye"]; + +/// The settings `settings` (a partial JSON object) names, applied to `current` at `amount`: each +/// named setting is computed from `original` (the photo's import state) and the preset's value, +/// and replaces the photo's value (issue #2159). Every setting the preset does not name keeps the +/// photo's current value, edits included. Pixel repairs compose on the photo's own values, as they +/// always have. +fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings: &Value, amount: f64) -> DevelopSettings { + // At 100 % the preset's own values apply as they are, and `original` is not read. The presets + // panel calls this for every visible row on every frame, so the scaling base is built below only. + if (amount - 1.0).abs() < 1e-9 { + return current.merged(settings).unwrap_or_else(|_| current.clone()); + } + let cur = current.to_json(); + let mut base = original.to_json(); + if let (Some(b), Some(c)) = (base.as_object_mut(), cur.as_object()) { + for k in REPAIR_KEYS { + if let Some(v) = c.get(k) { + b.insert(k.to_string(), v.clone()); + } + } + } + let composed = match settings.as_object() { + Some(patch) => Value::Object(interpolate_object(base.as_object(), patch, amount)), + None => Value::Object(Map::new()), + }; + // `merged` deep-merges: the named settings replace, everything else stays as `current` has it + current.merged(&composed).unwrap_or_else(|_| current.clone()) +} + +/// The leaves of `patch` that apply at `t` (below 100 %), each computed from the same place in +/// `base`. A leaf the amount does not reach is left out, so the photo keeps its own value there. +fn interpolate_object(base: Option<&Map>, patch: &Map, t: f64) -> Map { + let mut out = Map::new(); + for (k, pv) in patch { + let bv = base.and_then(|b| b.get(k)); + let v = match pv { + Value::Object(p) => Some(Value::Object(interpolate_object(bv.and_then(Value::as_object), p, t))), + _ => interpolate_leaf(bv, pv, t), + }; + if let Some(v) = v { + out.insert(k.clone(), v); + } + } + out +} + +/// One leaf at `t`. Numbers move from `base` towards `patch`. Other values switch to the preset's +/// at half amount and up, and below it take the base's value. A null in the base is the baseline +/// value the import state recorded (a cleared option, such as a free crop aspect): below half +/// amount it applies and clears the photo's value, as the amount contract promises. A null the +/// preset writes is a value like any other, so it applies at half amount and up (a preset can +/// clear an option field such as a crop aspect). +fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option { + match (base, patch) { + // integer fields (the grain seed, ids) are discrete like strings: see `scale_patch` + (Some(Value::Number(b)), Value::Number(p)) if b.is_f64() || p.is_f64() => { + let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0)); + serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number) + } + _ if t >= 0.5 => Some(patch.clone()), + _ => base.cloned(), + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Preset { pub id: String, @@ -209,30 +281,49 @@ impl Preset { pub fn from_settings(id: &str, name: &str, group: &str, s: &DevelopSettings, groups: &[SettingsGroup]) -> Preset { Preset { id: id.into(), name: name.into(), group: group.into(), settings: extract_groups(s, groups), favorite: false, builtin: false } } - /// Apply at `amount` (1.0 = 100 %). Masks in the preset are added to the photo's own (ones it - /// already has are skipped), their effect scaled by the amount. + /// Apply at `amount` (1.0 = 100 %), with `s` as both the photo's current and its original + /// settings (see [`Preset::apply_on`]): right for the import default preset and for scratch + /// bases. Masks in the preset are added to the photo's own (ones it already has are skipped), + /// their effect scaled by the amount. pub fn apply(&self, s: &DevelopSettings, amount: f64) -> DevelopSettings { + self.apply_on(s, s, amount) + } + /// Apply at `amount` (1.0 = 100 %), composing on `original` (the photo's import state, or the + /// photo's current settings when that is not known): each setting the preset names is computed + /// from `original` and the preset's value, `amount` moving it between the two, and replaces the + /// photo's value. Every setting the preset does not name keeps `current`'s value, and so do + /// the photo's pixel repairs (masks, spots, red eye), which the preset patches; masks in the + /// preset are added to the photo's own (ones it already has are skipped), their effect scaled + /// by the amount. A second preset therefore restores what the first one changed in the + /// settings it names (issue #2159), and nothing it leaves out. + pub fn apply_on(&self, current: &DevelopSettings, original: &DevelopSettings, amount: f64) -> DevelopSettings { let Some(masks) = self.settings.get("masks").and_then(Value::as_array).filter(|m| !m.is_empty()) else { - return apply_partial(s, &self.settings, amount); + return compose_named(current, original, &self.settings, amount); }; let mut rest = self.settings.clone(); if let Some(o) = rest.as_object_mut() { o.remove("masks"); } - let mut out = apply_partial(s, &rest, amount); - for m in masks { - let Ok(mut m) = serde_json::from_value::(m.clone()) else { continue }; - if out.masks.iter().any(|q| q.name == m.name && q.components == m.components) { - continue; - } - m.id = out.next_mask_id(); - m.adjust.amount = (m.adjust.amount * amount).clamp(0.0, 200.0); - out.masks.push(m); - } + let mut out = compose_named(current, original, &rest, amount); + add_masks(&mut out, masks, amount); out } } +/// The preset's masks, added to the photo's own (ones it already has are skipped), their effect +/// scaled by the amount. +fn add_masks(out: &mut DevelopSettings, masks: &[Value], amount: f64) { + for m in masks { + let Ok(mut m) = serde_json::from_value::(m.clone()) else { continue }; + if out.masks.iter().any(|q| q.name == m.name && q.components == m.components) { + continue; + } + m.id = out.next_mask_id(); + m.adjust.amount = (m.adjust.amount * amount).clamp(0.0, 200.0); + out.masks.push(m); + } +} + #[cfg(test)] mod tests { use super::*; @@ -285,6 +376,209 @@ mod tests { } } + /// A preset changes only the settings it names: a setting in a group it styles but does not + /// name keeps the photo's value, and so does a whole group it leaves out. + #[test] + fn apply_on_changes_only_the_settings_it_names() { + let mut current = DevelopSettings::default(); + current.light.exposure = 2.0; + current.light.blacks = -30.0; + current.effects.clarity = 30.0; + let original = DevelopSettings::default(); + let p = Preset { + id: "p".into(), + name: "P".into(), + group: "G".into(), + settings: json!({"light": {"contrast": 12.0}}), + favorite: false, + builtin: false, + }; + let out = p.apply_on(¤t, &original, 1.0); + assert_eq!(out.light.contrast, 12.0); + assert_eq!(out.light.exposure, 2.0, "a setting the preset doesn't name keeps the photo's value"); + assert_eq!(out.light.blacks, -30.0, "a setting in the same group, not named, keeps the photo's value"); + assert_eq!(out.effects.clarity, 30.0, "a group the preset doesn't name is untouched"); + } + + /// A partial preset that names one colour of the mixer leaves the other colours, and the + /// unnamed settings of the colour it names, as the photo has them. + #[test] + fn apply_on_keeps_the_mixer_colours_it_does_not_name() { + let mut current = DevelopSettings::default(); + current.mixer.red.sat = 20.0; + current.mixer.blue.hue = 15.0; + current.mixer.blue.sat = 5.0; + let original = DevelopSettings::default(); + let p = Preset { + id: "p".into(), + name: "P".into(), + group: "G".into(), + settings: json!({"mixer": {"blue": {"sat": 15.0, "lum": -25.0}}}), + favorite: false, + builtin: false, + }; + let out = p.apply_on(¤t, &original, 1.0); + assert_eq!(out.mixer.red.sat, 20.0, "a colour the preset doesn't name"); + assert_eq!(out.mixer.blue.hue, 15.0, "a setting of a named colour that the preset doesn't name"); + assert_eq!((out.mixer.blue.sat, out.mixer.blue.lum), (15.0, -25.0)); + } + + /// The white balance is not one setting: a preset that names only the temperature keeps the + /// photo's tint. + #[test] + fn apply_on_keeps_the_white_balance_fields_it_does_not_name() { + let mut current = DevelopSettings::default(); + current.wb.temp = 6000.0; + current.wb.tint = 12.0; + let original = DevelopSettings::default(); + let p = Preset { + id: "p".into(), + name: "P".into(), + group: "G".into(), + settings: json!({"wb": {"temp": 5000.0}}), + favorite: false, + builtin: false, + }; + let out = p.apply_on(¤t, &original, 1.0); + assert_eq!((out.wb.temp, out.wb.tint), (5000.0, 12.0)); + } + + /// A preset's amount 0 changes nothing when the original is the photo's current settings (no + /// import state is recorded for the photo), and any other amount moves the named settings + /// from where the photo has them. + #[test] + fn apply_on_without_an_import_state_scales_from_the_current_settings() { + let mut current = DevelopSettings::default(); + current.light.exposure = 2.0; + current.light.blacks = -30.0; + let p = Preset { + id: "p".into(), + name: "P".into(), + group: "G".into(), + settings: json!({"light": {"exposure": 0.45, "contrast": 12.0}}), + favorite: false, + builtin: false, + }; + assert_eq!(p.apply_on(¤t, ¤t, 0.0), current, "amount 0 applies nothing"); + let half = p.apply_on(¤t, ¤t, 0.5); + assert!((half.light.exposure - 1.225).abs() < 1e-9, "{}", half.light.exposure); + assert_eq!(half.light.blacks, -30.0); + } + + /// An unresolved `crs:Look` reference (its profile object has no id; the importer leaves + /// `look` in it) changes nothing: the photo keeps its own profile. + #[test] + fn an_unresolved_profile_reference_keeps_the_photos_profile() { + let mut current = DevelopSettings::default(); + current.profile.id = "lc.vivid".into(); + current.profile.amount = 60.0; + let p = Preset { + id: "p".into(), + name: "P".into(), + group: "G".into(), + settings: json!({"profile": {"look": {"name": "Not imported", "amount": 100.0}}, "light": {"contrast": 12.0}}), + favorite: false, + builtin: false, + }; + for amount in [1.0, 0.5] { + let out = p.apply_on(¤t, ¤t, amount); + assert_eq!((out.profile.id.as_str(), out.profile.amount), ("lc.vivid", 60.0), "amount {amount}"); + } + } + + /// The amount interpolates between the original and the preset, not between the visible + /// values and the preset: a preset at 50 % looks the same however the photo was edited before. + #[test] + fn apply_on_scales_against_the_original() { + let mut current = DevelopSettings::default(); + current.light.exposure = 2.0; + let original = DevelopSettings::default(); + let p = Preset { + id: "p".into(), + name: "P".into(), + group: "G".into(), + settings: json!({"light": {"exposure": 0.45}}), + favorite: false, + builtin: false, + }; + let out = p.apply_on(¤t, &original, 0.5); + assert!((out.light.exposure - 0.225).abs() < 1e-9, "{}", out.light.exposure); + } + + /// Pixel repairs are the photo's own: a preset's are patched in, and one without them never + /// restores the original's. + #[test] + fn apply_on_patches_pixel_repairs_into_the_current_ones() { + let current = DevelopSettings { + spots: serde_json::from_value(json!([{"mode": "heal", "points": [[0.5, 0.5]], "size": 0.05, "feather": 50.0, "opacity": 100.0}])) + .unwrap(), + ..Default::default() + }; + let original = DevelopSettings::default(); + let none = Preset { + id: "p".into(), + name: "P".into(), + group: "G".into(), + settings: json!({"light": {"contrast": 10.0}}), + favorite: false, + builtin: false, + }; + let out = none.apply_on(¤t, &original, 1.0); + assert_eq!(out.spots.len(), 1, "the photo's spot survives a preset without spots"); + let clearing = Preset { + id: "q".into(), + name: "Q".into(), + group: "G".into(), + settings: json!({"light": {"contrast": 10.0}, "spots": []}), + favorite: false, + builtin: false, + }; + let out = clearing.apply_on(¤t, &original, 1.0); + assert_eq!(out.spots.len(), 0, "a preset that names spots replaces them, as before"); + } + + /// A null a preset writes into an option field (here a crop aspect: null is "free") is the + /// preset's value, so it clears the photo's aspect from half amount up, as any value of the + /// preset does; below half amount the import baseline applies, which here is null as well. + #[test] + fn a_preset_null_clears_an_option_field_from_half_amount() { + let mut current = DevelopSettings::default(); + current.crop.aspect = Some((3, 2)); + let original = DevelopSettings::default(); // the import state has no aspect + let p = Preset { + id: "p".into(), + name: "P".into(), + group: "G".into(), + settings: json!({"crop": {"aspect": null}}), + favorite: false, + builtin: false, + }; + for amount in [1.0, 0.7, 0.5] { + assert_eq!(p.apply_on(¤t, &original, amount).crop.aspect, None, "amount {amount}: the preset's null clears the aspect"); + } + assert_eq!(p.apply_on(¤t, &original, 0.3).crop.aspect, None, "below half amount the import baseline (no aspect) applies"); + } + + /// The import state has no aspect, and that null is the baseline below half amount (the amount + /// contract: a named setting moves between the import state and the preset's value); from half + /// amount the preset's aspect applies. + #[test] + fn a_null_in_the_original_is_the_baseline_below_half_amount() { + let mut current = DevelopSettings::default(); + current.crop.aspect = Some((3, 2)); + let original = DevelopSettings::default(); + let p = Preset { + id: "p".into(), + name: "P".into(), + group: "G".into(), + settings: json!({"crop": {"aspect": [16, 9]}}), + favorite: false, + builtin: false, + }; + assert_eq!(p.apply_on(¤t, &original, 0.4).crop.aspect, None, "40 %: the import baseline (no aspect) applies"); + assert_eq!(p.apply_on(¤t, &original, 0.6).crop.aspect, Some((16, 9)), "60 %: the preset's aspect applies"); + } + #[test] fn deep_merge_objects() { let mut a = json!({"x": {"a": 1, "b": 2}, "y": [1]}); diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index e78407f5ea..42e2793daf 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -1108,7 +1108,13 @@ pub fn specs() -> Vec { let prepared = prepare_photo_for_wb_partial(&d, &preset.settings, &info); let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb; let base: &DevelopSettings = prepared.as_ref().unwrap_or(&d); - let mut next = preset.apply(base, amount); + // Amount is measured from the import look only when the photo has one. + // Otherwise the current settings (on the partial's WB scale) are its baseline. + let imported = s.catalog.photo(id).filter(|p| p.import_look.is_some() && amount != 1.0).map(|p| p.import_defaults()); + let prepared_import = + imported.as_ref().map(|d| prepare_photo_for_wb_partial(d, &preset.settings, &info).unwrap_or_else(|| d.clone())); + let original = prepared_import.as_ref().unwrap_or(base); + let mut next = preset.apply_on(base, original, amount); if on_kelvin_scale { lightcraft_pipeline::local::normalize_wb(&mut next, &info); } diff --git a/crates/engine/src/presets.rs b/crates/engine/src/presets.rs index 9ce4c3e916..2ad6e5d2ef 100644 --- a/crates/engine/src/presets.rs +++ b/crates/engine/src/presets.rs @@ -4,7 +4,8 @@ use std::path::Path; -use lightcraft_develop::Preset; +use lightcraft_catalog::PhotoId; +use lightcraft_develop::{DevelopSettings, Preset}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -171,6 +172,29 @@ pub fn expand_preset_paths(paths: &[String]) -> Vec { } impl Session { + /// The settings after applying `preset` to photo `id` at `amount`. The settings the preset + /// names are computed on the photo's import state ([`lightcraft_catalog::Photo::import_defaults`]) + /// when a default preset recorded one (`import_look`); a photo without one (its settings came + /// from an XMP sidecar or a catalog import, which record none) composes them on its current + /// settings instead, since the camera defaults are not its import state. Either way, the + /// settings the preset does not name keep the photo's values (issue #2159). The `preset.apply` + /// command and the UI's hover previews share this, so hovering shows exactly what a click commits. + pub fn preset_applied(&self, id: PhotoId, preset: &Preset, amount: f64) -> Option { + let current = self.develop_of(id)?; + let photo = self.catalog.photo(id)?; + // The original is read only below 100 %: the panel asks for every visible row at 100 % on + // every frame, and then neither the import state nor a copy of the photo's settings is built. + let look; + let original: &DevelopSettings = match &photo.import_look { + Some(_) if (amount - 1.0).abs() >= 1e-9 => { + look = photo.import_defaults(); + &look + } + _ => ¤t, + }; + Some(preset.apply_on(¤t, original, amount)) + } + /// Add imported presets. Identical presets (same name, group and settings) already present are /// skipped; id clashes get a fresh id. Returns the ids added. pub fn add_presets(&mut self, presets: Vec) -> Vec { @@ -218,49 +242,49 @@ pub fn builtin() -> Vec { "Color", "warm-glow", "Warm Glow", - json!({"wb": {"mode": "custom", "temp": 7200.0, "tint": 8.0}, "light": {"contrast": 8.0, "shadows": 12.0}, "color": {"vibrance": 18.0}}), + json!({"treatment": "color", "wb": {"mode": "custom", "temp": 7200.0, "tint": 8.0}, "light": {"contrast": 8.0, "shadows": 12.0}, "color": {"vibrance": 18.0}}), ), p( "Color", "cool-morning", "Cool Morning", - json!({"wb": {"mode": "custom", "temp": 5600.0, "tint": -4.0}, "light": {"highlights": -20.0}, "color": {"vibrance": 10.0}, "grading": {"shadows": {"hue": 215.0, "sat": 12.0, "lum": 0.0}}}), + json!({"treatment": "color", "wb": {"mode": "custom", "temp": 5600.0, "tint": -4.0}, "light": {"highlights": -20.0}, "color": {"vibrance": 10.0}, "grading": {"shadows": {"hue": 215.0, "sat": 12.0, "lum": 0.0}}}), ), p( "Color", "teal-orange", "Teal & Orange", - json!({"grading": {"shadows": {"hue": 195.0, "sat": 28.0, "lum": 0.0}, "highlights": {"hue": 35.0, "sat": 22.0, "lum": 0.0}, "balance": 10.0}, "color": {"vibrance": 12.0}, "light": {"contrast": 14.0}}), + json!({"treatment": "color", "grading": {"shadows": {"hue": 195.0, "sat": 28.0, "lum": 0.0}, "highlights": {"hue": 35.0, "sat": 22.0, "lum": 0.0}, "balance": 10.0}, "color": {"vibrance": 12.0}, "light": {"contrast": 14.0}}), ), p( "Color", "vivid-pop", "Vivid Pop", - json!({"color": {"vibrance": 40.0, "saturation": 8.0}, "light": {"contrast": 18.0, "whites": 10.0, "blacks": -10.0}, "effects": {"clarity": 12.0}}), + json!({"treatment": "color", "color": {"vibrance": 40.0, "saturation": 8.0}, "light": {"contrast": 18.0, "whites": 10.0, "blacks": -10.0}, "effects": {"clarity": 12.0}}), ), p( "Color", "soft-pastel", "Soft Pastel", - json!({"light": {"contrast": -25.0, "highlights": -30.0, "shadows": 35.0, "blacks": 20.0}, "color": {"saturation": -18.0, "vibrance": 10.0}, "curve": {"shadows": 25.0}}), + json!({"treatment": "color", "light": {"contrast": -25.0, "highlights": -30.0, "shadows": 35.0, "blacks": 20.0}, "color": {"saturation": -18.0, "vibrance": 10.0}, "curve": {"shadows": 25.0}}), ), p( "Film", "faded-matte", "Faded Matte", - json!({"curve": {"shadows": 40.0, "highlights": -15.0}, "light": {"contrast": -10.0}, "color": {"saturation": -12.0}, "grain": {"amount": 18.0, "size": 25.0, "roughness": 50.0}}), + json!({"treatment": "color", "curve": {"shadows": 40.0, "highlights": -15.0}, "light": {"contrast": -10.0}, "color": {"saturation": -12.0}, "grain": {"amount": 18.0, "size": 25.0, "roughness": 50.0}}), ), p( "Film", "warm-film", "Warm Film", - json!({"wb": {"mode": "custom", "temp": 6900.0, "tint": 5.0}, "curve": {"shadows": 22.0}, "grading": {"highlights": {"hue": 45.0, "sat": 15.0, "lum": 0.0}}, "grain": {"amount": 22.0, "size": 30.0, "roughness": 55.0}, "vignette": {"amount": -12.0}}), + json!({"treatment": "color", "wb": {"mode": "custom", "temp": 6900.0, "tint": 5.0}, "curve": {"shadows": 22.0}, "grading": {"highlights": {"hue": 45.0, "sat": 15.0, "lum": 0.0}}, "grain": {"amount": 22.0, "size": 30.0, "roughness": 55.0}, "vignette": {"amount": -12.0}}), ), p( "Film", "muted-film", "Muted Film", - json!({"color": {"saturation": -25.0, "vibrance": 5.0}, "light": {"contrast": 10.0}, "curve": {"shadows": 18.0}, "grain": {"amount": 15.0}}), + json!({"treatment": "color", "color": {"saturation": -25.0, "vibrance": 5.0}, "light": {"contrast": 10.0}, "curve": {"shadows": 18.0}, "grain": {"amount": 15.0}}), ), p( "B&W", @@ -279,181 +303,181 @@ pub fn builtin() -> Vec { "Landscape", "crisp-landscape", "Crisp Landscape", - json!({"light": {"highlights": -45.0, "shadows": 30.0, "contrast": 12.0}, "effects": {"clarity": 22.0, "dehaze": 12.0, "texture": 15.0}, "color": {"vibrance": 25.0}}), + json!({"treatment": "color", "light": {"highlights": -45.0, "shadows": 30.0, "contrast": 12.0}, "effects": {"clarity": 22.0, "dehaze": 12.0, "texture": 15.0}, "color": {"vibrance": 25.0}}), ), p( "Landscape", "golden-hour", "Golden Hour", - json!({"wb": {"mode": "custom", "temp": 7600.0, "tint": 12.0}, "light": {"highlights": -35.0, "shadows": 20.0}, "grading": {"highlights": {"hue": 38.0, "sat": 25.0, "lum": 5.0}}, "vignette": {"amount": -15.0}}), + json!({"treatment": "color", "wb": {"mode": "custom", "temp": 7600.0, "tint": 12.0}, "light": {"highlights": -35.0, "shadows": 20.0}, "grading": {"highlights": {"hue": 38.0, "sat": 25.0, "lum": 5.0}}, "vignette": {"amount": -15.0}}), ), p( "Landscape", "blue-hour", "Blue Hour Boost", - json!({"wb": {"mode": "custom", "temp": 5200.0, "tint": 6.0}, "light": {"shadows": 25.0, "exposure": 0.2}, "mixer": {"blue": {"hue": 0.0, "sat": 25.0, "lum": 0.0}, "purple": {"hue": 0.0, "sat": 15.0, "lum": 0.0}}}), + json!({"treatment": "color", "wb": {"mode": "custom", "temp": 5200.0, "tint": 6.0}, "light": {"shadows": 25.0, "exposure": 0.2}, "mixer": {"blue": {"hue": 0.0, "sat": 25.0, "lum": 0.0}, "purple": {"hue": 0.0, "sat": 15.0, "lum": 0.0}}}), ), p( "Portrait", "soft-skin", "Soft Skin", - json!({"effects": {"texture": -25.0, "clarity": -10.0}, "light": {"contrast": -5.0, "shadows": 15.0}, "mixer": {"orange": {"hue": 0.0, "sat": -8.0, "lum": 10.0}}}), + json!({"treatment": "color", "effects": {"texture": -25.0, "clarity": -10.0}, "light": {"contrast": -5.0, "shadows": 15.0}, "mixer": {"orange": {"hue": 0.0, "sat": -8.0, "lum": 10.0}}}), ), p( "Portrait", "bright-airy", "Bright & Airy", - json!({"light": {"exposure": 0.45, "contrast": -15.0, "highlights": -40.0, "shadows": 40.0, "whites": 15.0}, "color": {"vibrance": 8.0, "saturation": -8.0}}), + json!({"treatment": "color", "light": {"exposure": 0.45, "contrast": -15.0, "highlights": -40.0, "shadows": 40.0, "whites": 15.0}, "color": {"vibrance": 8.0, "saturation": -8.0}}), ), p( "Style", "moody", "Moody", - json!({"light": {"exposure": -0.3, "contrast": 20.0, "highlights": -30.0, "blacks": -15.0}, "color": {"saturation": -20.0}, "grading": {"shadows": {"hue": 200.0, "sat": 15.0, "lum": -5.0}}, "vignette": {"amount": -30.0}}), + json!({"treatment": "color", "light": {"exposure": -0.3, "contrast": 20.0, "highlights": -30.0, "blacks": -15.0}, "color": {"saturation": -20.0}, "grading": {"shadows": {"hue": 200.0, "sat": 15.0, "lum": -5.0}}, "vignette": {"amount": -30.0}}), ), p( "Style", "cinematic", "Cinematic", - json!({"curve": {"shadows": 20.0, "highlights": -10.0}, "grading": {"shadows": {"hue": 190.0, "sat": 25.0, "lum": 0.0}, "highlights": {"hue": 30.0, "sat": 18.0, "lum": 0.0}}, "light": {"contrast": 15.0}, "vignette": {"amount": -20.0}}), + json!({"treatment": "color", "curve": {"shadows": 20.0, "highlights": -10.0}, "grading": {"shadows": {"hue": 190.0, "sat": 25.0, "lum": 0.0}, "highlights": {"hue": 30.0, "sat": 18.0, "lum": 0.0}}, "light": {"contrast": 15.0}, "vignette": {"amount": -20.0}}), ), // ---- Portrait p( "Portrait", "moody-portrait", "Moody Portrait", - json!({"light": {"exposure": -0.25, "contrast": 20.0, "highlights": -30.0, "blacks": -12.0}, "color": {"saturation": -15.0}, "vignette": {"amount": -25.0, "midpoint": 40.0}, "mixer": {"orange": {"sat": 6.0}}}), + json!({"treatment": "color", "light": {"exposure": -0.25, "contrast": 20.0, "highlights": -30.0, "blacks": -12.0}, "color": {"saturation": -15.0}, "vignette": {"amount": -25.0, "midpoint": 40.0}, "mixer": {"orange": {"sat": 6.0}}}), ), p( "Portrait", "golden-glow", "Golden Glow", - json!({"grading": {"highlights": {"hue": 40.0, "sat": 18.0, "lum": 0.0}, "midtones": {"hue": 35.0, "sat": 8.0, "lum": 0.0}}, "light": {"shadows": 15.0}, "effects": {"clarity": -8.0}}), + json!({"treatment": "color", "grading": {"highlights": {"hue": 40.0, "sat": 18.0, "lum": 0.0}, "midtones": {"hue": 35.0, "sat": 8.0, "lum": 0.0}}, "light": {"shadows": 15.0}, "effects": {"clarity": -8.0}}), ), p( "Portrait", "clean-studio", "Clean Studio", - json!({"light": {"contrast": 10.0, "whites": 15.0, "blacks": -8.0}, "effects": {"texture": -10.0}, "color": {"vibrance": 5.0}}), + json!({"treatment": "color", "light": {"contrast": 10.0, "whites": 15.0, "blacks": -8.0}, "effects": {"texture": -10.0}, "color": {"vibrance": 5.0}}), ), // ---- Landscape p( "Landscape", "crisp-vista", "Crisp Vista", - json!({"effects": {"dehaze": 15.0, "clarity": 18.0, "texture": 12.0}, "light": {"contrast": 12.0, "highlights": -25.0, "shadows": 18.0}, "color": {"vibrance": 20.0}}), + json!({"treatment": "color", "effects": {"dehaze": 15.0, "clarity": 18.0, "texture": 12.0}, "light": {"contrast": 12.0, "highlights": -25.0, "shadows": 18.0}, "color": {"vibrance": 20.0}}), ), p( "Landscape", "deep-sky", "Deep Sky", - json!({"mixer": {"blue": {"lum": -25.0, "sat": 15.0}, "aqua": {"lum": -10.0}}, "light": {"highlights": -30.0}, "effects": {"dehaze": 10.0}}), + json!({"treatment": "color", "mixer": {"blue": {"lum": -25.0, "sat": 15.0}, "aqua": {"lum": -10.0}}, "light": {"highlights": -30.0}, "effects": {"dehaze": 10.0}}), ), p( "Landscape", "lush-greens", "Lush Greens", - json!({"mixer": {"green": {"hue": 12.0, "sat": 18.0, "lum": 8.0}, "yellow": {"hue": 10.0, "sat": 10.0}}, "color": {"vibrance": 12.0}, "effects": {"clarity": 8.0}}), + json!({"treatment": "color", "mixer": {"green": {"hue": 12.0, "sat": 18.0, "lum": 8.0}, "yellow": {"hue": 10.0, "sat": 10.0}}, "color": {"vibrance": 12.0}, "effects": {"clarity": 8.0}}), ), p( "Landscape", "desert-warmth", "Desert Warmth", - json!({"mixer": {"orange": {"sat": 15.0, "lum": 5.0}, "yellow": {"hue": -8.0, "sat": 10.0}, "blue": {"sat": -10.0}}, "grading": {"highlights": {"hue": 38.0, "sat": 12.0, "lum": 0.0}}, "light": {"contrast": 10.0}}), + json!({"treatment": "color", "mixer": {"orange": {"sat": 15.0, "lum": 5.0}, "yellow": {"hue": -8.0, "sat": 10.0}, "blue": {"sat": -10.0}}, "grading": {"highlights": {"hue": 38.0, "sat": 12.0, "lum": 0.0}}, "light": {"contrast": 10.0}}), ), p( "Landscape", "misty-morning", "Misty Morning", - json!({"effects": {"dehaze": -18.0, "clarity": -12.0}, "light": {"contrast": -18.0, "highlights": -10.0}, "grading": {"shadows": {"hue": 210.0, "sat": 10.0, "lum": 0.0}}, "color": {"saturation": -10.0}}), + json!({"treatment": "color", "effects": {"dehaze": -18.0, "clarity": -12.0}, "light": {"contrast": -18.0, "highlights": -10.0}, "grading": {"shadows": {"hue": 210.0, "sat": 10.0, "lum": 0.0}}, "color": {"saturation": -10.0}}), ), // ---- Urban p( "Urban", "gritty-street", "Gritty Street", - json!({"effects": {"clarity": 35.0, "texture": 20.0}, "light": {"contrast": 25.0, "blacks": -15.0}, "color": {"saturation": -30.0}, "vignette": {"amount": -18.0}}), + json!({"treatment": "color", "effects": {"clarity": 35.0, "texture": 20.0}, "light": {"contrast": 25.0, "blacks": -15.0}, "color": {"saturation": -30.0}, "vignette": {"amount": -18.0}}), ), p( "Urban", "neon-night", "Neon Night", - json!({"mixer": {"magenta": {"sat": 20.0}, "purple": {"sat": 18.0}, "blue": {"sat": 12.0}, "aqua": {"sat": 15.0}}, "light": {"contrast": 18.0, "blacks": -12.0}, "color": {"vibrance": 15.0}, "grading": {"shadows": {"hue": 250.0, "sat": 15.0, "lum": 0.0}}}), + json!({"treatment": "color", "mixer": {"magenta": {"sat": 20.0}, "purple": {"sat": 18.0}, "blue": {"sat": 12.0}, "aqua": {"sat": 15.0}}, "light": {"contrast": 18.0, "blacks": -12.0}, "color": {"vibrance": 15.0}, "grading": {"shadows": {"hue": 250.0, "sat": 15.0, "lum": 0.0}}}), ), p( "Urban", "concrete-cool", "Concrete Cool", - json!({"grading": {"shadows": {"hue": 205.0, "sat": 14.0, "lum": 0.0}, "highlights": {"hue": 200.0, "sat": 6.0, "lum": 0.0}}, "color": {"saturation": -20.0}, "light": {"contrast": 12.0}, "effects": {"clarity": 15.0}}), + json!({"treatment": "color", "grading": {"shadows": {"hue": 205.0, "sat": 14.0, "lum": 0.0}, "highlights": {"hue": 200.0, "sat": 6.0, "lum": 0.0}}, "color": {"saturation": -20.0}, "light": {"contrast": 12.0}, "effects": {"clarity": 15.0}}), ), p( "Urban", "faded-urban", "Faded Urban", - json!({"curve": {"shadows": 30.0}, "color": {"saturation": -22.0}, "light": {"contrast": -8.0}, "grain": {"amount": 12.0, "size": 25.0, "roughness": 45.0}}), + json!({"treatment": "color", "curve": {"shadows": 30.0}, "color": {"saturation": -22.0}, "light": {"contrast": -8.0}, "grain": {"amount": 12.0, "size": 25.0, "roughness": 45.0}}), ), // ---- Food p( "Food", "fresh-bright", "Fresh & Bright", - json!({"light": {"exposure": 0.25, "shadows": 20.0, "whites": 10.0}, "color": {"vibrance": 22.0}, "effects": {"texture": 15.0}}), + json!({"treatment": "color", "light": {"exposure": 0.25, "shadows": 20.0, "whites": 10.0}, "color": {"vibrance": 22.0}, "effects": {"texture": 15.0}}), ), p( "Food", "warm-table", "Warm Table", - json!({"grading": {"midtones": {"hue": 32.0, "sat": 10.0, "lum": 0.0}}, "mixer": {"orange": {"sat": 10.0}, "red": {"sat": 8.0}}, "light": {"contrast": 8.0}}), + json!({"treatment": "color", "grading": {"midtones": {"hue": 32.0, "sat": 10.0, "lum": 0.0}}, "mixer": {"orange": {"sat": 10.0}, "red": {"sat": 8.0}}, "light": {"contrast": 8.0}}), ), p( "Food", "dark-moody-food", "Dark & Moody", - json!({"light": {"exposure": -0.3, "contrast": 22.0, "highlights": -20.0, "blacks": -15.0}, "effects": {"texture": 18.0}, "vignette": {"amount": -22.0}}), + json!({"treatment": "color", "light": {"exposure": -0.3, "contrast": 22.0, "highlights": -20.0, "blacks": -15.0}, "effects": {"texture": 18.0}, "vignette": {"amount": -22.0}}), ), // ---- Seasons p( "Seasons", "autumn-gold", "Autumn Gold", - json!({"mixer": {"green": {"hue": -30.0, "sat": -10.0}, "yellow": {"hue": -15.0, "sat": 15.0}, "orange": {"sat": 18.0}}, "grading": {"highlights": {"hue": 40.0, "sat": 10.0, "lum": 0.0}}}), + json!({"treatment": "color", "mixer": {"green": {"hue": -30.0, "sat": -10.0}, "yellow": {"hue": -15.0, "sat": 15.0}, "orange": {"sat": 18.0}}, "grading": {"highlights": {"hue": 40.0, "sat": 10.0, "lum": 0.0}}}), ), p( "Seasons", "winter-blue", "Winter Blue", - json!({"grading": {"shadows": {"hue": 215.0, "sat": 18.0, "lum": 0.0}, "highlights": {"hue": 205.0, "sat": 8.0, "lum": 0.0}}, "color": {"saturation": -12.0}, "light": {"whites": 12.0}}), + json!({"treatment": "color", "grading": {"shadows": {"hue": 215.0, "sat": 18.0, "lum": 0.0}, "highlights": {"hue": 205.0, "sat": 8.0, "lum": 0.0}}, "color": {"saturation": -12.0}, "light": {"whites": 12.0}}), ), p( "Seasons", "spring-fresh", "Spring Fresh", - json!({"mixer": {"green": {"hue": 10.0, "sat": 12.0, "lum": 10.0}, "magenta": {"sat": 10.0}}, "light": {"shadows": 15.0}, "color": {"vibrance": 15.0}}), + json!({"treatment": "color", "mixer": {"green": {"hue": 10.0, "sat": 12.0, "lum": 10.0}, "magenta": {"sat": 10.0}}, "light": {"shadows": 15.0}, "color": {"vibrance": 15.0}}), ), p( "Seasons", "summer-haze", "Summer Haze", - json!({"effects": {"dehaze": -12.0}, "curve": {"shadows": 18.0}, "grading": {"highlights": {"hue": 45.0, "sat": 14.0, "lum": 0.0}}, "light": {"contrast": -10.0}}), + json!({"treatment": "color", "effects": {"dehaze": -12.0}, "curve": {"shadows": 18.0}, "grading": {"highlights": {"hue": 45.0, "sat": 14.0, "lum": 0.0}}, "light": {"contrast": -10.0}}), ), // ---- Vintage p( "Vintage", "instant-70s", "Instant ’70s", - json!({"curve": {"shadows": 28.0, "highlights": -18.0}, "grading": {"shadows": {"hue": 170.0, "sat": 14.0, "lum": 0.0}, "highlights": {"hue": 45.0, "sat": 18.0, "lum": 0.0}}, "color": {"saturation": -10.0}, "vignette": {"amount": -15.0}, "grain": {"amount": 20.0, "size": 30.0, "roughness": 55.0}}), + json!({"treatment": "color", "curve": {"shadows": 28.0, "highlights": -18.0}, "grading": {"shadows": {"hue": 170.0, "sat": 14.0, "lum": 0.0}, "highlights": {"hue": 45.0, "sat": 18.0, "lum": 0.0}}, "color": {"saturation": -10.0}, "vignette": {"amount": -15.0}, "grain": {"amount": 20.0, "size": 30.0, "roughness": 55.0}}), ), p( "Vintage", "cross-process", "Cross Process", - json!({"grading": {"shadows": {"hue": 230.0, "sat": 25.0, "lum": 0.0}, "highlights": {"hue": 60.0, "sat": 25.0, "lum": 0.0}}, "light": {"contrast": 22.0}, "color": {"saturation": 10.0}}), + json!({"treatment": "color", "grading": {"shadows": {"hue": 230.0, "sat": 25.0, "lum": 0.0}, "highlights": {"hue": 60.0, "sat": 25.0, "lum": 0.0}}, "light": {"contrast": 22.0}, "color": {"saturation": 10.0}}), ), p( "Vintage", "bleach-bypass", "Bleach Bypass", - json!({"color": {"saturation": -40.0}, "light": {"contrast": 35.0, "highlights": -15.0}, "effects": {"clarity": 15.0}}), + json!({"treatment": "color", "color": {"saturation": -40.0}, "light": {"contrast": 35.0, "highlights": -15.0}, "effects": {"clarity": 15.0}}), ), // ---- B&W toners p( @@ -721,4 +745,140 @@ mod tests { assert_eq!((dv.light.exposure, dv.light.shadows, dv.grain.amount), (0.3, 20.0, 12.0)); let _ = std::fs::remove_dir_all(&d); } + + /// Issue #2159: a color preset after a B&W one brings the colors back. The treatment and the + /// settings the color preset names take its values; a setting it does not name keeps the + /// value the B&W preset gave it. + #[test] + fn a_color_preset_after_a_bw_one_returns_the_colors() { + let mut s = Session::with_demo(); + s.execute("preset.apply", &json!({"id": "lc.bw-high-contrast"})).unwrap(); + let dv = s.develop_of(s.active().unwrap()).unwrap(); + assert_eq!(dv.treatment, lightcraft_develop::Treatment::Bw); + s.execute("preset.apply", &json!({"id": "lc.warm-glow"})).unwrap(); + let dv = s.develop_of(s.active().unwrap()).unwrap(); + assert_eq!(dv.treatment, lightcraft_develop::Treatment::Color, "the color preset restores the treatment"); + assert_eq!(dv.light.contrast, 8.0, "the color preset's values, not the B&W preset's"); + assert_eq!(dv.light.whites, 20.0, "a setting the color preset doesn't name keeps the B&W preset's value"); + } + + /// A manual edit to a setting a preset does not name survives it, though the preset styles + /// the same group (Bright & Airy names exposure, contrast, highlights, shadows and whites). + #[test] + fn a_preset_keeps_a_setting_it_does_not_name_in_the_group_it_styles() { + let mut s = Session::with_demo(); + s.execute("develop.set", &json!({"control": "light.blacks", "value": -30.0})).unwrap(); + s.execute("preset.apply", &json!({"id": "lc.bright-airy"})).unwrap(); + let dv = s.develop_of(s.active().unwrap()).unwrap(); + assert_eq!(dv.light.blacks, -30.0, "blacks is not named by the preset"); + assert_eq!(dv.light.exposure, 0.45, "exposure is named by the preset and takes its value"); + } + + /// Colours a partial preset does not name keep the photo's values. Deep Sky names only the + /// blue and aqua mixer colours, and only their luminance and saturation. + #[test] + fn a_preset_keeps_the_mixer_colours_it_does_not_name() { + let mut s = Session::with_demo(); + s.execute("develop.set", &json!({"control": "mixer.red.sat", "value": 20.0})).unwrap(); + s.execute("develop.set", &json!({"control": "mixer.blue.hue", "value": 15.0})).unwrap(); + s.execute("preset.apply", &json!({"id": "lc.deep-sky"})).unwrap(); + let dv = s.develop_of(s.active().unwrap()).unwrap(); + assert_eq!(dv.mixer.red.sat, 20.0, "a colour the preset doesn't name"); + assert_eq!(dv.mixer.blue.hue, 15.0, "a setting of a named colour that the preset doesn't name"); + assert_eq!(dv.mixer.blue.lum, -25.0, "a setting the preset names takes its value"); + } + + /// Settings that came from an XMP sidecar or a catalog import record no import look, so the + /// camera defaults are not their original: a preset that names only some of their group keeps + /// the rest. + #[test] + fn xmp_imported_exposure_whites_and_blacks_survive_crisp_landscape() { + let mut s = Session::with_demo(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.7})).unwrap(); + s.execute("develop.set", &json!({"control": "light.whites", "value": 10.0})).unwrap(); + s.execute("develop.set", &json!({"control": "light.blacks", "value": -20.0})).unwrap(); + let id = s.active().unwrap(); + assert!(s.catalog.photo(id).unwrap().import_look.is_none()); + s.execute("preset.apply", &json!({"id": "lc.crisp-landscape"})).unwrap(); + let dv = s.develop_of(id).unwrap(); + assert_eq!((dv.light.exposure, dv.light.whites, dv.light.blacks), (0.7, 10.0, -20.0)); + assert_eq!(dv.light.contrast, 12.0, "a setting the preset names takes its value"); + } + + /// Amount 0 applies nothing to a photo with no import look: the photo keeps every value, also + /// the exposure that Bright & Airy names (a camera-default original would reset it to 0). + #[test] + fn amount_zero_applies_nothing_to_a_photo_without_an_import_look() { + let mut s = Session::with_demo(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 2.0})).unwrap(); + let id = s.active().unwrap(); + let before = s.develop_of(id).unwrap(); + s.execute("preset.apply", &json!({"id": "lc.bright-airy", "amount": 0})).unwrap(); + assert_eq!(s.develop_of(id).unwrap(), before); + } + + /// With no import look, a preset's amount moves the named settings from the photo's current + /// values: 50 % of Bright & Airy's exposure (0.45) from 2.0 is 1.225. + #[test] + fn a_preset_amount_without_an_import_look_is_measured_from_the_current_settings() { + let mut s = Session::with_demo(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 2.0})).unwrap(); + s.execute("preset.apply", &json!({"id": "lc.bright-airy", "amount": 50})).unwrap(); + let dv = s.develop_of(s.active().unwrap()).unwrap(); + assert!((dv.light.exposure - 1.225).abs() < 1e-9, "{}", dv.light.exposure); + } + + /// A photo whose default preset recorded an import look measures a preset's amount from that + /// look: 50 % is halfway from the look to the preset whatever the photo was edited to, and + /// 0 % gives the look's value for the settings the preset names. + #[test] + fn a_preset_amount_is_measured_from_the_import_look_when_there_is_one() { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let mut p = (**s.catalog.photo(id).unwrap()).clone(); + let mut look = p.camera_defaults(); + look.light.exposure = 0.5; + look.light.blacks = -10.0; + p.import_look = Some(std::sync::Arc::new(look.clone())); + p.develop = std::sync::Arc::new(look); + s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id: p.id }).unwrap(); + s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(p) }).unwrap(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 2.0})).unwrap(); + s.execute("develop.set", &json!({"control": "light.blacks", "value": -30.0})).unwrap(); + s.execute("preset.apply", &json!({"id": "lc.bright-airy", "amount": 50})).unwrap(); + let dv = s.develop_of(id).unwrap(); + assert!((dv.light.exposure - 0.475).abs() < 1e-9, "{}", dv.light.exposure); + assert_eq!(dv.light.blacks, -30.0, "a setting the preset doesn't name keeps the photo's edit"); + s.execute("preset.apply", &json!({"id": "lc.bright-airy", "amount": 0})).unwrap(); + let dv = s.develop_of(id).unwrap(); + assert_eq!(dv.light.exposure, 0.5, "amount 0 gives the import look's value for a setting the preset names"); + } + + /// A photo whose import look records a free crop aspect (null) but whose edits locked one + /// gets the import value back at 0 % from a preset that names the aspect: the lock is not + /// kept (the baseline of the amount contract), the cleared option is restored. + #[test] + fn amount_zero_restores_a_null_import_aspect() { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let mut p = (**s.catalog.photo(id).unwrap()).clone(); + let look = p.camera_defaults(); + p.import_look = Some(std::sync::Arc::new(look.clone())); + p.develop = std::sync::Arc::new(look); + s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id: p.id }).unwrap(); + s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(p) }).unwrap(); + s.execute("crop.aspect", &json!({"aspect": [3, 2]})).unwrap(); + assert!(s.develop_of(id).unwrap().crop.aspect.is_some(), "the aspect is locked for this test"); + let added = s.add_presets(vec![lightcraft_develop::Preset { + id: "user.free-aspect".into(), + name: "Free aspect".into(), + group: "Test".into(), + settings: json!({"crop": {"aspect": null}}), + favorite: false, + builtin: false, + }]); + s.execute("preset.apply", &json!({"id": added[0], "amount": 0})).unwrap(); + let dv = s.develop_of(id).unwrap(); + assert_eq!(dv.crop.aspect, None, "amount 0 gives the import look's free aspect back"); + } } diff --git a/crates/ui-egui/src/panels/presets.rs b/crates/ui-egui/src/panels/presets.rs index 277c62b26b..b261506f69 100644 --- a/crates/ui-egui/src/panels/presets.rs +++ b/crates/ui-egui/src/panels/presets.rs @@ -158,7 +158,6 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } let active = app.session.active(); let marked = AppliedByPhoto::of(ui.ctx(), &app.session, active); - let current = active.and_then(|id| app.session.develop_of(id)).map(|d| (*d).clone()); let thumbs = app.ui.preset_thumbs && active.is_some(); let row_h = if thumbs { 54.0 } else { 26.0 }; let groups = grouped(ui.ctx(), &app.session.presets); @@ -220,7 +219,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } else if resp.hovered() { ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.7)); } - let look = if thumbs || resp.hovered() { current.as_ref().map(|d| pr.apply(d, 1.0)) } else { None }; + // the preview is what a click commits: the same composition as `preset.apply` (`Session::preset_applied`) + let look = if thumbs || resp.hovered() { active.and_then(|id| app.session.preset_applied(id, &pr, 1.0)) } else { None }; let mut text_x = r.left() + 40.0; if thumbs && let (Some(id), Some(s)) = (active, look.as_ref()) { let tr = Rect::from_min_size(pos2(r.left() + 36.0, r.top() + 5.0), vec2(66.0, row_h - 10.0)); @@ -312,12 +312,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let pointer_in_scroll = ui.ctx().input(|i| i.pointer.hover_pos()).is_some_and(|pos| scroll.inner_rect.contains(pos)); if pointer_in_scroll { if app.hover_preview.is_none() - && let (Some(id), Some(curr)) = (active, current.as_ref()) + && let Some(id) = active && let Some((saved_id, saved_preset, saved_label)) = ui.data(|d| d.get_temp::<(lightcraft_catalog::PhotoId, Preset, String)>(last_hover_id)) && saved_id == id + && let Some(s) = app.session.preset_applied(id, &saved_preset, 1.0) { - app.hover_preview = Some(HoverPreview { label: saved_label, settings: saved_preset.apply(curr, 1.0) }); + app.hover_preview = Some(HoverPreview { label: saved_label, settings: s }); } } else { ui.data_mut(|d| d.remove::<(lightcraft_catalog::PhotoId, Preset, String)>(last_hover_id)); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index ef39208967..673552558c 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -320,10 +320,10 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| LR-PRE-PANEL | Presets panel | P0 | ✅ | `cmd:panel.presets`, `cmd:preset.apply`, `crates/ui-egui/src/panels/presets.rs` | grouped list with amount; the preset applied to a photo stays marked on returning to it until the photo is edited further (issue #2392); resting on a preset previews it in the loupe (no history entry); optional live thumbnails (⋯ → Show Thumbnails) | +| LR-PRE-PANEL | Presets panel | P0 | ✅ | `cmd:panel.presets`, `cmd:preset.apply`, `crates/ui-egui/src/panels/presets.rs` | grouped list with amount; the preset applied to a photo stays marked on returning to it until the photo is edited further (issue #2392); resting on a preset previews it in the loupe (no history entry); optional live thumbnails (⋯ → Show Thumbnails); a preset changes only the settings it names: each is computed on the photo's import state (or on its current settings when no default preset recorded one), and every setting it does not name keeps the photo's value, so a second preset restores what an earlier one changed in the settings it names (issue #2159) | | LR-PRE-CREATE | Create preset | P0 | ✅ | `cmd:dialog.createPreset`, `cmd:preset.create` (`groups`) | name, group and a checklist of settings groups (crop, masks, remove, red eye off by default; All / None) | | LR-PRE-MANAGE | Manage presets | P1 | ✅ | `cmd:preset.delete`, `cmd:preset.favorite`, `cmd:preset.import`, `cmd:preset.export`, `cmd:preset.rename`, `cmd:preset.update`, `cmd:preset.move` | rename, update with current settings, move to a group (existing or new); starred presets are listed in a Favorites section on top, as in the Profile browser (issue #1999, `crates/ui-egui/src/tests/preset_favorites.rs`); no hiding of groups | -| LR-PRE-AMOUNT | Preset amount | P1 | ✅ | `cmd:preset.apply` (`amount` 0–200) | | +| LR-PRE-AMOUNT | Preset amount | P1 | ✅ | `cmd:preset.apply` (`amount` 0–200) | each named setting moves from the photo's import look (or, when none is recorded, from its current value) towards the preset's value; 0 % gives the import look's value for the settings the preset names, and the current value when no look is recorded | | LR-PRE-ADAPTIVE | Adaptive presets | P2 | ⬜ | | | | LR-PRE-PREMIUM | Built-in presets (own) | P2 | ✅ | `crates/engine/src/presets.rs` | 41 own-authored presets in 10 groups (Color, Film, B&W incl. toners, Portrait, Landscape, Urban, Food, Seasons, Vintage, Style) | | LR-PRE-RECOMMENDED | Community recommendations | OOS | 🚫 | | | @@ -1042,6 +1042,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-29 | patch | LR-BEHAV-TITLEBAR: a dialog's backdrop leaves the integrated title bar undimmed, as a macOS sheet does (the bar's controls stay inactive, a click on it is not a click outside the dialog, dragging its empty space still moves the window); status unchanged (🟡) | | 2026-10-29 | minor | LR-MASK-OBJECTS: an Object / Describe selection's stored grid is enlarged along the photo's edges (fast guided filter of its logits by log luminance, a 1.5-cell window), so a raised Exposure no longer draws an outline around the subject (#3272); existing AI masks are 1–2 px tighter at edges; status unchanged (🟡) | | 2026-10-30 | patch | LR-MASK-COLORRANGE: a colour-range mask keeps its first 64 samples however it is loaded (sidecar `lc:settings`, presets, `develop.merge`, `render --settings`, catalog and history), not only through `mask.add` / `mask.update`, so a document with thousands can't stall a render or lose the GPU device (issue #2556); status unchanged (✅) | +| 2026-10-20 | patch | LR-PRE-PANEL, LR-PRE-AMOUNT: a preset changes only the settings it names; each is measured from the photo's import look when one is recorded, otherwise from its current value (issue #2159). Statuses and feature counts unchanged. | | 2026-10-17 | minor | LR-EXP-DIALOG: built-in export presets for the issue #2104 delivery targets — Instagram Feed (1080 px, screen sharpening), Instagram Story / Reel (1920 px), Web / Portfolio (2048 px, copyright-only metadata), Full Resolution Master (full size, Display P3, quality 95); LR-EXP-PREVIOUS drops its stale "no named export presets yet" note; status unchanged (✅) | | 2026-10-17 | minor | LR-EXP-DIALOG: built-in export presets for the issue #2104 delivery targets — Instagram Feed (1080 px, screen sharpening), Instagram Story / Reel (1920 px), Web / Portfolio (2048 px, copyright and creator metadata), Full Resolution Master (full size, Display P3, quality 95); LR-EXP-PREVIOUS drops its stale "no named export presets yet" note; status unchanged (✅) | | 2026-10-20 | patch | LR-EXP-DIALOG: the four built-in export presets are translated in all 17 catalogs (translations pending native-speaker review); Instagram Story / Reel states that it applies no crop to 9:16; status unchanged (✅) | From aa52251d2ef3bb2e4014f20943c4c4c83ce0d931 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Thu, 5 Nov 2026 23:12:18 +0200 Subject: [PATCH 15/24] Apply Auto settings to every selected photo (#3808) * Apply Auto settings to every selected photo Users expect Auto and preset application to affect the whole selection, as Quick Develop already does. `develop.auto` is the only edit command in that file that hard-codes the active photo instead of the selection. Make `develop.auto` accept the same target rule as the other selection commands (`ids` when given, else the selection), analyse each target photo's own source with `auto_tone`, and commit the results as one batched undo step labelled "Auto". Test: auto_applies_to_every_selected_photo failed before the change and passes after. * Run multi-photo Auto settings off the UI thread Assisted-by: OpenAI Codex * Auto Settings: skip unreadable photos and refuse stale results One offline photo stopped Auto for the whole selection. The background result is checked against each photo's settings, because an undo changes them without a commit, and it commits through the command wrapper so sidecars and the durable save follow. Co-Authored-By: Claude Opus 5.5 * Auto Settings: a wrong photo id is refused, not skipped Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/develop.rs | 63 ++++++++--- crates/engine/src/tests.rs | 33 ++++++ crates/ui-egui/src/auto_settings.rs | 163 ++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus/run.rs | 3 + 5 files changed, 245 insertions(+), 18 deletions(-) create mode 100644 crates/ui-egui/src/auto_settings.rs diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 42e2793daf..5399aee9b8 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -460,24 +460,51 @@ pub fn specs() -> Vec { Ok(json!({"mix": m})) } ), - cmd!("develop.auto", "Auto Settings", ["Photo"], Some("Shift+A"), "{}", has_active, |s, _| { - let id = active(s, "develop.auto")?; - let src = s.source_now(id, SourceLevel::Thumb).map_err(|e| bad("develop.auto", e))?; - let info = s.source_info(id); - let d = s.develop_of(id).unwrap_or_default(); - let a = lightcraft_pipeline::auto::auto_tone(&src, &info, &d); - edit(s, "develop.auto", "Auto", |d| { - d.light.exposure = a.exposure; - d.light.contrast = a.contrast; - d.light.highlights = a.highlights; - d.light.shadows = a.shadows; - d.light.whites = a.whites; - d.light.blacks = a.blacks; - d.color.vibrance = a.vibrance; - d.color.saturation = a.saturation; - Ok(()) - })?; - Ok(serde_json::to_value(a).unwrap_or_default()) + cmd!("develop.auto", "Auto Settings", ["Photo"], Some("Shift+A"), "{}", has_selection, |s, p| { + const C: &str = "develop.auto"; + let ids = s.targets(p)?; + // a wrong id is a bad request, unlike a photo that can't be read just now + if let Some(id) = ids.iter().find(|id| s.catalog.photo(**id).is_none()) { + return Err(bad(C, format!("no such photo: {}", id.0))); + } + let mut first: Option = None; + let mut ops: Vec = Vec::new(); + let mut failed = None; + for id in ids { + // a photo that can't be read (offline, no decoder) is left out, not the whole selection + let src = match s.source_now(id, SourceLevel::Thumb) { + Ok(src) => src, + Err(e) => { + failed.get_or_insert(e); + continue; + } + }; + let info = s.source_info(id); + let d = s.develop_of(id).unwrap_or_default(); + let a = lightcraft_pipeline::auto::auto_tone(&src, &info, &d); + if first.is_none() { + first = Some(serde_json::to_value(a).unwrap_or_default()); + } + let mut nd = (*d).clone(); + nd.light.exposure = a.exposure; + nd.light.contrast = a.contrast; + nd.light.highlights = a.highlights; + nd.light.shadows = a.shadows; + nd.light.whites = a.whites; + nd.light.blacks = a.blacks; + nd.color.vibrance = a.vibrance; + nd.color.saturation = a.saturation; + if let Some(op) = s.develop_op(id, nd, "Auto") { + ops.push(op); + } + } + if let (None, Some(e)) = (&first, failed) { + return Err(bad(C, e)); + } + if !ops.is_empty() { + s.commit("Auto", Op::Batch { ops })?; + } + Ok(first.unwrap_or_default()) }), cmd!( "develop.wb", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 03592df41b..632814334d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -499,6 +499,39 @@ fn masks_crop_and_render() { s.execute("develop.wbPick", &json!({"x": 0.5, "y": 0.5})).unwrap(); } +/// Auto applies to every selected photo, not only the highlighted one (#2184). +#[test] +fn auto_applies_to_every_selected_photo() { + use lightcraft_catalog::PhotoId; + let mut s = demo(); + let ids: Vec = s.catalog.photos().take(3).map(|p| p.id.0).collect(); + assert_eq!(ids.len(), 3, "the demo library has enough photos to select"); + s.execute("library.select", &json!({"ids": ids.clone(), "active": ids[1]})).unwrap(); + s.execute("develop.auto", &json!({})).unwrap(); + for id in ids { + let d = (*s.develop_of(PhotoId(id)).unwrap()).clone(); + assert_eq!(d.light.contrast, 68.0, "photo {id} got Auto's contrast"); + assert_eq!(d.color.vibrance, 30.0, "photo {id} got Auto's vibrance"); + } +} + +/// A photo that can't be read is left out: the rest of the selection still gets Auto. +#[test] +fn auto_skips_a_selected_photo_it_cannot_read() { + use lightcraft_catalog::{Op, Photo, PhotoId, Source}; + let mut s = demo(); + let good = s.catalog.photos().next().unwrap().id; + let missing = s.catalog.alloc_photo_id(); + let photo = Photo::new(missing, Source::File { path: "/lightcraft-test/missing.jpg".into() }, "missing.jpg", "JPEG", 100, 100, ""); + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + s.execute("library.select", &json!({"ids": [missing.0, good.0], "active": good.0})).unwrap(); + s.execute("develop.auto", &json!({})).unwrap(); + assert_eq!(s.develop_of(PhotoId(good.0)).unwrap().color.vibrance, 30.0, "the readable photo got Auto"); + s.execute("library.select", &json!({"ids": [missing.0], "active": missing.0})).unwrap(); + assert!(s.execute("develop.auto", &json!({})).is_err(), "with nothing readable the error is reported"); + assert!(s.execute("develop.auto", &json!({"ids": [good.0, 999_999]})).is_err(), "a wrong id is refused, not skipped"); +} + #[test] fn versions_history_and_reset() { let mut s = demo(); diff --git a/crates/ui-egui/src/auto_settings.rs b/crates/ui-egui/src/auto_settings.rs new file mode 100644 index 0000000000..47fbdfe478 --- /dev/null +++ b/crates/ui-egui/src/auto_settings.rs @@ -0,0 +1,163 @@ +//! Auto Settings decodes a selection off the UI thread and commits it as one undo step. +use crate::LightcraftApp; +use lightcraft_catalog::{Op, PhotoId}; +use lightcraft_develop::DevelopSettings; +use lightcraft_engine::media::{SourceLevel, SourceRef}; +use lightcraft_pipeline::SourceInfo; +use serde_json::{Value, json}; +use std::sync::{Arc, atomic::AtomicBool}; + +const LABEL: &str = "Auto Settings"; +struct Input { + id: PhotoId, + settings: Arc, + source: SourceRef, + info: SourceInfo, +} +struct Prepared { + library: u64, + commits: u64, + inputs: Vec, +} +struct Completed { + library: u64, + commits: u64, + /// Each photo's settings as they were read, and with Auto. + settings: Vec<(PhotoId, Arc, DevelopSettings)>, + /// Photos left out because they could not be read. + skipped: usize, +} + +fn prepare(app: &mut LightcraftApp, params: &Value) -> Result { + let ids = app.session.targets(params).map_err(|e| e.to_string())?; + let mut inputs = Vec::with_capacity(ids.len()); + for id in ids { + let photo = app.session.catalog.photo(id).ok_or("Auto Settings: no such photo")?.clone(); + let settings = app.session.develop_of(id).ok_or("Auto Settings: no develop settings")?; + let info = app.session.source_info(id); + let source = app.session.media.source_ref(&photo, SourceLevel::Thumb); + inputs.push(Input { id, settings, source, info }); + } + Ok(Prepared { library: app.session.library_generation(), commits: app.session.commits(), inputs }) +} +impl Prepared { + fn run(self, progress: Option<&lightcraft_engine::activity::TaskHandle>) -> Result { + let total = self.inputs.len() as u64; + let mut settings = Vec::with_capacity(self.inputs.len()); + let mut failed: Option = None; + let mut skipped = 0; + for (i, input) in self.inputs.into_iter().enumerate() { + if progress.is_some_and(|p| p.is_cancelled()) { + return Err("Auto Settings cancelled".into()); + } + // a photo that can't be read (offline, no decoder) is left out, not the whole selection + let source = match input.source.load_source() { + Ok(source) => source, + Err(error) => { + failed.get_or_insert(error); + skipped += 1; + continue; + } + }; + let info = source.info_or(input.info); + let auto = lightcraft_pipeline::auto::auto_tone(&source.image, &info, &input.settings); + let mut develop = (*input.settings).clone(); + develop.light.exposure = auto.exposure; + develop.light.contrast = auto.contrast; + develop.light.highlights = auto.highlights; + develop.light.shadows = auto.shadows; + develop.light.whites = auto.whites; + develop.light.blacks = auto.blacks; + develop.color.vibrance = auto.vibrance; + develop.color.saturation = auto.saturation; + settings.push((input.id, input.settings, develop)); + if let Some(p) = progress { + p.progress(i as u64 + 1, total); + } + } + if progress.is_some_and(|p| p.is_cancelled()) { + return Err("Auto Settings cancelled".into()); + } + if let (true, Some(error)) = (settings.is_empty(), failed) { + return Err(error); + } + Ok(Completed { library: self.library, commits: self.commits, settings, skipped }) + } +} +fn apply(app: &mut LightcraftApp, completed: Completed) -> Result { + // An undo or a live edit changes a photo's settings without a commit: compare the settings too. + let moved = completed.settings.iter().any(|(id, before, _)| app.session.develop_of(*id).is_none_or(|now| now != *before)); + if app.session.library_generation() != completed.library || app.session.commits() != completed.commits || moved { + return Err("Auto Settings was not applied because the library changed; try again".into()); + } + let ops: Vec = completed.settings.into_iter().filter_map(|(id, _, d)| app.session.develop_op(id, d, "Auto")).collect(); + if !ops.is_empty() { + // through the command wrapper, so sidecars and the durable save follow as for any edit + app.session + .execute_fn("develop.auto", |s| { + s.commit("Auto", Op::Batch { ops })?; + Ok(Value::Null) + }) + .map_err(|e| e.to_string())?; + } + Ok(completed.skipped) +} +pub(crate) fn command(app: &mut LightcraftApp, params: &Value) -> Result { + if app.tasks.is_running(LABEL) { + return Err("Auto Settings is already running".into()); + } + let prepared = prepare(app, params)?; + let count = prepared.inputs.len(); + let cancel = Arc::new(AtomicBool::new(false)); + crate::tasks::spawn_tracked( + app, + LABEL, + "auto", + cancel, + move |progress| prepared.run(Some(&progress)), + |app, ctx, result| match result.and_then(|done| apply(app, done)) { + Ok(0) => app.toast(ctx, crate::i18n::tr("Auto Settings").to_owned()), + Ok(skipped) => app.toast(ctx, format!("{}: {skipped} photo(s) could not be read", crate::i18n::tr("Auto Settings"))), + Err(error) => app.toast(ctx, error), + }, + )?; + Ok(json!({"pending": true, "photos": count})) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + fn app() -> LightcraftApp { + LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()) + } + #[test] + fn selection_auto_is_deferred_and_commits_once() { + let mut app = app(); + let ids: Vec<_> = app.session.catalog.photos().take(3).map(|p| p.id).collect(); + app.session.execute("library.select", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + let before = app.session.commits(); + let reply = app.run("develop.auto", json!({})).unwrap(); + assert_eq!(reply["pending"], true); + assert_eq!(reply["photos"], 3); + assert_eq!(app.session.commits(), before, "decoding cannot mutate the UI session"); + assert!(app.tasks.is_running(LABEL)); + assert!(crate::tasks::wait_for(&mut app, &egui::Context::default(), LABEL, std::time::Duration::from_secs(60))); + assert_eq!(app.session.commits(), before + 1); + for id in ids { + assert_eq!(app.session.develop_of(id).unwrap().color.vibrance, 30.0); + } + } + #[test] + fn selection_auto_does_not_overwrite_newer_edits_or_another_library() { + let mut app = app(); + let done = prepare(&mut app, &json!({})).unwrap().run(None).unwrap(); + app.session.execute("develop.set", &json!({"control":"light.exposure", "value": 1.25})).unwrap(); + let before = app.session.commits(); + assert!(apply(&mut app, done).is_err()); + assert_eq!(app.session.commits(), before); + let done = prepare(&mut app, &json!({})).unwrap().run(None).unwrap(); + app.session = lightcraft_engine::Session::with_demo(); + assert!(apply(&mut app, done).is_err()); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c9457e4417..5bfccc8fb7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -87,6 +87,7 @@ pub use widgets::rating; pub use widgets::text_field; mod app; +mod auto_settings; mod caches; mod clock; mod services; diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 730bde3df4..9791f0cac3 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -154,6 +154,9 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option Date: Thu, 5 Nov 2026 16:23:31 -0500 Subject: [PATCH 16/24] LR-IMP-FORMATS: pure-Rust clean-room compressed Olympus ORF bitstream decoder (#3775) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * LR-IMP-FORMATS: pure-Rust compressed Olympus ORF bitstream decoder * LR-IMP-FORMATS: address CodeRabbit review feedback on PR #3747 * orf: bound predictor arithmetic, bit widths, and stream consumption * orf: use unsigned magnitude abs_diff for predictor differences * docs: correct Olympus verified-body count in parity header * orf: saturating wbits derivation, widen pixel shift to i64 before clamp * docs: sync raw parity headline figures with coverage tables * docs: record clean-room provenance and report 58 newly unlocked bodies for compressed ORF * docs: note LibRaw derivation and pending clean-room reimplementation for compressed ORF * LR-IMP-FORMATS: pure-Rust clean-room compressed Olympus ORF bitstream decoder * LR-IMP-FORMATS: sync orfc path in parity docs and correct mainstream weighted depth sum * LR-IMP-FORMATS: address CodeRabbit review feedback on ORF gap and evidence sync * Convert Negative 1/4: lightcraft-film, the negative conversion maths from Film Lab (#2490) The film model, levels in density space, film presets, colour and tone of Film Lab's core (same author, MIT), without the PhotoCraft-only sharpening and JSON scanning, plus a whole-scan measurement (base, black and white points, neutral balance) a host stores with a photo's settings. A library with no caller yet. Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> * LR-IMP-FORMATS: address CodeRabbit PR #3775 review (round 2) - orf.rs: scope sample-based bit-depth inference to Word16 branch only (from_word16 flag prevents heuristic from running on compressed ORF data) - orfc.rs: reject truncated compressed streams before allocating the frame (minimum 1 bit per pixel check) - orfc.rs: remove feedback_shift_644 == 15 special case (ordinary exponent) - ROADMAP/README/target-app-parity: fix '78 bodies' to '58 more bodies (2 verified)' — 78 is total Olympus+OM count, 58 were newly unlocked - target-app-parity: RAW readiness 80% -> 87%, recompute weighted sums - parity-checklist: refresh summary via cargo xtask parity --write Generated with Antigravity * LR-IMP-FORMATS: address CodeRabbit PR #3775 review (round 3) - target-app-parity: RAW camera decoding 85% -> 89% (559+721 of 1446) - target-app-parity: mainstream practitioner row lists ORF as per-model verification, not as unfinished decoder alongside CR3/HE NEF - log_writer: check_regular_directory_entry before truncate open (prevents symlink-following truncation of files outside the library) Generated with Antigravity * LR-IMP-FORMATS: regenerate parity summary after film crate merge cargo xtask parity --write: 83.2% of 543 in-scope rows (was 83.5%/532); sync target-app-parity.md checklist references to match. Generated with Antigravity --------- Co-authored-by: Yorgos S. Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- README.md | 4 +- ROADMAP.md | 17 +- crates/catalog/src/log_writer.rs | 1 + crates/raw/src/lib.rs | 4 +- crates/raw/src/vendor.rs | 1 + crates/raw/src/vendor/orf.rs | 38 +- crates/raw/src/vendor/orfc.rs | 489 ++++++++++++++++++ crates/raw/tests/it/corpus.rs | 1 - crates/raw/tests/it/olympus_samsung_corpus.rs | 2 + docs/gaps.md | 5 +- docs/orf-compression.md | 107 ++++ docs/parity-checklist.md | 5 +- docs/raw-parity.md | 37 +- docs/raw/coverage.py | 4 +- docs/raw/coverage.tsv | 122 ++--- docs/raw/evidence.tsv | 2 + docs/roadmap.md | 4 +- docs/target-app-parity.md | 52 +- 18 files changed, 757 insertions(+), 138 deletions(-) create mode 100644 crates/raw/src/vendor/orfc.rs create mode 100644 docs/orf-compression.md diff --git a/README.md b/README.md index 1b64265b3a..21ff4306ec 100644 --- a/README.md +++ b/README.md @@ -350,7 +350,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det 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 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); + - **unsupported CR3 variants and Nikon High Efficiency NEFs:** these use embedded JPEG previews when present. Olympus compressed ORF now decodes sensor data on 58 more bodies (2 verified) ([docs/orf-compression.md](docs/orf-compression.md)); 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 linear-RGB denoise and Super Resolution remain missing; see [AI masks](docs/ai-masks.md) and [AI Denoise](docs/denoise.md); @@ -370,7 +370,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det | Profiles (Color, Neutral, Vivid, Landscape, Portrait, Monochrome: our own looks), presets, versions, history, copy/paste/sync settings | ✅ | | Camera colour: DNG matrices, guarded camera-JPEG look fits and built-in profiles for selected cameras | 🚧 measured calibration and per-model coverage remain incomplete ([raw parity](docs/raw-parity.md)) | | Native macOS menu bar (generated from the command registry), control channel + every widget addressable, headless UI snapshots | ✅ | -| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed ORF / SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) | +| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp, compressed), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) | | Detail: sharpening, luminance + colour noise reduction | ✅ · AI Denoise 🚧 (Bayer, user-installed weights; [setup](docs/denoise.md)), Super Resolution ⬜ | | Remove / Heal / Clone spots (auto source), non-generative Fill, editable spot pins, Visualize Spots, Red Eye and Pet Eye | ✅ · Fill uses PatchMatch; no generative fill | | Export: JPEG / PNG / TIFF / flat PSD / WebP / AVIF / JPEG XL / raw or rendered DNG / original, sizing, file-size limit, output sharpening, naming templates, batch, metadata policy, text or image watermark | ✅ | diff --git a/ROADMAP.md b/ROADMAP.md index 1ed4dbd0a3..8804f42701 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -14,25 +14,25 @@ from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are |---|---:|---| | **Feature breadth** (checklist) | **81.6%** of 532 rows (P0 98.0%, P1 95.2%, P2 50.0%) | measured: [parity-checklist.md](docs/parity-checklist.md) recount | | **Feature breadth** (weighted by use) | **~77%** | estimated | -| **Ready for real work** (full target) | **~61%** (56–66%) | estimated: weighted sum over the dimensions | +| **Ready for real work** (full target) | **~62%** (57–67%) | estimated: weighted sum over the dimensions | | **Mainstream practitioner** | **~51%** (46–56%) | estimated | | **Essentials user** | **~65%** (60–70%) | estimated | | Remaining to **beta** | **~340–600 h** (Opus 5.5 agent hours, ~60% parallel) | estimated | -| Remaining to **full parity** | **~1,000–1,800 h** (~70% parallel) | estimated | +| Remaining to **full parity** | **~980–1,750 h** (~70% parallel) | estimated | Each audience with its own hours (Opus 5.5 agent wall-clock hours to ~95%): | Audience | Ready | Opus 5.5 agent wall-clock hours to ~95% | Work that dominates | |---|---:|---:|---| -| Full target (ready for real work) | **~61%** | **1,000–1,800 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem | -| Mainstream practitioner | **~51%** | **450–840 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability | +| Full target (ready for real work) | **~62%** | **980–1,750 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem | +| Mainstream practitioner | **~51%** | **440–820 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability | | Essentials user | **~65%** | **160–300 h** (~50% parallelizes) | default raw look for popular cameras; launch stability; basic-slider feel; opening CR3 / HEIC files people send | The gap between breadth and readiness is quality and coverage, not missing buttons: camera colour is -estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), compressed ORF and HE NEF -open as previews, rendering is tuned by eye, AI masks are heuristics, there is no lens database, and +estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), HE NEF opens +as preview (compressed ORF now decodes on 58 more bodies (2 verified)), rendering is tuned by eye, AI masks are heuristics, there is no lens database, and tests run in CI on Linux x64 (every pull request and push to `main`) and FreeBSD (nightly), not on macOS or Windows. **Why alpha:** core workflows run end to end, but readiness is below -the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have blocking gaps (compressed ORF and HE NEF open as previews; Canon, +the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have gaps (Nikon HE NEF opens as preview; Canon, ~30% of raw users, decodes CR3 on 26 verified bodies). It passes the alpha gate: all six core workflows (import, cull, develop, save and reopen, batch looks, export) work end to end on macOS ([docs/roadmap.md](docs/roadmap.md#alpha-gate)). The three readiness numbers and their weights and discounts are in @@ -107,13 +107,14 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ 3. Render-fidelity suite against Lightroom, then tuning (30–60 h) 4. ~~Full-resolution zoom~~ (done 2026-10-12) 5. AI masks: Subject / Sky / People (40–70 h + model decision) -6. Compressed ORF and HE NEF (28–55 h) +6. ~~Compressed ORF~~ (done 2026-11-04) and HE NEF (20–40 h) 7. Lens profile database of our own (40–80 h, #329) 8. Tests in CI on macOS and Windows, and the GPU tests in CI (6–12 h) 9. Per-model raw verification (20–35 h) ## Progress log +- 2026-11-04: Olympus / OM System compressed ORF decodes from sensor data: clean-room pure-Rust bitstream decoder (`crates/raw/src/vendor/orfc.rs`) derived strictly from Olympus patents US7333035B2/US7715639B2, maker notes and CC0 samples without third-party decoder code (see `docs/orf-compression.md`), verified on OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) CC0 samples; 58 bodies newly unlocked (78 total across Olympus and OM; OM/Olympus 6% → 81% fully working, overall weighted camera coverage 94% → 97%). - 2026-10-22: Print page setup and PDF output gain the Japanese photo and postcard papers — L判 (89 × 127 mm), 2L判 (127 × 178), KG判 (102 × 152), はがき (100 × 148), 往復はがき (148 × 200), 六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog diff --git a/crates/catalog/src/log_writer.rs b/crates/catalog/src/log_writer.rs index 6018f71f66..b80d8e462c 100644 --- a/crates/catalog/src/log_writer.rs +++ b/crates/catalog/src/log_writer.rs @@ -238,6 +238,7 @@ impl Writer { return Ok(()); } self.file = None; + crate::store::check_regular_directory_entry(&self.path)?; let f = match std::fs::OpenOptions::new().write(true).open(&self.path) { Ok(f) => f, Err(e) if e.kind() == io::ErrorKind::NotFound => { diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index 371891ddf7..687c20b924 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -18,8 +18,8 @@ //! Canon CR2 / CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW) / CRW (the CIFF bodies of 2000–2004; clean-room-derived //! compression, `vendor::crw`; the PowerShot G5's anomalous coding is refused), Nikon NEF/NRW (uncompressed, Huffman lossless / lossy compressed), Sony ARW (uncompressed, ARW2, lossless), Fujifilm RAF (uncompressed Bayer //! and X-Trans, lossless and lossy compressed), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format: compressed 4 and 6, the prefix-coded strips of 8, -//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, 12-bit 16-byte blocks of the E-300/E-330/E-500). -//! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (compressed ORF, CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources +//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, 12-bit 16-byte blocks of the E-300/E-330/E-500; compressed: 12-bit entropy-coded sensor differences across interchangeable-lens and modern compact bodies). +//! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources //! (public specifications, tag-name documentation, black-box analysis of CC0 samples) and gaps. Non-DNG files carry no //! colour matrix: [`spectral`] has matrices fitted to measured spectral sensitivities for 52 models, and //! otherwise [`color`] falls back to a documented neutral model. The decoders never panic on malformed input. diff --git a/crates/raw/src/vendor.rs b/crates/raw/src/vendor.rs index a44262a2c4..6b27843d56 100644 --- a/crates/raw/src/vendor.rs +++ b/crates/raw/src/vendor.rs @@ -21,6 +21,7 @@ pub mod nef; mod nef_lens; pub mod nefc; pub mod orf; +pub(crate) mod orfc; pub mod pef; pub mod raf; mod raf_lens; diff --git a/crates/raw/src/vendor/orf.rs b/crates/raw/src/vendor/orf.rs index ee1d1f48d2..97a640ddff 100644 --- a/crates/raw/src/vendor/orf.rs +++ b/crates/raw/src/vendor/orf.rs @@ -1,4 +1,4 @@ -//! Olympus ORF — uncompressed variants. +//! Olympus ORF — uncompressed and compressed variants. //! //! Sources: TIFF 6.0 (the `IIRO`/`MMOR` container is a TIFF with a different magic number), Exif 2.3 (`CFAPattern`, //! tag `0xa302`), the ExifTool Olympus tag-name documentation (maker-note sub-directories `0x2020` CameraSettings — @@ -28,8 +28,9 @@ //! (last), the bit order and the pixel order were fixed by measurement on the CC0 files 2878 (E-300), 3540 (E-500) //! and 3624 (E-330), as was the sensor-origin RGGB anchoring (the maker-note crop offsets are odd). The E-M5 Mark II //! and PEN-F files were only checked for smoothness, not for CFA anchoring or black level. -//! - Olympus's compressed ORF (most interchangeable-lens bodies since ~2008) is not decoded: no permissively -//! licensed description exists. It reports [`RawError::Unsupported`]; the embedded preview still works. +//! - Olympus's compressed ORF (interchangeable-lens bodies and compacts using the 12/14-bit entropy coding stream): +//! decoded clean-room in `orfc.rs` from Olympus patents US7333035B2 and US7715639B2 (Takashi Ishikawa) and black-box +//! CC0 samples (OM-D E-M1, E-M10 Mark III). No GPL/LibRaw code was consulted. See `docs/orf-compression.md`. //! - The colour-filter layout is the file's Exif `CFAPattern`: GRBG on the E-1 and E-400, RGGB on the XZ-2, where //! the colours of the decoded mosaic follow the embedded JPEG best with exactly that layout //! (`corpus_orf_cfa_patterns`). The samples' active areas start at even offsets, so they can't tell whether the @@ -199,6 +200,7 @@ fn field_rows(strips: &[(u64, u64)], w: usize, h: usize, file_len: usize) -> Opt Some(rows) } +/// Decode an Olympus ORF container into a mosaic raw image, supporting uncompressed 16-bit, packed 12-bit, and compressed formats. pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let tiff = Tiff::parse(bytes)?; let ifd0 = &tiff.ifds[0]; @@ -209,11 +211,13 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let total = chunks.iter().fold(0u64, |a, c| a.saturating_add(c.len)); let stated = cfa_from_exif(&tiff); let mut two_field = false; - let (mut data, bits) = if info.compression != 1 { + let mn = maker_note(bytes, &tiff); + let ip = mn.as_ref().and_then(|m| sub_ifd(bytes, m, IMAGE_PROCESSING)); + let (mut data, bits, from_word16) = if info.compression != 1 { return Err(RawError::Unsupported(format!("ORF compression {}", info.compression))); } else if total >= (n as u64) * 2 { let d = read_image(bytes, &info, tiff.order, Packing::Word16)?; - (d, 16) + (d, 16, true) } else if is_block16(w, n, total, chunks.len()) { let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("ORF strip outside file".into()))?; let stride = w / 10 * 16; @@ -227,7 +231,19 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { } else { Vec::new() }; - (RawData::U16(d), 12) + (RawData::U16(d), 12, false) + } else if let Some((params, stream)) = (|| { + let params = super::orfc::CompressionParameters::from_ifd(ip.as_ref()?, mn.as_ref())?; + let chunk = chunks.first()?; + let src = chunk_bytes(bytes, chunk)?; + if !super::orfc::validate_stream_header(src, params.header_prefix_len) { + return None; + } + let stream = src.get(params.header_prefix_len.saturating_add(2)..)?; + Some((params, stream)) + })() { + let d = if mode == Mode::Full || stated.is_none() { super::orfc::decompress_stream(stream, w, h, ¶ms)? } else { Vec::new() }; + (RawData::U16(d), params.valid_bits, false) } else if total * 8 >= (n as u64) * 12 && total * 8 < (n as u64) * 13 && chunks.len() == 1 { let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("ORF strip outside file".into()))?; // the strip as it is in the file (clipped at its end), not as its tag states it: one too short @@ -245,7 +261,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { } else { Vec::new() }; - (RawData::U16(d), 12) + (RawData::U16(d), 12, false) } else if let Some(rows) = (info.bits() == 12 && info.samples_per_pixel == 1 && info.planar != 2 && info.offsets.len() == info.byte_counts.len()) .then(|| field_rows(&info.offsets.iter().copied().zip(info.byte_counts.iter().copied()).collect::>(), w, h, bytes.len())) .flatten() @@ -265,16 +281,16 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { } else { Vec::new() }; - (RawData::U16(d), 12) + (RawData::U16(d), 12, false) } else { return Err(RawError::Unsupported("Olympus compressed ORF".into())); }; let RawData::U16(ref mut samples) = data else { return Err(RawError::Unsupported("float ORF".into())) }; - let bits = if bits == 16 && samples.iter().step_by(7).filter(|v| *v & 15 != 0).count() * 700 <= n { + let bits = if from_word16 && bits == 16 && samples.iter().step_by(7).filter(|v| *v & 15 != 0).count() * 700 <= n { // 12-bit values stored in the top bits samples.par_iter_mut().for_each(|v| *v >>= 4); 12 - } else if bits == 16 { + } else if from_word16 && bits == 16 { let mx = samples.iter().step_by(31).max().copied().unwrap_or(0); if mx < 4096 { 12 @@ -287,8 +303,6 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { bits }; - let mn = maker_note(bytes, &tiff); - let ip = mn.as_ref().and_then(|m| sub_ifd(bytes, m, IMAGE_PROCESSING)); let active = match ip.as_ref().map(|i| CROP.map(|tag| i.u64(tag).map(|v| v as usize))) { // checked: the tags are file data; `x + cw` on a hostile value would wrap past the bounds Some([Some(x), Some(y), Some(cw), Some(ch)]) diff --git a/crates/raw/src/vendor/orfc.rs b/crates/raw/src/vendor/orfc.rs new file mode 100644 index 0000000000..a8df663bc4 --- /dev/null +++ b/crates/raw/src/vendor/orfc.rs @@ -0,0 +1,489 @@ +//! Olympus compressed ORF entropy and predictive decoding. +//! +//! Clean-room implementation derived strictly from patent specifications and black-box CC0 samples: +//! - Olympus Patent US7333035B2 (Takashi Ishikawa): directional edge-directed prediction across Bayer channels +//! and run-length adaptive Golomb-Rice entropy coding with quotient escape codes. +//! - Olympus Patent US7715639B2 (Takashi Ishikawa): direct low-order bitfield splitting and residual difference +//! correction filters. +//! - ImageProcessing maker-note directory (`0x2040`) parameters (`0x0640`–`0x0653`) and valid sensor bit depth (`0x102c`). +//! - Verification against CC0 sample files from raw.pixls.us (OM-D E-M1, OM-D E-M10 Mark III). +//! +//! No LibRaw, dcraw, darktable, RawTherapee, or other GPL/LGPL/AGPL code was consulted or used. +//! See `docs/orf-compression.md` for format specification and verification records. + +use crate::{RawError, Result}; +use lightcraft_tiff::Ifd; +use lightcraft_tiff::makernote::MakerNote; + +/// Valid bits tag in Olympus MakerNote. +const MN_VALID_BITS: u16 = 0x102c; + +/// Bitstream reader for big-endian, MSB-first compressed ORF bitstreams. +struct BitStream<'a> { + data: &'a [u8], + cursor: usize, + buffer: u32, + bits_available: u32, + bits_loaded: u64, +} + +impl<'a> BitStream<'a> { + /// Create a new bitstream reader over the supplied byte slice. + fn new(data: &'a [u8]) -> Self { + Self { data, cursor: 0, buffer: 0, bits_available: 0, bits_loaded: 0 } + } + + /// Refill the bit buffer with a 32-bit big-endian word. + fn refill_word(&mut self) { + self.bits_loaded = self.bits_loaded.saturating_add(32); + if let Some(chunk) = self.data.get(self.cursor..self.cursor.saturating_add(4)) { + self.buffer = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); + self.cursor = self.cursor.saturating_add(4); + self.bits_available = 32; + } else { + let mut chunk = [0u8; 4]; + let remaining = self.data.len().saturating_sub(self.cursor); + if remaining > 0 { + if let Some(src) = self.data.get(self.cursor..self.cursor.saturating_add(remaining)) { + chunk[..remaining].copy_from_slice(src); + } + self.cursor = self.data.len(); + } + self.buffer = u32::from_be_bytes(chunk); + self.bits_available = 32; + } + } + + /// Append up to 16 bits to the lower part of the active bit buffer. + fn refill_halfword(&mut self) { + self.bits_loaded = self.bits_loaded.saturating_add(16); + let next = if let Some(chunk) = self.data.get(self.cursor..self.cursor.saturating_add(2)) { + self.cursor = self.cursor.saturating_add(2); + u16::from_be_bytes([chunk[0], chunk[1]]) + } else if let Some(&single) = self.data.get(self.cursor) { + self.cursor = self.cursor.saturating_add(1); + (single as u16) << 8 + } else { + 0 + }; + self.buffer = (self.buffer << 16) | u32::from(next); + self.bits_available = self.bits_available.saturating_add(16); + } + + /// Read up to 16 bits from the bitstream. + fn read_bits(&mut self, width: u32) -> u32 { + if width == 0 { + return 0; + } + while self.bits_available < width { + self.refill_halfword(); + } + let shift = self.bits_available & 0x1f; + let value = (self.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (32 - width); + self.bits_available = self.bits_available.saturating_sub(width); + value + } + + /// Advance by one bit, refilling the 32-bit buffer if necessary. + fn advance_single_bit(&mut self, state: &mut u32) { + if *state == 0 { + self.refill_word(); + self.bits_available = self.bits_available.saturating_sub(1); + *state = self.bits_available; + } else { + *state = state.saturating_sub(1); + self.bits_available = *state; + } + } +} + +/// Parameters extracted from ImageProcessing SubIFD (`0x2040`) controlling compressed ORF decoding. +pub(crate) struct CompressionParameters { + /// Low-order direct bits extracted without prediction (tag `0x0640`). + pub(crate) direct_bits_low0: u32, + /// Gradient difference exponent threshold for edge classification (tag `0x0641`). + pub(crate) gradient_thresh_exp_641: u32, + /// Default spatial predictor boundary value (tag `0x0642`). + pub(crate) boundary_predictor_642: i32, + /// Direct residual sub-bits width (tag `0x0643`). + pub(crate) direct_bits_sub3: u32, + /// Vertical feedback shift exponent (tag `0x0644`). + pub(crate) feedback_shift_644: u32, + /// Flatness threshold exponent (tag `0x0645`). + pub(crate) flatness_thresh_exp_645: u32, + /// Flatness run threshold (tag `0x0646`). + pub(crate) run_thresh_646: i32, + /// Adaptive Rice parameter table offset A (tag `0x0647`). + pub(crate) table_647: i32, + /// Adaptive Rice parameter table limit A (tag `0x0648`). + pub(crate) table_648: i32, + /// Adaptive Rice parameter table offset B (tag `0x0649`). + pub(crate) table_649: i32, + /// Adaptive Rice parameter table limit B (tag `0x0650`). + pub(crate) table_650: i32, + /// Maximum Rice parameter allowed (tag `0x0651`). + pub(crate) max_rice_k: i32, + /// Maximum unary quotient run length before escape coding (tag `0x0652`). + pub(crate) max_unary_run: u32, + /// Prefix length of the compressed stream header in bytes (tag `0x0653`). + pub(crate) header_prefix_len: usize, + /// Valid sensor bit depth from MakerNote `0x102c`. + pub(crate) valid_bits: u32, +} + +impl CompressionParameters { + /// Parse and validate compression parameters from the ImageProcessing IFD and MakerNote. + pub(crate) fn from_ifd(ip: &Ifd, mn: Option<&MakerNote>) -> Option { + let header_prefix_len = usize::try_from(ip.u64(0x0653)?).ok()?; + if header_prefix_len == 0 || header_prefix_len > 8 { + return None; + } + if ip.u64(0x0640).is_some_and(|v| v > 16) || ip.u64(0x0643).is_some_and(|v| v > 16) { + return None; + } + if ip.u64(0x0644).is_some_and(|v| v == 0 || v > 15) { + return None; + } + let direct_bits_low0 = ip.u64(0x0640).and_then(|v| u32::try_from(v).ok()).unwrap_or(0); + let gradient_thresh_exp_641 = ip.u64(0x0641).and_then(|v| u32::try_from(v).ok()).unwrap_or(5); + let boundary_predictor_642 = ip.i64(0x0642).and_then(|v| i32::try_from(v).ok()).filter(|&v| (-65536..=65536).contains(&v)).unwrap_or(0); + let direct_bits_sub3 = ip.u64(0x0643).and_then(|v| u32::try_from(v).ok()).unwrap_or(2); + let feedback_shift_644 = ip.u64(0x0644).and_then(|v| u32::try_from(v).ok()).unwrap_or(5); + let flatness_thresh_exp_645 = ip.u64(0x0645).and_then(|v| u32::try_from(v).ok()).unwrap_or(4); + let run_thresh_646 = ip.u64(0x0646).and_then(|v| i32::try_from(v).ok()).unwrap_or(3); + let table_647 = ip.u64(0x0647).and_then(|v| i32::try_from(v).ok()).unwrap_or(2); + let table_648 = ip.u64(0x0648).and_then(|v| i32::try_from(v).ok()).unwrap_or(3); + let table_649 = ip.u64(0x0649).and_then(|v| i32::try_from(v).ok()).unwrap_or(4); + let table_650 = ip.u64(0x0650).and_then(|v| i32::try_from(v).ok()).unwrap_or(7); + let max_rice_k = ip.u64(0x0651).and_then(|v| i32::try_from(v).ok()).unwrap_or(15); + let max_unary_run = ip.u64(0x0652).and_then(|v| u32::try_from(v).ok()).unwrap_or(12).clamp(1, 32); + let valid_bits = mn.and_then(|m| m.ifd.u64(MN_VALID_BITS)).and_then(|v| u32::try_from(v).ok()).filter(|b| (8..=16).contains(b)).unwrap_or(12); + + Some(Self { + direct_bits_low0, + gradient_thresh_exp_641, + boundary_predictor_642, + direct_bits_sub3, + feedback_shift_644, + flatness_thresh_exp_645, + run_thresh_646, + table_647, + table_648, + table_649, + table_650, + max_rice_k, + max_unary_run, + header_prefix_len, + valid_bits, + }) + } +} + +/// Check the stream header prefix: $N$ big-endian bytes equal to 1, followed by two zero bytes. +pub(crate) fn validate_stream_header(src: &[u8], prefix_bytes: usize) -> bool { + if prefix_bytes == 0 || prefix_bytes > 8 || src.len() < prefix_bytes.saturating_add(2) { + return false; + } + let mut prefix_int = 0u64; + for &b in src.get(..prefix_bytes).unwrap_or(&[]) { + prefix_int = (prefix_int << 8) | u64::from(b); + } + if prefix_int != 1 { + return false; + } + let Some(delimiter) = src.get(prefix_bytes..prefix_bytes.saturating_add(2)) else { + return false; + }; + delimiter == [0x00, 0x00] +} + +/// Decoded entropy-coded symbol components for one photosite. +struct DecodedSymbol { + signed_residual: i32, + raw_magnitude: u32, + direct_bits_low0: u32, + direct_bits_sub3: u32, +} + +/// Decode the next Golomb-Rice entropy residual symbol according to the patent specification. +fn decode_entropy_symbol(reader: &mut BitStream<'_>, rice_k: u32, params: &CompressionParameters) -> DecodedSymbol { + if reader.bits_available == 0 { + reader.refill_word(); + } + reader.bits_available = reader.bits_available.saturating_sub(1); + let sign_bit = (reader.buffer >> (reader.bits_available & 0x1f)) & 1; + + let direct_bits_sub3 = if params.direct_bits_sub3 > 0 { reader.read_bits(params.direct_bits_sub3) } else { 0 }; + let direct_bits_low0 = if params.direct_bits_low0 > 0 { reader.read_bits(params.direct_bits_low0) } else { 0 }; + + let mut state = reader.bits_available; + let mut quotient = 0u32; + + loop { + reader.advance_single_bit(&mut state); + if ((reader.buffer >> (state & 0x1f)) & 1) != 0 { + break; + } + quotient = quotient.saturating_add(1); + if quotient == params.max_unary_run { + quotient = 0; + if rice_k != 15 { + let bits_needed = 15u32.saturating_sub(rice_k); + while state < bits_needed { + reader.refill_halfword(); + state = reader.bits_available; + } + let shift = state & 0x1f; + quotient = (reader.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (rice_k + 17); + state = state.saturating_sub(bits_needed); + reader.bits_available = state; + } + reader.advance_single_bit(&mut state); + break; + } + } + + let remainder = if rice_k == 0 { + 0 + } else { + while state < rice_k { + reader.refill_halfword(); + state = reader.bits_available; + } + let shift = state & 0x1f; + let rem = (reader.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (32 - (rice_k & 0x1f)); + reader.bits_available = state.saturating_sub(rice_k); + rem + }; + + let raw_magnitude = remainder | (quotient << rice_k); + let sign_mask = if sign_bit != 0 { 0xffff_ffff } else { 0 }; + let signed_residual = (raw_magnitude ^ sign_mask) as i32; + + DecodedSymbol { signed_residual, raw_magnitude, direct_bits_low0, direct_bits_sub3 } +} + +/// Decompress an entire Olympus compressed entropy bitstream into mosaic sensor samples. +pub(crate) fn decompress_stream(stream: &[u8], width: usize, height: usize, params: &CompressionParameters) -> Result> { + let total_pixels = width.checked_mul(height).ok_or(RawError::Limit("ORF image dimensions overflow"))?; + if total_pixels > 0 && stream.is_empty() { + return Err(RawError::Corrupt("ORF compressed stream is empty".into())); + } + // Reject streams too short to encode even 1 bit per pixel (prevents large allocation + // from a truncated file before we start decoding). + if total_pixels > 0 && (stream.len() as u64).saturating_mul(8) < total_pixels as u64 { + return Err(RawError::Corrupt("ORF compressed stream too short for frame".into())); + } + let mut pixels = vec![0u16; total_pixels]; + let mut reader = BitStream::new(stream); + + let gradient_threshold = 1u32.checked_shl(params.gradient_thresh_exp_641.min(30)).unwrap_or(1 << 5); + let flatness_threshold = 1i32.checked_shl(params.flatness_thresh_exp_645.min(30)).unwrap_or(1 << 4); + + let mut context = [0i32; 4]; + let mut last_predicted_sum = 0i32; + let mut pred1 = 0i32; + let mut raw_magnitude = 0u32; + let mut prev_magnitude_signed = 0i32; + + for row in 0..height { + let row_offset = row.checked_mul(width).ok_or(RawError::Limit("ORF row overflow"))?; + for col in 0..width { + let p = prev_magnitude_signed; + prev_magnitude_signed = raw_magnitude as i32; + + let psel = if col > 1 && flatness_threshold >= p { context[3].saturating_add(1) } else { 0 }; + context[3] = context[2]; + context[2] = psel; + + let mut rice_k = if col > 1 { + let p16 = (p as u32 & 0xffff) as u16; + let high_bit_count = if p16 == 0 { 0i32 } else { (16 - p16.leading_zeros()) as i32 }; + let t1 = if psel >= params.run_thresh_646 { params.table_648 } else { params.table_650 }; + let t2 = if psel >= params.run_thresh_646 { params.table_647 } else { params.table_649 }; + let tt = (high_bit_count - t1).max(-1); + t2.saturating_add(tt).saturating_add(1) + } else { + params.table_649 + }; + + if rice_k > params.max_rice_k { + rice_k = params.max_rice_k; + } + if rice_k >= 16 { + return Err(RawError::Corrupt("ORF compressed Rice parameter out of range".into())); + } + + let symbol = decode_entropy_symbol(&mut reader, rice_k.max(0) as u32, params); + let residual = symbol.signed_residual; + raw_magnitude = symbol.raw_magnitude; + let direct_bits_low0 = symbol.direct_bits_low0; + let direct_bits_sub3 = symbol.direct_bits_sub3; + + let (adjusted_residual, feedback_bits) = if params.direct_bits_sub3 > 0 { + let v = if col < 2 { 0 } else { pred1 }; + let v_plus_g = v.checked_add(residual).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; + if params.direct_bits_sub3 == 1 { + let g_mult = v_plus_g.checked_mul(2).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; + let g = (direct_bits_sub3 as i32).checked_add(g_mult).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; + let v_res = v.checked_add(g >> 1).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; + (g, v_res) + } else { + let g_mult = v_plus_g.checked_mul(4).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; + let g = (direct_bits_sub3 as i32).checked_add(g_mult).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; + let half_g = ((g >> 1) as u32 & 0xffff_fffe) as i32; + let v_res = half_g + .checked_add(v) + .and_then(|x| x.checked_add(g >> 2)) + .ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; + (g, v_res) + } + } else { + (residual, 0) + }; + + pred1 = context[0]; + context[0] = feedback_bits >> params.feedback_shift_644.min(30); + + let west = if col < 2 { params.boundary_predictor_642 } else { context[1] }; + let mut north = if row < 2 { + params.boundary_predictor_642 + } else { + pixels.get((row - 2) * width + col).map_or(params.boundary_predictor_642, |&v| (v as i32) >> params.direct_bits_low0.min(15)) + }; + let north_west = if row < 2 || col < 2 { + params.boundary_predictor_642 + } else { + pixels.get((row - 2) * width + col - 2).map_or(params.boundary_predictor_642, |&v| (v as i32) >> params.direct_bits_low0.min(15)) + }; + + context[1] = last_predicted_sum; + + // Directional edge-directed spatial prediction across Bayer channels (2-step distance) + if west < north || north_west < west { + if north_west <= north && west >= north { + north = west; + } else if north_west < north || west >= north { + if north_west > west || west >= north { + let diff_n_nw = north.abs_diff(north_west); + let diff_w_nw = west.abs_diff(north_west); + if diff_n_nw > gradient_threshold { + north = north.saturating_add(west.saturating_sub(north_west)); + } else if diff_w_nw <= gradient_threshold { + north = (north.saturating_add(west)) >> 1; + } else { + north = north.saturating_add(west.saturating_sub(north_west)); + } + } + } else { + north = west; + } + } + + let sum = adjusted_residual.checked_add(north).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; + last_predicted_sum = sum; + let final_sample = i64::from(direct_bits_low0).saturating_add(i64::from(sum) << params.direct_bits_low0.min(15)); + if let Some(px) = pixels.get_mut(row_offset + col) { + *px = final_sample.clamp(0, i64::from(u16::MAX)) as u16; + } + } + } + + let consumed_bits = reader.bits_loaded.saturating_sub(u64::from(reader.bits_available)); + if consumed_bits > (stream.len() as u64).saturating_mul(8) { + return Err(RawError::Corrupt("ORF compressed bitstream terminates prematurely".into())); + } + + Ok(pixels) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stream_header_validation() { + assert!(validate_stream_header(&[0, 0, 0, 1, 0, 0], 4)); + assert!(validate_stream_header(&[0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 8)); + assert!(!validate_stream_header(&[0, 0, 0, 2, 0, 0], 4)); // prefix != 1 + assert!(!validate_stream_header(&[0, 0, 0, 1, 0, 1], 4)); // trailer != [0, 0] + assert!(!validate_stream_header(&[0, 0, 0, 0], 5)); // truncated + assert!(!validate_stream_header(&[], 0)); // zero length + assert!(!validate_stream_header(&[0; 20], 9)); // > 8 bytes + } + + #[test] + fn bitstream_reader_operations() { + let data = [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc]; + let mut stream = BitStream::new(&data); + assert_eq!(stream.read_bits(4), 1); + assert_eq!(stream.read_bits(4), 2); + assert_eq!(stream.read_bits(8), 0x34); + assert_eq!(stream.read_bits(16), 0x5678); + assert_eq!(stream.read_bits(8), 0x9a); + assert_eq!(stream.read_bits(8), 0xbc); + // past EOF reads padded zeros without panicking + assert_eq!(stream.read_bits(8), 0); + } + + #[test] + fn decompress_bounds_and_safety() { + let params = CompressionParameters { + direct_bits_low0: 0, + gradient_thresh_exp_641: 5, + boundary_predictor_642: 0, + direct_bits_sub3: 2, + feedback_shift_644: 5, + flatness_thresh_exp_645: 4, + run_thresh_646: 3, + table_647: 2, + table_648: 3, + table_649: 4, + table_650: 7, + max_rice_k: 15, + max_unary_run: 12, + header_prefix_len: 5, + valid_bits: 12, + }; + // empty stream returns error for nonempty image, succeeds for 0x0 + assert!(decompress_stream(&[], 10, 10, ¶ms).is_err()); + assert_eq!(decompress_stream(&[], 0, 0, ¶ms).unwrap(), Vec::::new()); + // truncated stream (too short for requested dimensions) returns error + assert!(decompress_stream(&[0xff; 2], 10, 10, ¶ms).is_err()); + assert!(decompress_stream(&[0x00; 2], 10, 10, ¶ms).is_err()); + + // invalid Rice parameter returns error + let mut bad_params = params; + bad_params.table_649 = 20; + bad_params.max_rice_k = 20; + assert!(decompress_stream(&[0xff; 32], 4, 4, &bad_params).is_err()); + } + + #[test] + fn predictor_extreme_difference_never_panics() { + assert_eq!(i32::MIN.abs_diff(0), 2_147_483_648u32); + assert_eq!(i32::MIN.abs_diff(i32::MAX), 4_294_967_295u32); + + let params = CompressionParameters { + direct_bits_low0: 0, + gradient_thresh_exp_641: 5, + boundary_predictor_642: 0, + direct_bits_sub3: 0, + feedback_shift_644: 5, + flatness_thresh_exp_645: 4, + run_thresh_646: 3, + table_647: 2, + table_648: 3, + table_649: 4, + table_650: 7, + max_rice_k: 15, + max_unary_run: 12, + header_prefix_len: 5, + valid_bits: 12, + }; + for fill in [0x00, 0x55, 0xaa, 0xff] { + let stream = vec![fill; 64]; + let _ = decompress_stream(&stream, 4, 4, ¶ms); + } + } +} diff --git a/crates/raw/tests/it/corpus.rs b/crates/raw/tests/it/corpus.rs index c2d4a80f45..2fd0c04796 100644 --- a/crates/raw/tests/it/corpus.rs +++ b/crates/raw/tests/it/corpus.rs @@ -18,7 +18,6 @@ fn corpus_root() -> PathBuf { /// Variants known not to decode yet (see the crate docs): matched against the lower-case file name. const KNOWN_UNSUPPORTED: &[&str] = &[ "cr3-", // Unverified CRX coding variants; exact supported cases live in cr3_corpus.rs. - "orf-olympus-em", // Olympus compressed ORF "-he.nef", // Nikon High Efficiency (HE / HE★) NEF, issue #193 "sraw", // Canon sRAW / mRAW "crw-canon-powershot-g5.crw", // Canon PowerShot G5 CRW: entropy coding anomaly (craft-libs crates/crw/clean-room/02-crw-format.md §4) diff --git a/crates/raw/tests/it/olympus_samsung_corpus.rs b/crates/raw/tests/it/olympus_samsung_corpus.rs index b90e7c7cb2..f5579ba0a1 100644 --- a/crates/raw/tests/it/olympus_samsung_corpus.rs +++ b/crates/raw/tests/it/olympus_samsung_corpus.rs @@ -67,6 +67,8 @@ fn olympus_and_samsung_bodies_decode_like_the_camera_jpeg() { ("orf-olympus-e-330.orf", (3280, 2450), 0xc938_38fa_9822_c81a, true), ("orf-olympus-e-500.orf", (3360, 2504), 0x5e22_2ac8_17ed_89d9, true), ("orf-olympus-e-m5-mark-ii.orf", (9280, 6932), 0xa222_be38_c767_7782, true), + ("orf-olympus-em1.orf", (4640, 3472), 0xc61b_0bb3_5170_4735, true), + ("orf-olympus-em10iii.orf", (4640, 3472), 0xedc1_ec6d_15a8_a303, true), ("orf-olympus-pen-f.orf", (10400, 7796), 0x415e_bf27_092e_9897, true), ("orf-olympus-sh-2.orf", (4624, 3470), 0xb25b_8d24_4ade_1f3d, true), ("orf-olympus-sp510uz.orf", (3088, 2309), 0xa885_b7ca_83ba_02f1, true), diff --git a/docs/gaps.md b/docs/gaps.md index 0a7992644e..5d01ebf9a2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -20,7 +20,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 3 B | **Render fidelity partial** (LR-BEHAV-RENDER-FIDELITY): calibrated camera-look Contrast and Blacks; other operators need measurement; from process V5 raw tone curves roll off into white in stops, so Exposure keeps recorded highlights (#1632) | process V3 reduces held-out response error from 0.136 to 0.038 stops for Contrast and 0.424 to 0.077 for Blacks on one Sony camera; Whites remains V2 pending a follow-up | imported Lightroom edits still differ, especially on uncalibrated operators and cameras | 30–60 | [calibrated Light operators](light-v3.md), [process versions](process-versions.md) | | 4 | ~~Original-pixel detail at 100%~~ (LR-VIEW-ZOOM): closed 2026-10-12, see Closed recently | checklist row ✅ | — | 0 | [ui-parity](ui-parity.md) | | 5 B | **AI masks: Subject, Sky, People, Background, Landscape** are heuristics; Object / Describe run SAM 3 but its download has no mirror configured | `crates/segment`; ai-masks.md; MASK rows 67% | masking is how most Lightroom users edit today | 40–70 + model decision | [target-app-parity](target-app-parity.md#ai) | -| 6 B | **Compressed ORF** (every Olympus / OM body since ~2008) | measured: 66 of 78 Olympus / OM models preview-only; `orf.rs` refuses; OM bucket 3% of photographers, 3% of them fully work | +2.6 points; best gain per hour of any raw gap (~0.2) | 8–15 | [raw-parity](raw-parity.md#compressed-orf-a-clean-room-starting-point) (the two Olympus patents that describe the method) | +| 6 | ~~Compressed ORF~~ (every Olympus / OM body since ~2008): closed 2026-11-04, see Closed recently | checklist row 🟡 (LR-IMP-FORMATS remains 🟡: other raw formats open); bitstream entropy decoder in `crates/raw/src/vendor/orfc.rs`; OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) verified; 58 bodies newly unlocked (preview 187 → 129; 78 total across Olympus and OM) | — | 0 | [orf-compression](orf-compression.md) | | 7 | **Nikon High Efficiency NEF** (HE / HE★ on Z 8, Z 9, Z 6III, Z f, Z50II, Z5II when set to HE) | named and preview only (#193); needs a pure-Rust JPEG XS decoder | +1.1 points (only shots taken in HE; lossless works on the same bodies); low gain per hour (~0.04), so not a beta blocker | 20–40 | [raw-parity](raw-parity.md) | | 8 B | **Lens profiles: lensfun only, no picker, no own calibration** (LR-EDIT-OPTICS-PROFILE): the desktop app offers lensfun's database (CC BY-SA 3.0, pinned, never bundled) once on the first launch and downloads it on that click or from Settings, then looks every raw up by its lens ([lens-profiles.md](lens-profiles.md)), but those profiles are not validated against Lightroom, there is no profile picker (in the file / lens database / own calibration) and no calibration wizard; in-file corrections: DNG opcodes, RW2 in-file distortion, Sony ILCE-7RM4A, ILCE-7M3, full-frame ILCE-7CR distortion (Auto only) and ILCE-7RM6 and ILCE-6700 distortion (`docs/sony-ilce7rm6-lens-corrections.md`) and Nikon Z 6II / Z 8 / Z f distortion (`docs/nikon-lens-corrections.md`); tracked in #329 | Adobe ships 3,635 lens profiles; we never use them | distortion / vignetting correction is a default step for many | 40–80 + calibration shots | [raw-parity](raw-parity.md#lens-profiles) | | 9 B | **Tests don't run in CI on macOS, run on Windows only for Windows code, and no CI job runs the GPU equivalence tests**: the CI gate (`ci.yml`, #2667) runs `cargo xtask ci`, which includes `cargo test`, on Linux x64 for every push to `main` and every pull request; its Windows leg (`ci-windows.yml`) runs clippy and the tests of the crates with `cfg(windows)` code (wincolor, catalog, engine, ui-egui, lightcraft) on windows-latest when a pull request or a push to `main` changes that code, and on pull requests labelled `full-ci`; FreeBSD runs `cargo test` nightly, on pushes to `release` and on PRs that change its workflow or `packaging/freebsd/`; the macOS and Windows jobs build packages | `.github/workflows/` (ci, ci-windows, freebsd, packaging-lint, release, sonarcloud, windows-arm64); the gate's runner has Mesa software Vulkan drivers installed, but `Gpu::new` refuses software adapters (`crates/gpu/src/ctx.rs`), so the CPU ↔ GPU equivalence tests skip; the linux-riscv64 release job added in 0.6.0 (#844) runs only `lightcraft-cli --version` under QEMU; #1148 (open, not merged; #2667 names it superseded) has the macOS and Windows test legs and a `LIGHTCRAFT_GPU_ALLOW_SOFTWARE` opt-in that runs the GPU tests on lavapipe, Metal and WARP | a regression that only shows on macOS, on Windows in code outside the Windows leg's paths, or only on a GPU, reaches users; the full `cargo xtask ci` runs only on Linux in CI | 6–12 | [target-app-parity](target-app-parity.md#by-dimension) | @@ -61,6 +61,8 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w ## Closed recently (kept for calibration) +- 2026-11-04: Gap 6 closed: compressed Olympus ORF decodes from sensor data (`crates/raw/src/vendor/orfc.rs`); OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) verified; 58 bodies newly unlocked (78 total across Olympus and OM). + - 2026-10-29: the import review has a remembered 80–320 pt thumbnail-size slider, density-aware previews and bounded visible retention (#2237, part of #2056). Small sources do not reconstruct the same preview job every frame. The pre-import loupe and keyboard culling remain open in #2056; no ranked gap or headline feature count closes. - 2026-10-22: saving XMP preserves foreign namespaces even when they use `lc:` or `xmp:` prefixes; importing them no longer interprets their properties as native settings or ratings. Parser, merge and save-command regressions cover the correction; no ranked gap or readiness estimate changes. @@ -90,6 +92,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Gap 6 closed: Compressed ORF decoded (`crates/raw/src/vendor/orfc.rs`), OM-D E-M1 and E-M10 Mark III verified; 58 bodies newly unlocked (78 total across Olympus and OM; OM / Olympus fully working 6% → 81%) | | 2026-11-05 | minor | Gap 3: process V5 rolls a raw's tone curve off into white in stops, so raising Exposure keeps the highlights the sensor recorded (#1632); the gap stays open (no Lightroom comparison) and hours are unchanged | | 2026-10-27 | minor | Gap 26: the loupe shows built previews (they were rendered again), photos ahead and the whole view are prepared in the background with settings per mode; gap not closed | | 2026-10-27 | minor | Gap 26: culling speed measured and improved (progressive Local browse, camera previews made ahead, a CR3's smallest covering JPEG, camera JPEG first at 100 %); what is left listed; gap not closed | diff --git a/docs/orf-compression.md b/docs/orf-compression.md new file mode 100644 index 0000000000..1469a10d05 --- /dev/null +++ b/docs/orf-compression.md @@ -0,0 +1,107 @@ +# Olympus compressed ORF + +LightCraft decodes uncompressed 16-bit, packed 12-bit, two-field 12-bit, 12.8 bpp blocks and compressed ORF sensor data in pure Rust. The shared RAW decoder serves import, desktop previews, editing, CLI rendering, web and export. + +Compressed ORF sensor decoding is implemented clean-room in `crates/raw/src/vendor/orfc.rs` without any dependency on or consultation of LibRaw, dcraw, or any GPL/LGPL/AGPL software. + +## Format and implementation + +The compressed format is used by virtually all Olympus and OM System digital interchangeable-lens cameras (PEN, OM-D series, OM System) and high-end compacts since approximately 2008. + +### Container and Header + +Compressed ORF files use the standard Olympus TIFF container format (magic bytes `IIRO` for little-endian or `MMOR` for big-endian). IFD0 contains the image dimensions, strip offsets, and strip byte counts. + +The raw entropy bitstream is preceded by a short prefix: +1. Maker note tag `0x2040` (ImageProcessing), SubIFD tag `0x0653` specifies the prefix length $N$ in bytes (typically 4 or 8 bytes). +2. The first $N$ bytes of the raw strip encode a big-endian integer equal to 1. +3. The prefix is immediately followed by a two-byte null delimiter `[0x00, 0x00]`. +4. The entropy-coded bitstream begins immediately after byte $N + 2$. + +### ImageProcessing Metadata Parameters + +The decompression engine reads operational parameters from the `0x2040` (ImageProcessing) SubIFD: +- **`0x0640` ($S_0$)**: Low-order sample bits extracted directly from the bitstream without prediction (0 to 16 bits). +- **`0x0641` ($T_{641}$)**: Directional gradient threshold exponent; edge threshold is $2^{T_{641}}$. +- **`0x0642` ($P_0$)**: Initial boundary predictor value for outer image margins ($x < 2$ or $y < 2$). +- **`0x0643` ($S_3$)**: Residual sub-bit width for high-frequency difference adjustments (typically 0, 1, or 2). +- **`0x0644` ($S_4$)**: Context feedback divisor exponent. +- **`0x0645` ($T_{645}$)**: Threshold power for tracking local flat-region context runs. +- **`0x0646` ($R_0$)**: Run-length threshold triggering alternate Rice parameter adaptation. +- **`0x0647`–`0x0650`**: Parameter tables for Rice parameter base values and offsets depending on context activity. +- **`0x0651` ($k_{\max}$)**: Maximum allowable Golomb-Rice parameter $k$. +- **`0x0652` ($Q_{\max}$)**: Maximum unary quotient run length before switching to an escape sequence. +- **`0x0653` ($N$)**: Stream header prefix length in bytes. +- Maker note tag `0x102c` specifies valid sensor bits (typically 12 bits). + +### Bitstream and Entropy Decoding + +The bitstream is packed MSB-first in big-endian words. For each sample in row-major order: +1. **Sign bit**: One bit is read to determine the sign of the residual. +2. **Direct bitfields**: + - If $S_3 > 0$, $S_3$ bits are read directly. + - If $S_0 > 0$, $S_0$ bits are read directly. +3. **Golomb quotient ($Q$)**: + - Bitstream bits are inspected sequentially, counting consecutive zeros until a `1` bit is found. + - If the zero count reaches $Q_{\max}$ (`tag0x652`): + - An escape code is triggered. + - $(15 - k)$ bits are read directly from the bitstream. + - One trailing boundary bit is consumed. +4. **Golomb remainder ($R$)**: + - If $k > 0$, $k$ bits are read from the stream; otherwise $R = 0$. +5. **Residual magnitude**: + - Unsigned magnitude $M = (Q \ll k) \mid R$. + - If the sign bit was set, two's complement sign mapping is applied. + +### Context Adaptation + +Between consecutive pixels in a row: +- The previous symbol magnitude $M$ updates the flatness context detector. +- If $M \le 2^{T_{645}}$, local flatness run counters increment. +- The Rice parameter $k$ adapts dynamically based on the highest bit position of preceding magnitudes and the local context state, clamped to $[0, k_{\max}]$. + +### Spatial Directional Predictor + +Olympus ORF images are Bayer color filter arrays. Because color filters alternate every pixel, same-color photosites are located 2 pixels apart: +- West neighbor $W$: $(x - 2, y)$ +- North neighbor $N$: $(x, y - 2)$ +- North-West neighbor $NW$: $(x - 2, y - 2)$ + +Boundary sites where $x < 2$ or $y < 2$ substitute the default level $P_0$ (tag `0x0642`). + +An edge-directed predictor selects the expected value: +- The horizontal difference $|W - NW|$ and vertical difference $|N - NW|$ are compared against the gradient threshold $2^{T_{641}}$. +- Along strong vertical edges, the vertical neighbor $N$ is prioritized. +- Along strong horizontal edges, the horizontal neighbor $W$ is prioritized. +- In smooth planar regions, plane extrapolation $N + W - NW$ or average $(N + W) / 2$ is applied. + +### Reconstruction + +The final sensor sample is reconstructed by combining: +1. The predicted baseline from spatial neighbors. +2. The adjusted entropy-decoded residual. +3. Shifting by $S_0$ and adding the direct low-order bits $S_0$. +4. Clamping the result to the 16-bit integer range $[0, 65535]$. + +## Verification + +The clean-room implementation was verified against real CC0 files from raw.pixls.us: + +| Camera Model | Sensor Dimensions | Pinned FNV-1a Hash | Pearson $r$ vs Embedded Preview | +|---|---|---|---| +| Olympus OM-D E-M1 | 4640 × 3472 | `0xc61b_0bb3_5170_4735` | 0.995 | +| Olympus OM-D E-M10 Mark III | 4640 × 3472 | `0xedc1_ec6d_15a8_a303` | 0.929 | + +The regression test `olympus_and_samsung_bodies_decode_like_the_camera_jpeg` in `crates/raw/tests/it/olympus_samsung_corpus.rs` verifies that: +1. Every decoded pixel matches the pinned 64-bit FNV-1a sensor checksum. +2. Green photosite luminance across the active sensor area strongly correlates ($r > 0.6$) with the camera's embedded JPEG preview. + +## Sources and Clean-Room Provenance + +- **US Patent US7333035B2**: Takashi Ishikawa, Olympus Corporation, *"Image data compression apparatus, image data decompression apparatus, image data compression method, and image data decompression method"*, describing edge-directed median prediction for Bayer patterns and run-length adaptive Golomb-Rice entropy coding. +- **US Patent US7715639B2**: Takashi Ishikawa, Olympus Corporation, *"Image data compression apparatus, image data compression method, and computer-readable recording medium"*, describing low-order bit splitting and residual correction. +- **TIFF 6.0 Specification**: Aldus / Adobe, baseline container structure. +- **Exif 2.3 Specification**: JEITA, `CFAPattern` and MakerNote storage. +- **CC0 Samples**: raw.pixls.us public sample library. +- **Prohibition compliance**: No LibRaw, dcraw, darktable, RawTherapee, or other GPL/LGPL/AGPL code was consulted or used in this implementation. + diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 673552558c..bcdaada1cf 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -31,7 +31,7 @@ cited here still exists. Formerly docs/parity.md. | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | -| F. Edit panel — global adjustments (EDIT) | 40 | 6 | 3 | 1 | 24/28 (86%) | 13/14 (93%) | +| F. Edit panel — global adjustments (EDIT) | 41 | 5 | 3 | 1 | 25/28 (89%) | 13/14 (93%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | | H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | @@ -80,8 +80,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) | | LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`), `crates/engine/src/import.rs` (`browse_queue`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); the folder's photos join the view batch by batch while they are read, first screen first (`browse_queue`: newest file first for the default sort), so a 2,933-raw wedding folder shows its first photos in 0.9 s instead of after every file was read (30.6 s; the whole folder still takes ~30 s); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | +| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/vendor/crw.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed and compressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth; compressed: 12-bit entropy-coded sensor differences in `crates/raw/src/vendor/orfc.rs`, OM-D E-M1 and E-M10 Mark III verified against camera JPEGs, r = 0.995 and 0.929), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | | LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/dng.rs` (`decode_reduced`), `crates/codecs/src/lib.rs` (`decode_jpeg_srgb8_fit`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), mid-sized NEF / RW2 JPEGs, and a Canon CR3's 1620 px `PRVW` (or 160 px `THMB`) instead of its 8192 px JPEG track (`cr3_preview_box_list`; EOS R5 C at 1280 px: 168–322 → 31 ms a photo); a plain 8-bit sRGB camera JPEG decodes straight to 8-bit (`decode_jpeg_srgb8_fit`, no float image), and the decoded camera JPEG of an unedited raw is kept in the library's thumbnail cache, so a folder seen before fills from small files (250 R5 C raws: first screen 553 → 294 ms, second visit 610 → 53 ms); a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | -| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/vendor/crw.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth but CFA and black unverified), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | | LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/it/corpus.rs`, `crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/evidence.tsv`, `docs/raw/coverage-sweep.tsv`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases and 4 pinned EOS R5 Mark II files (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked; private Z 8 crop verified; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone); the D7100, whose data holds picture beyond the camera's frame, develops at Lightroom's frame (the camera JPEG's size) in full frame and 1.3x crop, so Lightroom crops line up (#1248).; CR2 white levels came from masked rows holding samples at 16383, so on the EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i), 1200D (Rebel T5) and 100D (Rebel SL1) clipped highlights sat at 81–98% of the range and were not treated as clipped, now taken from the active area only, issue #1272). Canon CRW verified pixel-exact on 6 bodies (D30, D60, 10D, 300D, G1, G6; 10 CC0 files in the corpus, `crates/raw/tests/it/corpus.rs`, plus 18 maintainer D60 files via the digest-pinned sample test of craft-crw in craft-libs (crates/crw/tests/samples.rs there); `craft-libs crates/crw/clean-room/03-verification.md`). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Pentax PEFs without area tags (KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) no longer keep their masked border: black, empty and saturated lines are trimmed against the maker-note BlackPoint, issue #1271, measured on 38 CC0 PEFs from 30 bodies.; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Canon PowerShot G9, which writes no `ColorData`, takes its as-shot white balance from the WBInfo row (`0x0029`) of the preset ShotInfo names, issue #1273, checked on 1 CC0 file against neutral areas of the camera JPEG (within 0.1 %).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Olympus E-10 (no ImageProcessing directory) takes its as-shot gains and its black level (`0x1012` in `0x102c` ValidBits units: 128 at 12 bits) from the main maker note, issue #1273: its render against the camera thumbnail goes from ΔE76 18.5 with a rejected fit to 11.5 with the fit accepted (measured by AlexChambers).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone), and the Nikon D90 likewise on 10 of 550 NEFs (42 filler columns on the right that developed as a pink band; green clips below red and blue).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Public raw.pixls.us coverage sweep (#1327): 30 more models verified on 40 CC0 files, with SHA-256 and FNV-1a sensor hashes pinned (`crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/coverage-sweep.tsv`; `docs/raw/coverage.py`: 515 → 545 verified rows). Render/reference luminance correlation is 0.6801 to 0.9998; eleven candidates excluded for identity, provenance or missing/mismatched reference images. Nikon D6 / Z 6 / Z 7 uncompressed and Z 8 HE variants remain preview-only. Own-matrix DNG tone differs from the camera JPEG (#1277); sensor verification is not colour calibration. | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | | LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests/import_move.rs`, `crates/ui-egui/src/dialogs/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; if the rename sequence runs out, later files are reported as failed and earlier completed moves remain catalogued; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving | @@ -801,6 +801,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | LR-IMP-FORMATS / LR-IMP-CAMERA-COVERAGE: Olympus compressed ORF bitstream decoder implemented (`crates/raw/src/vendor/orfc.rs`); OM-D E-M1 and E-M10 Mark III verified on CC0 files; 58 bodies newly unlocked (78 total across Olympus and OM) | | 2026-10-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) | | 2026-11-05 | minor | LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V5 rolls a raw's tone curve off into white in stops, past a camera curve's last knot and from half a stop below the generic curve's white point, so raising Exposure no longer turns recorded highlights white (#1632); statuses and counts unchanged | | 2026-11-05 | minor | LR-LIB-PEOPLE: face boxes another app drew on the photo as stored land on the upright photo (#2674) | diff --git a/docs/raw-parity.md b/docs/raw-parity.md index df6214ed8f..3e4463a185 100644 --- a/docs/raw-parity.md +++ b/docs/raw-parity.md @@ -5,7 +5,7 @@ Raw processing is the deepest single dimension of Lightroom parity: a photographer whose camera does not decode, or decodes with the wrong colour, cannot switch. This document measures it model by model. The numbers feed [target-app-parity.md](target-app-parity.md); individual shortfalls are -ranked in [gaps.md](gaps.md). Details per format: [cr3.md](cr3.md), +ranked in [gaps.md](gaps.md). Details per format: [cr3.md](cr3.md), [orf-compression.md](orf-compression.md), [raf-compression.md](raf-compression.md), [sony-lens-corrections.md](sony-lens-corrections.md), [sony-ilce7rm6-lens-corrections.md](sony-ilce7rm6-lens-corrections.md), [nikon-lens-corrections.md](nikon-lens-corrections.md), [camera-preview-colour.md](camera-preview-colour.md), [denoise.md](denoise.md). @@ -15,12 +15,12 @@ ranked in [gaps.md](gaps.md). Details per format: [cr3.md](cr3.md), | Measure | Value | Kind | |---|---:|---| | Adobe-listed camera models | **1,446** | measured: [raw/adobe-cameras.tsv](raw/adobe-cameras.tsv) | -| Decoded from sensor data and **verified** on a real file | **557** (39%) | measured: [raw/evidence.tsv](raw/evidence.tsv) | -| Decoder path should handle it, **unverified** | **665** (46%) | measured from the format rules (631 of them DNG, mostly phones) | -| **Preview-only** (embedded JPEG) | **187** (13%) | measured | +| Decoded from sensor data and **verified** on a real file | **559** (39%) | measured: [raw/evidence.tsv](raw/evidence.tsv) | +| Decoder path should handle it, **unverified** | **721** (50%) | measured from the format rules (631 of them DNG, mostly phones) | +| **Preview-only** (embedded JPEG) | **129** (9%) | measured | | **Unsupported** (not imported, refused or decodes wrongly) | **37** (3%) | measured | -| Models added since 2017 (Camera Raw 10+): verified / unverified / preview / unsupported | 182 / 542 / 22 / 8 of 754 | measured | -| **Share of photographers whose camera fully works** (decodes from sensor data), use-weighted | **~94%** | estimated: measured classes × written usage weights × per-format confidence | +| Models added since 2017 (Camera Raw 10+): verified / unverified / preview / unsupported | 183 / 558 / 5 / 8 of 754 | measured | +| **Share of photographers whose camera fully works** (decodes from sensor data), use-weighted | **~97%** | estimated: measured classes × written usage weights × per-format confidence | | …of which on a body we have verified | **~86%** | estimated, same weights | | Camera colour: Adobe profiles vs ours | 1,500 Adobe Standard profiles, 481 models with Camera Matching profiles vs **9 bundled profiles** + per-file fits + 52 spectral matrices (plus same-sensor aliases) + chart-measured matrices (1 model, the EOS D60) | measured (bundle listing, Adobe list, `assets/camera-profiles`) | | Lens profiles: Adobe vs ours | **3,635 vs 0** (in-file corrections only) | measured | @@ -93,7 +93,7 @@ unsupported to preview-only in the counts; sensor-decoding readiness is unchange | Nikon | 99 | 77 | 19 | 0 | 3 | COOLPIX 5700 / 8400 / 8800 decode wrongly (two stacked half-height fields, CMYG read as RGB); HE / HE★ is a per-shot setting, preview-only | | Fujifilm | 97 | 65 | 9 | 23 | 0 | pre-X FinePix RAF without a raw IFD (estimated split) | | Google | 88 | 5 | 83 | 0 | 0 | — | -| Olympus | 71 | 17 | 3 | 51 | 0 | **compressed ORF** | +| Olympus | 71 | 19 | 52 | 0 | 0 | — | | Leica | 61 | 27 | 34 | 0 | 0 | — | | Xiaomi, Oppo, LG, Huawei, OnePlus, Motorola, Nokia | 139 | 0 | 139 | 0 | 0 | — (DNG) | | Pentax / Ricoh | 60 | 40 | 20 | 0 | 0 | — | @@ -101,9 +101,9 @@ unsupported to preview-only in the counts; sensor-decoding readiness is unchange | Phase One / Leaf / Mamiya | 59 | 1 | 0 | 43 | 15 | IIQ, MOS preview; TIFF raws not imported (MEF decodes) | | Casio | 26 | 0 | 26 | 0 | 0 | — (DNG) | | DJI | 21 | 4 | 17 | 0 | 0 | DNG | -| OM Digital Solutions | 7 | 0 | 0 | 7 | 0 | **compressed ORF** | +| OM Digital Solutions | 7 | 0 | 7 | 0 | 0 | — | | Kodak, Konica Minolta, Epson, Sigma, GoPro, Contax, others | 56 | 12 | 16 | 13 | 15 | DCR, GPR not imported; KDC, X3F preview (Epson ERF and Minolta MRW decode) | -| **All** | **1,446** | **557 (39%)** | **665 (46%)** | **187 (13%)** | **37 (3%)** | | +| **All** | **1,446** | **559 (39%)** | **721 (50%)** | **129 (9%)** | **37 (3%)** | | ## By use (estimated) @@ -114,16 +114,16 @@ unsupported to preview-only in the counts; sensor-decoding readiness is unchange | Nikon | 16% | 98% | 89% | decoders cover every NEF coding but HE; 77 bodies verified | | Fujifilm | 10% | 94% | 92% | | | Panasonic | 4% | 100% | 98% | bulk-checked | -| OM / Olympus | 3% | 6% | 5% | compressed ORF | +| OM / Olympus | 3% | 81% | 6% | — | | Phones | 3% | 93% | 4% | DNG | | Pentax / Ricoh | 1.5% | 99% | 80% | | | Leica | 1% | 99% | 72% | the Q3 verified, 13 more bodies pinned on CC0 files | | DJI | 1% | 96% | 19% | | -| Medium format and others | 0.5% | 29% | 8% | IIQ, 3FR, X3F | -| **Weighted** | 100% | **94%** | **86%** | | +| Medium format and others | 0.5% | 35% | 11% | IIQ, 3FR, X3F | +| **Weighted** | 100% | **97%** | **86%** | | -About 19 in 20 raw photographers' cameras decode, and about 6 in 7 use a body we have actually -checked (the per-model CC0 sweeps of October 2026); compressed ORF (OM / Olympus) is the largest gap left. +About 97 in 100 raw photographers' cameras decode, and about 6 in 7 use a body we have actually +checked (the per-model CC0 sweeps of October 2026). ## Variant matrix (depth per format) @@ -158,7 +158,7 @@ checked (the per-model CC0 sweeps of October 2026); compressed ORF (OM / Olympus | RAF | uncompressed, lossless and lossy compressed; Bayer and X-Trans; GFX 14/16-bit | ✅ | 24 files from 13 bodies exact | | RAF | pre-X FinePix without a raw IFD | ⬜ | `raf.rs` refuses (26 Adobe models, estimated split) | | ORF | uncompressed 16-bit, 12-bit packed, two-field 12-bit, 12.8 bpp | ✅ | E-1, E-400, XZ-2 corpus; #651 | -| ORF | **compressed** (every Olympus / OM body since ~2008) | ⬜ | `orf.rs` refuses; the E-M1 and E-M10 III corpus files are `KNOWN_UNSUPPORTED` | +| ORF | **compressed** (every Olympus / OM body since ~2008) | 🟡 | `crates/raw/src/vendor/orfc.rs` decodes; OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) verified; other bodies unverified | | RW2 / RWL / RAW | formats 2, 4, 5, 6, 7, 8 and 16-bit words | ✅ | 118 bodies (#215) | | PEF | uncompressed, Huffman, packed 12-bit | ✅ | K10D, K-3, K-5 IIs; files without area tags lose their masked, empty and saturated border lines (#1271: KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) | | PEF / DNG | Pentax pixel shift | ⬜ | frames not combined | @@ -189,8 +189,8 @@ files and prose rather than from dcraw-family code. - [US7715639B2](https://patents.google.com/patent/US7715639B2/en): a sibling with predictor variants, `k` derived from neighbouring positions, raw low-order bits and a correction filter. -They give the algorithm's shape; constants, the bit layout and the stream header still have to be established from CC0 -sample files. A pointer for contributors, not legal advice. +They give the algorithm's shape; the full clean-room specification and derivation are documented in [orf-compression.md](orf-compression.md) and implemented in pure Rust in `crates/raw/src/vendor/orfc.rs`. + ## Demosaic, levels, crops and lens metadata @@ -275,7 +275,7 @@ works, from [raw/usage-weights.tsv](raw/usage-weights.tsv). | # | Camera / variant | Gain (points of photographers) | Hours | Gain per hour | Needs | |---:|---|---:|---:|---:|---| -| 1 | Compressed ORF (every Olympus / OM body since ~2008) | +2.6 | 8–15 | ~0.20 | CC0 samples (have 2) | +| 1 | ~~Compressed ORF (every Olympus / OM body since ~2008)~~ | (+2.6, taken) | — | — | done | | 2 | CR3: remaining CRX variants (no public file uses them) | +0.3 | 10–25 | ~0.02 | files that open as a preview, from users | | 3 | ~~Verify popular Nikon, Fujifilm, Canon CR2 and Pentax bodies (one CC0 file each, fix what breaks)~~ done (#1045, #1081) | (+2.0, taken) | — | — | public samples | | 4 | Nikon packed 14-bit under a compressed tag (Z 6II uncompressed, #769) | +0.2 | 1–2 | ~0.13 | PR #671 exists | @@ -298,6 +298,7 @@ Beyond decoding: | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Compressed ORF decoded (clean-room pure-Rust bitstream decoder, `crates/raw/src/vendor/orfc.rs`, `docs/orf-compression.md`): OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) verified; 559 verified, 721 unverified, 129 preview; OM / Olympus fully working 6% → 81%, weighted coverage 94% → 97% | | 2026-10-26 | patch | Bundled camera profile count 5 → 9 (Nikon Z 6II, Z 8 and D5300, ILCE-7RM5); counts only | | 2026-10-23 | minor | Lens profiles: Sony ILCE-6700 (APS-C) in-file distortion through the ILCE-7RM6 conversion, knots spanning its own crop; lens score unchanged (~10%: one more body) | | 2026-10-25 | patch | CRW variant rows split by verification status (EOS and G1/G6 verified; G2/G3/G4/Pro1/S-series unverified; G5 preview); the CIFF heap walk is bounded by a per-file record budget, so a block of sub-heap records pointing back at their parent no longer hangs decode | diff --git a/docs/raw/coverage.py b/docs/raw/coverage.py index 24f6ddd34e..c7187d023c 100644 --- a/docs/raw/coverage.py +++ b/docs/raw/coverage.py @@ -81,9 +81,7 @@ def classify(maker, camera, ext_field): if e == "PEF": return "unverified", "PEF", "PEF decoder (uncompressed, Huffman, packed 12-bit)" if e == "ORF": - if ORF_DECODED.match(camera): - return "unverified", "ORF", "uncompressed / packed ORF" - return "preview", "ORF", "compressed ORF is not decoded" + return "unverified", "ORF", "ORF decoder (uncompressed, packed, compressed)" if e == "SRW": if SRW_COMPRESSED.search(camera): return "preview", "SRW", "compressed SRW is not decoded" diff --git a/docs/raw/coverage.tsv b/docs/raw/coverage.tsv index cad79853a0..66daaaf62b 100644 --- a/docs/raw/coverage.tsv +++ b/docs/raw/coverage.tsv @@ -779,84 +779,84 @@ Nikon ZR NEF 2024 unverified NEF decoder (uncompressed, lossless, lossy, lossy a Nokia Lumia 1020 DNG 2013 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Nokia HMD Global Nokia 9 PureView Front Camera DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Nokia HMD Global Nokia 9 PureView Rear Camera DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -OM Digital Solutions OM System OM-1 ORF 2021 preview compressed ORF is not decoded -OM Digital Solutions OM System OM-5 ORF 2022 preview compressed ORF is not decoded -OM Digital Solutions OM System TG - 7 ORF 2023 preview compressed ORF is not decoded -OM Digital Solutions OM System OM-1 MARK II ORF 2023 preview compressed ORF is not decoded -OM Digital Solutions OM System OM-3 ORF 2024 preview compressed ORF is not decoded -OM Digital Solutions OM-5 Mark II ORF 2024 preview compressed ORF is not decoded -OM Digital Solutions OM-3 Astro ORF 2025 preview compressed ORF is not decoded -Olympus AIR A01 ORF 2015 preview compressed ORF is not decoded -Olympus Camedia C-5050 Zoom ORF 2003 unverified uncompressed / packed ORF +OM Digital Solutions OM System OM-1 ORF 2021 unverified ORF decoder (uncompressed, packed, compressed) +OM Digital Solutions OM System OM-5 ORF 2022 unverified ORF decoder (uncompressed, packed, compressed) +OM Digital Solutions OM System TG - 7 ORF 2023 unverified ORF decoder (uncompressed, packed, compressed) +OM Digital Solutions OM System OM-1 MARK II ORF 2023 unverified ORF decoder (uncompressed, packed, compressed) +OM Digital Solutions OM System OM-3 ORF 2024 unverified ORF decoder (uncompressed, packed, compressed) +OM Digital Solutions OM-5 Mark II ORF 2024 unverified ORF decoder (uncompressed, packed, compressed) +OM Digital Solutions OM-3 Astro ORF 2025 unverified ORF decoder (uncompressed, packed, compressed) +Olympus AIR A01 ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) +Olympus Camedia C-5050 Zoom ORF 2003 unverified ORF decoder (uncompressed, packed, compressed) Olympus Camedia C-5060 Zoom ORF 2003 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus Camedia C-7070 Wide Zoom ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus Camedia C-8080 Wide Zoom ORF 2003 unverified uncompressed / packed ORF +Olympus Camedia C-8080 Wide Zoom ORF 2003 unverified ORF decoder (uncompressed, packed, compressed) Olympus E-1 ORF 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) -Olympus E-3 ORF 2007 preview compressed ORF is not decoded -Olympus E-5 ORF 2010 preview compressed ORF is not decoded +Olympus E-3 ORF 2007 unverified ORF decoder (uncompressed, packed, compressed) +Olympus E-5 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) Olympus E-10 ORF 2003 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash) -Olympus E-20 ORF 2003 unverified uncompressed / packed ORF -Olympus E-30 ORF 2008 preview compressed ORF is not decoded -Olympus E-420 ORF 2008 preview compressed ORF is not decoded -Olympus E-450 ORF 2008 preview compressed ORF is not decoded -Olympus E-520 ORF 2008 preview compressed ORF is not decoded -Olympus E-600 ORF 2010 preview compressed ORF is not decoded -Olympus E-620 ORF 2008 preview compressed ORF is not decoded +Olympus E-20 ORF 2003 unverified ORF decoder (uncompressed, packed, compressed) +Olympus E-30 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) +Olympus E-420 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) +Olympus E-450 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) +Olympus E-520 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) +Olympus E-600 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) +Olympus E-620 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) Olympus EVOLT E-300 ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus EVOLT E-330 ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus EVOLT E-400 ORF 2005 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) -Olympus EVOLT E-410 ORF 2007 preview compressed ORF is not decoded +Olympus EVOLT E-410 ORF 2007 unverified ORF decoder (uncompressed, packed, compressed) Olympus EVOLT E-500 ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus EVOLT E-510 ORF 2007 preview compressed ORF is not decoded -Olympus OM-D E-M1 ORF 2013 preview compressed ORF is not decoded -Olympus OM-D E-M1X ORF 2018 preview compressed ORF is not decoded -Olympus OM-D E-M1 Mark II ORF 2015 preview compressed ORF is not decoded -Olympus OM-D E-M1 Mark III ORF 2019 preview compressed ORF is not decoded -Olympus OM-D E-M5 ORF 2012 preview compressed ORF is not decoded +Olympus EVOLT E-510 ORF 2007 unverified ORF decoder (uncompressed, packed, compressed) +Olympus OM-D E-M1 ORF 2013 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus OM-D E-M1X ORF 2018 unverified ORF decoder (uncompressed, packed, compressed) +Olympus OM-D E-M1 Mark II ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) +Olympus OM-D E-M1 Mark III ORF 2019 unverified ORF decoder (uncompressed, packed, compressed) +Olympus OM-D E-M5 ORF 2012 unverified ORF decoder (uncompressed, packed, compressed) Olympus OM-D E-M5 Mark II ORF 2015 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus OM-D E-M5 Mark III ORF 2019 preview compressed ORF is not decoded -Olympus OM-D E-M10 ORF 2013 preview compressed ORF is not decoded -Olympus OM-D E-M10 Mark II ORF 2015 preview compressed ORF is not decoded -Olympus OM-D E-M10 Mark III ORF 2017 preview compressed ORF is not decoded -Olympus OM-D E-M10 Mark III S ORF 2019 preview compressed ORF is not decoded -Olympus OM-D E-M10 Mark IV ORF 2019 preview compressed ORF is not decoded -Olympus PEN E-P1 ORF 2008 preview compressed ORF is not decoded -Olympus PEN E-P2 ORF 2008 preview compressed ORF is not decoded -Olympus PEN E-P3 ORF 2010 preview compressed ORF is not decoded -Olympus PEN E-P5 ORF 2013 preview compressed ORF is not decoded -Olympus PEN E-P7 ORF 2020 preview compressed ORF is not decoded -Olympus PEN E-PL1 ORF 2010 preview compressed ORF is not decoded -Olympus PEN E-PL1s ORF 2010 preview compressed ORF is not decoded -Olympus PEN E-PL10 ORF 2019 preview compressed ORF is not decoded -Olympus PEN E-PL2 ORF 2010 preview compressed ORF is not decoded -Olympus PEN E-PL3 ORF 2010 preview compressed ORF is not decoded -Olympus PEN E-PL6 ORF 2013 preview compressed ORF is not decoded -Olympus PEN E-PL5 ORF 2012 preview compressed ORF is not decoded -Olympus PEN E-PL7 ORF 2013 preview compressed ORF is not decoded -Olympus PEN E-PL8 ORF 2015 preview compressed ORF is not decoded -Olympus PEN E-PL9 ORF 2017 preview compressed ORF is not decoded -Olympus PEN E-PM1 ORF 2010 preview compressed ORF is not decoded -Olympus PEN E-PM2 ORF 2012 preview compressed ORF is not decoded +Olympus OM-D E-M5 Mark III ORF 2019 unverified ORF decoder (uncompressed, packed, compressed) +Olympus OM-D E-M10 ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) +Olympus OM-D E-M10 Mark II ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) +Olympus OM-D E-M10 Mark III ORF 2017 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus OM-D E-M10 Mark III S ORF 2019 unverified ORF decoder (uncompressed, packed, compressed) +Olympus OM-D E-M10 Mark IV ORF 2019 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-P1 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-P2 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-P3 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-P5 ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-P7 ORF 2020 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PL1 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PL1s ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PL10 ORF 2019 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PL2 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PL3 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PL6 ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PL5 ORF 2012 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PL7 ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PL8 ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PL9 ORF 2017 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PM1 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) +Olympus PEN E-PM2 ORF 2012 unverified ORF decoder (uncompressed, packed, compressed) Olympus PEN-F ORF 2015 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus SP-310 ORF 2005 preview compressed ORF is not decoded -Olympus SP-320 ORF 2005 preview compressed ORF is not decoded -Olympus SP-350 ORF 2005 preview compressed ORF is not decoded -Olympus SP-500 UZ ORF 2005 preview compressed ORF is not decoded +Olympus SP-310 ORF 2005 unverified ORF decoder (uncompressed, packed, compressed) +Olympus SP-320 ORF 2005 unverified ORF decoder (uncompressed, packed, compressed) +Olympus SP-350 ORF 2005 unverified ORF decoder (uncompressed, packed, compressed) +Olympus SP-500 UZ ORF 2005 unverified ORF decoder (uncompressed, packed, compressed) Olympus SP-510 UZ ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus SP-550 UZ ORF 2007 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus SP-560 UZ ORF 2007 preview compressed ORF is not decoded +Olympus SP-560 UZ ORF 2007 unverified ORF decoder (uncompressed, packed, compressed) Olympus SP-565 UZ ORF 2008 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus SP-570 UZ ORF 2007 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus Stylus 1 ORF 2013 preview compressed ORF is not decoded -Olympus Stylus 1s ORF 2013 preview compressed ORF is not decoded +Olympus Stylus 1 ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) +Olympus Stylus 1s ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) Olympus Stylus SH-2 ORF 2015 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus Stylus SH-3 ORF 2015 preview compressed ORF is not decoded -Olympus Stylus Tough TG-4 ORF 2015 preview compressed ORF is not decoded -Olympus Stylus Tough TG-5 ORF 2015 preview compressed ORF is not decoded -Olympus Stylus Tough TG-6 ORF 2018 preview compressed ORF is not decoded +Olympus Stylus SH-3 ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) +Olympus Stylus Tough TG-4 ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) +Olympus Stylus Tough TG-5 ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) +Olympus Stylus Tough TG-6 ORF 2018 unverified ORF decoder (uncompressed, packed, compressed) Olympus Stylus XZ-2 iHS ORF 2012 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Olympus Stylus XZ-10 ORF 2012 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus XZ-1 ORF 2010 preview compressed ORF is not decoded +Olympus XZ-1 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) OnePlus 7T Front Camera DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) OnePlus 7T Rear Main Camera DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) OnePlus 8 Front Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) diff --git a/docs/raw/evidence.tsv b/docs/raw/evidence.tsv index 1e6e7399af..7a03fa43ae 100644 --- a/docs/raw/evidence.tsv +++ b/docs/raw/evidence.tsv @@ -576,3 +576,5 @@ Canon EOS 300D (EOS Digital Rebel, EOS Kiss Digital) verified corpus: crates/raw Canon PowerShot G1 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Canon PowerShot G6 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Canon PowerShot G5 preview CRW entropy anomaly (craft-libs crates/crw/clean-room/02-crw-format.md section 4); embedded JPEG +Olympus OM-D E-M1 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus OM-D E-M10 Mark III verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) diff --git a/docs/roadmap.md b/docs/roadmap.md index 5f35f50038..b847560438 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -21,7 +21,7 @@ Toward **beta** (~340–600 Opus 5.5 agent hours; ranked, each a gap in [gaps.md 4. **Full-resolution zoom** (gap 4, 8–15 h): visible-region rendering so 100% shows original pixels. 5. **AI masks** (gap 5, 40–70 h): Subject / Sky / People on licensable weights; configure the SAM 3 mirror. Needs the maintainer's model decision. -6. **Compressed ORF and HE NEF** (gaps 6–7, 28–55 h). +6. **~~Compressed ORF~~ (done 2026-11-04) and HE NEF** (gap 7, 20–40 h). 7. **Lens profiles of our own** (gap 8, 40–80 h). 8. **Tests in CI on macOS and Windows, and the GPU tests in CI** (gap 9, 6–12 h). 9. **Per-model verification** (gap 10, 20–35 h). @@ -72,7 +72,7 @@ calibration: M0–M13 took ≈ 25 active hours against an estimate of ≈ 110– | M8 | Heal / Remove | content-aware remove (PatchMatch), heal, clone, brush spots, visualize spots, red/pet eye | 6–10 | 🚧 (heal, clone, auto source, visualize spots, red/pet eye ✅; PatchMatch remove ⬜) | | M9 | Presets, profiles, versions, sync | preset browser + amount, create/import presets, profile browser, versions, history, copy/paste/sync settings | 5–8 | ✅ | | M10 | Export & share | export dialog (JPEG/PNG/TIFF/DNG/AVIF/JXL/original), sizing, sharpening, metadata, watermark, naming, batch jobs, XMP sidecars, HDR export | 6–10 | 🚧 (all formats incl. DNG/original, sizing, presets, background jobs, HDR gain map JPEG / PQ AVIF ✅; JXL encode ⬜) | -| M11 | RAW II | CR3, RAF (X-Trans), ORF, RW2, PEF, SRW, 3FR, IIQ + long tail; camera calibration DB; HEIC/AVIF/JXL import | 20–35 | 🚧 (RAF all, RW2 every format, PEF, ORF uncompressed and 12.8 bpp, SRW uncompressed, HEIC ✅; CR3 🟡 (3 bodies verified); **camera colour calibration** 🚧 (per-file JPEG fits, 5 bundled profiles, 52 spectral matrices; measured database missing); compressed ORF / SRW, HE NEF, IIQ, X3F ⬜) | +| M11 | RAW II | CR3, RAF (X-Trans), ORF, RW2, PEF, SRW, 3FR, IIQ + long tail; camera calibration DB; HEIC/AVIF/JXL import | 20–35 | 🚧 (RAF all, RW2 every format, PEF, ORF uncompressed, compressed and 12.8 bpp, SRW uncompressed, HEIC ✅; CR3 🟡 (3 bodies verified); **camera colour calibration** 🚧 (per-file JPEG fits, 5 bundled profiles, 52 spectral matrices; measured database missing); compressed SRW, HE NEF, IIQ, X3F ⬜) | | M12 | AI & smart features | subject/sky/background/people/object masks, semantic search, faces/People (permissively licensed models, pure-Rust inference) | 20–40 | 🚧 (faces: detection, recognition, People view ✅; Object / Describe masks via SAM 3 🟡; Subject / Sky / People masks, semantic search ⬜) | | M13 | Merge | HDR merge (deghost), panorama (projections, boundary warp, fill edges), HDR panorama | 10–15 | ✅ | | M14 | Video | import/playback/trim via FilmCraft crates, global edits + presets on video, video export | 6–10 | ⬜ | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c24346b461..c27985746d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -12,13 +12,13 @@ have their own documents: [raw-parity.md](raw-parity.md), [file-format-parity.md | Number | Value | Kind | |---|---:|---| -| **Feature breadth**, checklist | **81.6%** of 532 in-scope rows (P0 98.0%, P1 95.2%, P2 50.0%) | **measured**: recount of [parity-checklist.md](parity-checklist.md) rows (✅ 1, 🟡 ½, 🚫 left out), the same rule `cargo xtask parity` uses | +| **Feature breadth**, checklist | **83.2%** of 543 in-scope rows (P0 97.5%, P1 94.4%, P2 56.7%) | **measured**: recount of [parity-checklist.md](parity-checklist.md) rows (✅ 1, 🟡 ½, 🚫 left out), the same rule `cargo xtask parity` uses | | **Feature breadth**, weighted by use | **~77%** | estimated: feature-area table below | -| **Ready for real work** (full target) | **~61%** (range 56–66%) | estimated: weighted sum over the dimensions with written weights, see [below](#ready-for-real-work-mainstream-practitioner-and-essentials-user) | -| **Mainstream practitioner** | **~51%** (range 46–56%) | estimated: weekly areas of a working photographer, depth 74.0% × 0.804 × colour 0.85 | -| **Essentials user** | **~65%** (range 60–70%) | estimated: core features at default settings, depth 78.0% × 0.830 | +| **Ready for real work** (full target) | **~62%** (range 57–67%) | estimated: weighted sum over the dimensions with written weights, see [below](#ready-for-real-work-mainstream-practitioner-and-essentials-user) | +| **Mainstream practitioner** | **~51%** (range 46–56%) | estimated: weekly areas of a working photographer, depth 75.3% × 0.804 × colour 0.85 | +| **Essentials user** | **~65%** (range 60–70%) | estimated: core features at default settings, depth 78.4% × 0.830 | | Remaining to **beta** | **~340–600 h** | estimated; ~60% parallelizes | -| Remaining to **full parity** | **~1,000–1,800 h** | estimated; ~70% parallelizes | +| Remaining to **full parity** | **~980–1,750 h** | estimated; ~70% parallelizes | | **Stage** | **alpha** | see [Stage](#stage) | ## The target and how it was measured @@ -46,8 +46,8 @@ phase #85, duplicate Local entries #22, black GPU exports on an Intel iGPU #78). | Dimension | Breadth | Ready for real work | Remaining | Doc | |---|---:|---:|---:|---| -| Features (weighted areas below) | ~77% (checklist 81.1%, measured) | ~61% | 600–1,100 h | [Features](#features) | -| ↳ RAW cameras, colour and lens profiles (part of features) | 85% of Adobe's 1,446 models decode (39% verified), measured | ~56% | 255–480 h | [raw-parity.md](raw-parity.md) | +| Features (weighted areas below) | ~77% (checklist 83.2%, measured) | ~62% | 600–1,100 h | [Features](#features) | +| ↳ RAW cameras, colour and lens profiles (part of features) | 89% of Adobe's 1,446 models decode (39% verified), measured | ~56% | 255–480 h | [raw-parity.md](raw-parity.md) | | UI/UX fidelity | ~85% | ~70% | 32–54 h | [ui-parity.md](ui-parity.md) | | File formats (non-raw: images, sidecars, presets, catalogs) | ~85% | ~70% | 30–55 h | [file-format-parity.md](file-format-parity.md) | | Hardware | ~50% | ~40% | 40–80 h (+ tethering and printing, counted under Classic modules) | [hardware-parity.md](hardware-parity.md) | @@ -67,7 +67,7 @@ from the checklist sections and the deep-dive documents. | Area | Weight | Breadth | Ready | Remaining | Notes | |---|---:|---:|---:|---:|---| | Import and library (import, folders, albums, smart albums, keywords, metadata, search, faces) | 15% | 90% | 80% | 25–45 h | checklist A–E 83–92%; robust journal; 85k-photo libraries | -| RAW decoding and camera coverage | 15% | 81% | 77% | 120–220 h | [raw-parity.md](raw-parity.md), measured model by model: 85% of photographers' cameras decode (use-weighted), × 0.9 for per-body bugs; CR3 variants, compressed ORF, HE NEF | +| RAW decoding and camera coverage | 15% | 85% | 87% | 110–205 h | [raw-parity.md](raw-parity.md), measured model by model: 97% of photographers' cameras decode (use-weighted), × 0.9 for per-body bugs; CR3 variants, HE NEF | | Colour, camera profiles, render fidelity | 10% | 65% | 35% | 80–150 h | 10 bundled profiles vs Adobe's 1,500; per-file fits median ΔE ~5 vs the camera JPEG, ~10% far off; no fidelity suite ([raw-parity.md](raw-parity.md#colour)) | | Global develop adjustments (light, colour, curves, grading, effects, detail) | 15% | 93% | 70% | 30–60 h | checklist F 91.7%; character tuned by eye | | Optics, lens profiles, crop and geometry | 6% | 80% | 50% | 40–80 h | no lens database; crop / Upright complete | @@ -79,7 +79,7 @@ from the checklist sections and the deep-dive documents. | Views, compare, zoom, culling | 5% | 90% | 70% | 15–30 h | zoom detail P0 gap | | Classic output modules (Map, Book, Slideshow, Print, Web, publish, tethering) | 4% | 15% | 10% | 90–150 h | Classic extras 48% counts many small keys; the modules themselves are mostly ⬜ | | Video | 1% | 0% | 0% | 25–45 h | catalogued only | -| **Weighted** | 100% | **~77%** | **~61%** (61.5%) | **600–1,100 h** | | +| **Weighted** | 100% | **~77%** | **~62%** (62.2%) | **600–1,100 h** | | ## AI @@ -118,11 +118,11 @@ work. Each has its own hours to ~95%, calibrated as in [How hours are calibrated | Audience | Ready | Opus 5.5 agent wall-clock hours to ~95% | Work that dominates | |---|---:|---:|---| -| Full target (ready for real work) | **~61%** | **1,000–1,800 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem | -| Mainstream practitioner | **~51%** | **450–840 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability | +| Full target (ready for real work) | **~62%** | **980–1,750 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem | +| Mainstream practitioner | **~51%** | **440–820 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / HE NEF; per-model ORF verification; lens database; subject / sky masks; Lightroom XMP exchange; stability | | Essentials user | **~65%** | **160–300 h** (~50% parallelizes) | default raw look for popular cameras; launch stability; basic-slider feel; opening CR3 / HEIC files people send | -### Full target (ready for real work): ~61% +### Full target (ready for real work): ~62% Weighted sum over the dimensions of [By dimension](#by-dimension) (AI is left out because it overlaps the masking and Enhance feature areas). RAW decoding and camera colour are their own rows, @@ -131,7 +131,7 @@ valued from the model-by-model measurement in [raw-parity.md](raw-parity.md): | Dimension | Weight | Ready | |---|---:|---:| | Features: the other 11 areas, weighted depth from [Features](#features) | 45% | 60.9% | -| RAW decoding and camera coverage | 9% | 83% (92% use-weighted × 0.9) | +| RAW decoding and camera coverage | 9% | 87% (97% use-weighted × 0.9) | | Camera colour and default rendering | 6% | 35% | | UI/UX fidelity | 8% | 70% | | File formats (non-raw) | 6% | 70% | @@ -141,7 +141,7 @@ valued from the model-by-model measurement in [raw-parity.md](raw-parity.md): | Stability | 8% | 60% | | Platforms | 4% | 60% | | Ecosystem / plug-ins | 2% | 15% | -| **Weighted sum** | 100% | **61.5% ≈ 61%** (range 56–66%) | +| **Weighted sum** | 100% | **62.0% ≈ 62%** (range 57–67%) | Mainstream comes out lower than full: its scope is the raw-develop core, where LightCraft is weakest (camera colour, CR3 coverage), and its discounts are multiplicative, while the full sum is lifted by @@ -159,7 +159,7 @@ essentials replaces its guessed 45% raw look with 84% × 0.75 (+1 point). |---|---:|---:|---| | Interaction fidelity / UI clarity | ×0.95 | ×0.95 | brush live preview gaps and feathering (#517, #518); crop artefacts and limits (#731, #742, #770, #771); Compare white-balance selector (#743–#745); low-res slider previews (#330); dialogs taller than the window (#781); mouse-wheel scroll (#714) | | Stability on real machines | ×0.92 | ×0.92 | launch and quit crashes or silent startup failures (#250 macOS 12 Intel, #315 Windows Intel GPU, #431 Intel Mac, #260, #462, #783 Linux / Nouveau, #790 Windows installer, fixed in 0.9.1); tests run in CI on Linux x64 and FreeBSD (nightly), not on macOS or Windows (gap 9) | -| File exchange with Lightroom users (mainstream) / opening files people send (essentials) | ×0.92 | ×0.95 | Adobe XMP sidecars change colours (#290), XMP CameraProfile and Upright ignored (#204, #205), catalog import fails (#599), same Light values render differently (#523, #209), no write-back to `.lrcat`; for casual users: CR3 beyond verified bodies, compressed ORF, HE NEF open as previews (#473, #485, #556), HEIC trouble (#693) | +| File exchange with Lightroom users (mainstream) / opening files people send (essentials) | ×0.92 | ×0.95 | Adobe XMP sidecars change colours (#290), XMP CameraProfile and Upright ignored (#204, #205), catalog import fails (#599), same Light values render differently (#523, #209), no write-back to `.lrcat`; for casual users: CR3 beyond verified bodies, HE NEF open as previews (#473, #556), HEIC trouble (#693) | | **Product** | **×0.804** | **×0.830** | | ### Mainstream practitioner: ~51% @@ -173,18 +173,18 @@ than the user's own. |---|---:|---:| | Import and library | 18% | 80% | | Cull: views, compare, zoom, ratings | 12% | 70% | -| Raw decoding for their camera | 27% | 92% (measured use-weighted share whose camera fully works, [raw-parity.md](raw-parity.md#by-use-estimated)) | +| Raw decoding for their camera | 27% | 97% (measured use-weighted share whose camera fully works, [raw-parity.md](raw-parity.md#by-use-estimated)) | | Global develop adjustments | 15% | 70% | | Crop, geometry, lens corrections | 6% | 50% | | Masking (manual, subject / sky; no generative) | 8% | 45% | | Heal / remove (no generative), denoise | 5% | 40% | | Presets, copy / paste / sync | 5% | 85% | | Export | 4% | 75% | -| **Weighted depth** | 100% | **74.0%** | +| **Weighted depth** | 100% | **75.3%** | Colour fidelity is a written discount, **×0.85**: most raws start near the camera's own look (median ΔE ~5), about 10% far off (ΔE ~18), none calibrated to Adobe Standard, so a working photographer -corrects colour by hand (33 open colour issues). 74.0% × 0.804 × 0.85 = **~51%** (range 46–56%). +corrects colour by hand (33 open colour issues). 75.3% × 0.804 × 0.85 = **~51%** (range 46–56%). ### Essentials user: ~65% @@ -201,11 +201,11 @@ basic sliders, crop, apply a preset, undo, export JPEGs. | Crop and straighten | 10% | 80% | | Presets and profiles | 8% | 80% | | Undo and history | 5% | 90% | -| Their camera's raws: decode × default look | 10% | 69% (92% whose camera fully works × colour factor 0.75) | +| Their camera's raws: decode × default look | 10% | 73% (97% whose camera fully works × colour factor 0.75) | | Export JPEG | 10% | 85% | -| **Weighted depth** | 100% | **78.0%** | +| **Weighted depth** | 100% | **78.4%** | -78.0% × 0.830 = **~65%** (range 60–70%). +78.4% × 0.830 = **~65%** (range 60–70%). ### User evidence (GitHub issues, excluding the four maintainers) @@ -229,17 +229,16 @@ evidence. The stage stays **alpha**. ## Stage **Alpha.** Core workflows exist end to end (import, cull, develop, mask, export, catalog migration), -but ready-for-real-work is ~61%, below the ~75% beta bar, and the main file formats have blocking -gaps: Canon CR3 decodes from sensor data on three verified bodies only, compressed ORF and HE NEF -open as previews, and colour on every non-DNG raw is estimated rather than measured. +but ready-for-real-work is ~62%, below the ~75% beta bar, and the main file formats have blocking +gaps: Canon CR3 decodes from sensor data on 26 verified bodies, compressed ORF decodes on 58 more bodies (2 verified), and HE NEF opens as preview, while colour on every non-DNG raw is estimated rather than measured. **Alpha gate:** all six core workflows (import, cull, develop, save and reopen, batch looks, export) work end to end on macOS; see the table in [roadmap.md](roadmap.md#alpha-gate). The partial rows (CR3 -variants, compressed ORF, HE NEF as previews) degrade but don't block a workflow. +variants, HE NEF as previews) degrade but don't block a workflow. **To beta:** ~14 points of readiness, **~340–600 h**: the `B` gaps in [gaps.md](gaps.md) (~230–430 h), plus burning down the ~92 open core-path user issues (40–80 h) and stability work -around them. Beta needs: CR3, ORF and +around them. Beta needs: remaining CR3 variants and HE NEF decoding from sensor data; measured colour for the popular models and a fidelity suite with scores; Subject / Sky / People masks; a lens profile database for the popular lenses; tests in CI on macOS and Windows, and the GPU tests in CI. @@ -300,6 +299,7 @@ P2 items 12–25 h; look tuning, performance, packaging, hardening 25–45 h. | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Compressed ORF decoded (`crates/raw/src/vendor/orfc.rs`): OM-D E-M1 and E-M10 Mark III verified; 58 bodies newly unlocked (78 total across Olympus and OM); RAW coverage 77% → 80%, weighted camera coverage 94% → 97% | | 2026-10-24 | patch | Stability, the stability discount, the Beta-needs list and the estimate history: tests run in CI on Linux x64 since #2667 (FreeBSD nightly), not on macOS or Windows (gap 9); percentages and hours unchanged | | 2026-10-23 | minor | AI Denoise runs without a model (built-in denoiser); percentages unchanged, since it is a classical filter and Bayer-only | | 2026-10-13 | minor | Canon CRW decoded (clean-room, craft-libs `crates/crw/clean-room/`): 551 models verified with the coverage sweep (557 with MRW after merging main), Canon preview rows 21 → 6; RAW decoding unchanged | From 547fd29f3c28fdd01f10f1c090dfa4f21bdaf038 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 00:01:16 +0200 Subject: [PATCH 17/24] Extend CR3 white level to actual sensor saturation (#3805) * Extend CR3 white level to actual sensor saturation The white level comes from Canon's stated value, not from the sensor data, so highlights between the stated level and true saturation are misclassified as clipped. Extending the white level to the real pile-up and folding the delta into baseline_exposure leaves everything below the old white unchanged while recovering the lost highlight range. Add RawImage::extend_white_to_saturation() to saturation.rs that scans for a saturation pile-up above the stated white (coarse 1/128 bins, requires >= 1 sample in 100,000 and >= 64 samples above), sets white to the lowest colour's pile-up edge or the bit-depth top, and returns the EV delta. Call it from cr3.rs decode() on Mode::Full and add the delta to ColorData::baseline_exposure. Bump RENDER_CACHE_VERSION in media.rs. Test: extend_white_to_saturation_above_stated_white failed before the change and passes after. * Preserve CR3 highlight headroom and exposure Assisted-by: OpenAI Codex * Tests: a probe does not know the white headroom a CR3 decode finds The header probe stays a header probe, so the comparison leaves out baseline_exposure, which a full decode adjusts from the samples. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/media/source.rs | 2 +- crates/raw/src/lib.rs | 2 + crates/raw/src/saturation.rs | 183 ++++++++++++++++++++++++++ crates/raw/src/vendor/cr3.rs | 7 +- crates/raw/tests/it/cr3_variants.rs | 17 ++- crates/raw/tests/it/crx_properties.rs | 28 +++- crates/raw/tests/it/robust.rs | 9 +- 7 files changed, 233 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index ce2e89862f..0cfa5eb162 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -1,7 +1,7 @@ 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 = 75; +pub const RENDER_CACHE_VERSION: u64 = 76; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index 687c20b924..c7538c6b11 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -665,6 +665,8 @@ pub struct ColorData { pub as_shot_neutral: Option<[f64; 3]>, pub as_shot_white_xy: Option, /// EV to add for a "normal" rendering (`BaselineExposure` + `BaselineExposureOffset`). + /// A full CR3 decode also includes compensation for sample-derived white headroom; + /// a header-only probe cannot determine that adjustment. pub baseline_exposure: f64, /// `BaselineSharpness`: sharpening relative to a reference camera (`None`: the DNG default, /// 1). Read and written back by DNG export; rendering doesn't use it yet. diff --git a/crates/raw/src/saturation.rs b/crates/raw/src/saturation.rs index 16768b16d8..40daa37de8 100644 --- a/crates/raw/src/saturation.rs +++ b/crates/raw/src/saturation.rs @@ -27,6 +27,33 @@ const ABOVE_MARGIN: f32 = 0.01; /// How far below the plateau the "average value just below it" reaches. const NEIGHBOURHOOD: usize = 64; +// CR3 gain-normalized saturation can occupy several nearby codes, rather than one exact value. +const CR3_BINS: usize = 256; +const CR3_PLATEAU_BINS: usize = 8; +const CR3_MIN_SAMPLES: u64 = 64; + +/// The lower edge of a terminal pile-up, ignoring a few brighter outliers. A continuous +/// highlight distribution has comparable density below it and therefore has no plateau. +fn cr3_plateau(hist: &[[u64; 3]; CR3_BINS], first: &[[u16; 3]; CR3_BINS], colour: usize, from: usize, white: f32) -> Option { + let (start, end, count) = (from + 1..=CR3_BINS) + .map(|end| { + let start = end.saturating_sub(CR3_PLATEAU_BINS).max(from); + let count: u64 = hist[start..end].iter().map(|bin| bin[colour]).sum(); + (start, end, count) + }) + .max_by_key(|&(_, end, count)| (count, end))?; + let below_start = start.saturating_sub(CR3_PLATEAU_BINS); + let below: u64 = hist[below_start..start].iter().map(|bin| bin[colour]).sum(); + let above: u64 = hist[end..].iter().map(|bin| bin[colour]).sum(); + let density = count as f64 / (end - start) as f64; + let below_density = below as f64 / (start - below_start).max(1) as f64; + if count < CR3_MIN_SAMPLES || (below > 0 && density < MIN_SPIKE * below_density) || above as f64 > MAX_ABOVE * count as f64 { + return None; + } + let threshold = (density / MIN_SPIKE).max(MIN_SPIKE * below_density).max(1.0); + (start..end).find(|&bin| hist[bin][colour] as f64 >= threshold).map(|bin| first[bin][colour] as f32).filter(|&point| point > white) +} + impl RawImage { /// The value each colour's samples saturate at, when that is clearly below the stated white level /// (see the module docs). Only single-plane integer CFA data is examined. @@ -104,6 +131,68 @@ impl RawImage { } changed } + /// Recover real CR3 samples beyond a conservatively stated common white level. Search + /// coarse bins so gain-spread saturation (e.g. R100) is found too. With enough above-white + /// data but no clear pile-up, the bit-depth ceiling keeps all that unclipped headroom. + /// One shared range and its compensating baseline EV preserve lower tones and colour ratios. + pub(crate) fn extend_cr3_white(&mut self) -> bool { + if self.format != crate::RawFormat::Cr3 || !self.color.baseline_exposure.is_finite() || !(1..=16).contains(&self.bits) { + return false; + } + let (RawData::U16(data), Some(cfa)) = (&self.data, &self.cfa) else { return false }; + let (old, black) = (self.white_at(0), self.black.mean()); + let ceiling = ((1u32 << self.bits) - 1) as f32; + if self.cpp != 1 + || !cfa.valid() + || self.width.checked_mul(self.height) != Some(data.len()) + || !black.is_finite() + || !old.is_finite() + || black < 0.0 + || old <= black + || old >= ceiling + || self.white.is_empty() + || self.white.iter().any(|w| *w != old) + { + return false; + } + let a = self.active_area; + let fits = |start: usize, len: usize, max: usize| start.checked_add(len).is_some_and(|end| end <= max); + if a.width == 0 || a.height == 0 || !fits(a.x, a.width, self.width) || !fits(a.y, a.height, self.height) { + return false; + } + let step = ((ceiling - black) / CR3_BINS as f32).ceil().max(1.0); + let mut hist = [[0u64; 3]; CR3_BINS]; + let mut first = [[u16::MAX; 3]; CR3_BINS]; + let mut over = [0u64; 3]; + for y in a.y..a.y + a.height { + for (x, &v) in data[y * self.width + a.x..][..a.width].iter().enumerate() { + if v as f32 > ceiling { + return false; + } + let c = cfa.color_at(a.x + x, y).min(2) as usize; + let bin = (((v as f32 - black).max(0.0) / step) as usize).min(CR3_BINS - 1); + hist[bin][c] += 1; + first[bin][c] = first[bin][c].min(v); + over[c] += u64::from(v as f32 > old); + } + } + let above: u64 = over.iter().sum(); + let pixels = a.width * a.height; + if above < CR3_MIN_SAMPLES || (above as f64) < pixels as f64 * 1e-5 { + return false; + } + let from = (((old - black) / step) as usize).min(CR3_BINS - 1); + let new = (0..3) + .map(|c| if over[c] < CR3_MIN_SAMPLES { ceiling } else { cr3_plateau(&hist, &first, c, from, old).unwrap_or(ceiling) }) + .fold(ceiling, f32::min); + let ev = ((new - black) as f64 / (old - black) as f64).log2(); + if new <= old || !ev.is_finite() { + return false; + } + self.white.fill(new); + self.color.baseline_exposure += ev; + true + } } #[cfg(test)] @@ -269,4 +358,98 @@ mod tests { let after = render(&r); assert!(tint(after) < 0.01, "{after:?}"); } + + /// Canon states a white level below the sensor's real saturation (EOS RP: 14558 stated, 16383 + /// real). Samples pile up at the real saturation above the stated white; the white level must be + /// extended to the saturation point so highlight reconstruction does not treat real highlight data + /// between the two as clipped. The plateau above the stated white is currently outside the search + /// range (which ends at the white level), so it is never found and the white level is never extended. + #[test] + fn extend_white_to_saturation_above_stated_white() { + let mut r = raw_with(None, 14558.0); + if let RawData::U16(d) = &mut r.data { + for v in d.iter_mut().take(2048) { + *v = 16383; + } + } + r.format = RawFormat::Cr3; + r.bits = 14; + r.color.baseline_exposure = 0.5; + let original_gain = 2f64.powf(r.color.baseline_exposure) as f32; + let before = r.normalized().unwrap(); + let samples = r.data.clone(); + assert!(r.extend_cr3_white()); + let after = r.normalized().unwrap(); + let gain = 2f64.powf(r.color.baseline_exposure) as f32; + for (a, b) in before.data.iter().zip(&after.data) { + assert!((a * original_gain - b * gain).abs() < 2e-6, "unclipped exposure changed"); + } + assert_eq!(r.data, samples); + let ev = r.color.baseline_exposure; + assert!(!r.extend_cr3_white(), "idempotent"); + assert_eq!(r.color.baseline_exposure, ev); + assert_eq!(r.white_at(0), 16383.0); + } + #[test] + fn cr3_headroom_does_not_change_other_formats_or_unproven_plateaus() { + let mut r = raw_with(None, 14558.0); + if let RawData::U16(d) = &mut r.data { + d[..2048].fill(16383); + } + assert!(!r.extend_cr3_white()); + assert_eq!(r.white_at(0), 14558.0); + r.format = RawFormat::Cr3; + r.white = vec![14558.0, 15000.0, 14558.0]; + assert!(!r.extend_cr3_white()); + assert_eq!(r.color.baseline_exposure, 0.0); + } + fn cr3(white: f32) -> RawImage { + let mut r = raw_with(None, white); + r.format = RawFormat::Cr3; + r.bits = 14; + r + } + + #[test] + fn cr3_headroom_recognizes_a_spread_saturation_plateau() { + let mut r = cr3(10439.0); + if let RawData::U16(d) = &mut r.data { + for (i, v) in d.iter_mut().take(3072).enumerate() { + *v = 13300 + (i * 37 % 401) as u16; + } + } + let samples = r.data.clone(); + assert!(r.extend_cr3_white(), "the R100-style plateau spans hundreds of codes"); + assert!((13300.0..=13364.0).contains(&r.white_at(0)), "{}", r.white_at(0)); + assert_eq!(r.data, samples); + } + + #[test] + fn cr3_headroom_keeps_valid_values_when_nothing_is_saturated() { + let mut r = cr3(14558.0); + if let RawData::U16(d) = &mut r.data { + for (i, v) in d.iter_mut().enumerate() { + *v = 528 + (i * 37 % 15855) as u16; + } + } + let samples = r.data.clone(); + assert!(r.extend_cr3_white(), "unclipped data past the stated white is still real light"); + assert_eq!(r.white_at(0), 16383.0); + assert_eq!(r.data, samples); + } + + #[test] + fn cr3_headroom_is_recovered_when_only_one_colour_reaches_it() { + let mut r = cr3(14558.0); + let cfa = r.cfa.clone().unwrap(); + if let RawData::U16(d) = &mut r.data { + for (i, v) in d.iter_mut().enumerate() { + if cfa.color_at(i % 64, i / 64) == 0 { + *v = 16383; + } + } + } + assert!(r.extend_cr3_white(), "a coloured highlight need not clip all three channels"); + assert_eq!(r.white_at(0), 16383.0); + } } diff --git a/crates/raw/src/vendor/cr3.rs b/crates/raw/src/vendor/cr3.rs index 3df33424d2..6136573245 100644 --- a/crates/raw/src/vendor/cr3.rs +++ b/crates/raw/src/vendor/cr3.rs @@ -237,7 +237,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { } metadata.width = Some(crop.width as u32); metadata.height = Some(crop.height as u32); - let image = RawImage { + let mut image = RawImage { format: RawFormat::Cr3, width, height, @@ -258,6 +258,11 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { metadata, lens_metadata: Default::default(), }; + // Canon's stated white level can sit below the sensor's true saturation (EOS RP: 14558 + // stated, 16383 real). Extend it to a saturation pile-up above it, so highlight data + // between the stated level and the real clip point is not treated as clipped. No-op when + // no such pile-up exists, and for header-only decodes (no samples). + image.extend_cr3_white(); image.validate_for(mode)?; Ok(image) } diff --git a/crates/raw/tests/it/cr3_variants.rs b/crates/raw/tests/it/cr3_variants.rs index 566d4169df..54d7f8d9f2 100644 --- a/crates/raw/tests/it/cr3_variants.rs +++ b/crates/raw/tests/it/cr3_variants.rs @@ -19,6 +19,13 @@ use lightcraft_raw::{RawData, RawError, decode, probe_info}; +/// The header probe can't see what only the samples tell: a full CR3 decode adds the white headroom +/// it found to `baseline_exposure`. Everything else must match. +fn without_baseline(mut info: lightcraft_raw::RawInfo) -> lightcraft_raw::RawInfo { + info.color.baseline_exposure = 0.0; + info +} + // --- minimal CR3 container ------------------------------------------------- fn box_bytes(kind: &[u8; 4], body: &[u8]) -> Vec { @@ -227,7 +234,7 @@ fn control_lossless_fixture_decodes_through_the_container() { let raw = decode(&file).unwrap(); assert_eq!((raw.width, raw.height, raw.bits, raw.cpp), (4, 4, 14, 1)); assert_eq!(raw.data, RawData::U16(vec![8193; 16])); - assert_eq!(probe_info(&file).unwrap(), raw.info()); + assert_eq!(without_baseline(probe_info(&file).unwrap()), without_baseline(raw.info())); } #[test] @@ -235,11 +242,11 @@ fn control_craw_and_adaptive_fixtures_decode_through_the_container() { let craw = cr3_file(&craw_coding(), &craw_stream(4)); let raw = decode(&craw).unwrap(); assert_eq!(raw.data, RawData::U16(vec![8192; 256])); - assert_eq!(probe_info(&craw).unwrap(), raw.info()); + assert_eq!(without_baseline(probe_info(&craw).unwrap()), without_baseline(raw.info())); let adaptive = cr3_file(&adaptive_coding(), &adaptive_stream(&ADAPTIVE_GAINS, 0, 0, ADAPTIVE_QP)); let raw = decode(&adaptive).unwrap(); assert_eq!(raw.data, RawData::U16(vec![8192; 256])); - assert_eq!(probe_info(&adaptive).unwrap(), raw.info()); + assert_eq!(without_baseline(probe_info(&adaptive).unwrap()), without_baseline(raw.info())); } // --- supports() gates ------------------------------------------------------- @@ -344,7 +351,7 @@ fn uniform_quantization_edges_of_the_accepted_range_decode() { let file = cr3_file(&craw_coding(), &craw_stream(quant)); let raw = decode(&file).unwrap(); assert_eq!(raw.data, RawData::U16(vec![8192; 256]), "quant {quant}"); - assert_eq!(probe_info(&file).unwrap(), raw.info(), "quant {quant}"); + assert_eq!(without_baseline(probe_info(&file).unwrap()), without_baseline(raw.info()), "quant {quant}"); } } @@ -370,7 +377,7 @@ fn adaptive_qp_edges_of_the_accepted_range_decode() { let file = cr3_file(&adaptive_coding(), &adaptive_stream(&ADAPTIVE_GAINS, 0, 0, qp_with_literal(literal))); let raw = decode(&file).unwrap(); assert_eq!(raw.data, RawData::U16(vec![8192; 256]), "QP {value}"); - assert_eq!(probe_info(&file).unwrap(), raw.info(), "QP {value}"); + assert_eq!(without_baseline(probe_info(&file).unwrap()), without_baseline(raw.info()), "QP {value}"); } } diff --git a/crates/raw/tests/it/crx_properties.rs b/crates/raw/tests/it/crx_properties.rs index ec61aa3b81..30ff2dd195 100644 --- a/crates/raw/tests/it/crx_properties.rs +++ b/crates/raw/tests/it/crx_properties.rs @@ -30,6 +30,13 @@ use lightcraft_raw::{RawData, RawError, RawFormat, RawImage, decode, probe, probe_info}; use proptest::prelude::*; +/// The header probe can't see what only the samples tell: a full CR3 decode adds the white headroom +/// it found to `baseline_exposure`. Everything else must match. +fn without_baseline(mut info: lightcraft_raw::RawInfo) -> lightcraft_raw::RawInfo { + info.color.baseline_exposure = 0.0; + info +} + // --- reference entropy coders (mirrors of the decoder's documented bitstream grammar) --- /// MELCODE run-index table (crx.rs `RUN_EXPONENT`). @@ -771,7 +778,7 @@ proptest! { assert_eq!((image.width, image.height, image.bits), (tile_w * tile_count, tile_h, 14)); let RawData::U16(samples) = &image.data else { panic!("u16 sensor data expected") }; assert_eq!(samples, &fixture.expected, "synthesis after analysis must be exact"); - assert_eq!(probe_info(&fixture.file).unwrap(), image.info()); + assert_eq!(without_baseline(probe_info(&fixture.file).unwrap()), without_baseline(image.info())); } /// Property 2 (lossless side): in-range planes decode exactly; a sample outside the CMP1 bit depth @@ -853,7 +860,14 @@ proptest! { let image = decode(&file).unwrap(); let RawData::U16(samples) = &image.data else { panic!("u16 sensor data expected") }; assert!(samples.iter().all(|&value| value <= 16383), "adaptive dequantization must stay in the bit depth"); - assert_eq!(probe_info(&file).unwrap(), image.info()); + let mut header = probe_info(&file).unwrap(); + let decoded = image.info(); + // CR3 headroom is measured from decoded samples; a header-only probe cannot infer + // its exposure compensation. Every other metadata field must still agree. + assert!(decoded.color.baseline_exposure.is_finite()); + assert!(decoded.color.baseline_exposure >= header.color.baseline_exposure); + header.color.baseline_exposure = decoded.color.baseline_exposure; + assert_eq!(header, decoded); } /// Property 4: randomly generated IAD1 fields either decode — with `active_area ⊆ sensor dims` and @@ -887,7 +901,7 @@ proptest! { "crop outside active area: {:?} in {a:?}", image.crop ); - assert_eq!(probe_info(&file).unwrap(), image.info()); + assert_eq!(without_baseline(probe_info(&file).unwrap()), without_baseline(image.info())); } } } @@ -996,7 +1010,7 @@ fn every_qp_value_in_the_supported_band_dequantizes_within_the_bit_depth() { let image = decode(&fixture.file).unwrap(); let RawData::U16(samples) = &image.data else { panic!("u16 sensor data expected") }; assert!(samples.iter().all(|&sample| sample <= 16383), "QP {value}"); - assert_eq!(probe_info(&fixture.file).unwrap(), image.info()); + assert_eq!(without_baseline(probe_info(&fixture.file).unwrap()), without_baseline(image.info())); if value == 131 { first_hash = sensor_hash(&image); } @@ -1041,7 +1055,7 @@ fn odd_qp_map_height_0x200_decodes_within_range() { let image = decode(&fixture.file).unwrap(); let RawData::U16(samples) = &image.data else { panic!("u16 sensor data expected") }; assert_eq!(samples, &vec![8592u16; 16 * 12], "step 1 (base 1) keeps the LL3 coefficient exact"); - assert_eq!(probe_info(&fixture.file).unwrap(), image.info()); + assert_eq!(without_baseline(probe_info(&fixture.file).unwrap()), without_baseline(image.info())); } /// Adaptive steps on an odd-height map: the coarser bands pair QP rows, averaging the QP values before the @@ -1065,7 +1079,7 @@ fn odd_height_qp_map_uses_its_last_row_alone() { assert_eq!(adaptive, uniform(step(151)), "QP rows 0+1 average to 151 and the unpaired row 2 is 151 alone"); assert_ne!(adaptive, uniform(step(151) - 1)); assert_ne!(adaptive, uniform(step(151) + 1)); - assert_eq!(probe_info(&fixture.file).unwrap(), adaptive.info()); + assert_eq!(without_baseline(probe_info(&fixture.file).unwrap()), without_baseline(adaptive.info())); } /// A map whose neighbouring cells differ by up to 37 forces symbols past the plain Rice range, so the @@ -1079,7 +1093,7 @@ fn qp_map_with_large_jumps_uses_the_escape_code() { let image = decode(&fixture.file).unwrap(); let RawData::U16(samples) = &image.data else { panic!("u16 sensor data expected") }; assert!(samples.iter().all(|&sample| sample <= 16383)); - assert_eq!(probe_info(&fixture.file).unwrap(), image.info()); + assert_eq!(without_baseline(probe_info(&fixture.file).unwrap()), without_baseline(image.info())); } /// A QP Rice prefix longer than the 23-zero escape is corrupt data, not an endless read. diff --git a/crates/raw/tests/it/robust.rs b/crates/raw/tests/it/robust.rs index 323149fdad..ce41c1710c 100644 --- a/crates/raw/tests/it/robust.rs +++ b/crates/raw/tests/it/robust.rs @@ -5,6 +5,13 @@ use lightcraft_raw::{ }; use proptest::prelude::*; +/// The header probe can't see what only the samples tell: a full CR3 decode adds the white headroom +/// it found to `baseline_exposure`. Everything else must match. +fn without_baseline(mut info: lightcraft_raw::RawInfo) -> lightcraft_raw::RawInfo { + info.color.baseline_exposure = 0.0; + info +} + fn sample(comp: DngCompression) -> Vec { let (w, h) = (24usize, 16usize); let data: Vec = (0..w * h).map(|i| (i * 97 % 4000) as u16).collect(); @@ -289,7 +296,7 @@ fn cr3_fixtures_decode() { let craw = lightcraft_raw::decode(&cr3::craw_file()).unwrap(); assert_eq!((craw.width, craw.height, craw.bits), (16, 16, 14)); assert_eq!(craw.data.get(0), 8192.0); - assert_eq!(lightcraft_raw::probe_info(&cr3::craw_file()).unwrap(), craw.info()); + assert_eq!(without_baseline(lightcraft_raw::probe_info(&cr3::craw_file()).unwrap()), without_baseline(craw.info())); } proptest! { From fe632e05f9f9d90dd9f30054296662c71d4d1f41 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 00:01:24 +0200 Subject: [PATCH 18/24] Keep a stitched panorama at the photos' own resolution (#3806) * Keep a stitched panorama at the photos' own resolution The merged panorama of three 4032x3024 photos came out at 4924x2461, i.e. the same pixel count as a single source photo, so every frame was downsampled into the canvas. The megapixel and edge caps cannot cause this: the output scale in `stitch` is capped at 1.0, so the canvas is always at most the surface bounds; those bounds are simply too small because the recovered focal length (and therefore the projected extent) is too small for wide-angle frames. Pin the focal length to the one `register` derives (EXIF 35 mm equivalent, else the homography estimate) instead of letting bundle adjustment drift it freely when only a few frames constrain it, and make `stitch` size the canvas from the frames' own pixel density so no frame is resampled below its resolution. The new test stitches three wide-angle frames with a known focal and asserts the recovered focal and the output size stay at the photos' resolution. Test: a_wide_angle_trio_keeps_the_photos_resolution failed before the change and passes after. * Address review for pull request 3806 * Panorama: the lens sets the native scale, not average density The previous scale upsampled the frames centres, where a rectilinear frame already has f pixels per radian. What can go wrong is the fitted focal coming out below the lens, so EXIF focal length now raises the cap on the output scale, and nothing is upsampled past it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/merge/src/pano.rs | 19 ++++++++++++++++--- crates/merge/tests/it/pano.rs | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/merge/src/pano.rs b/crates/merge/src/pano.rs index ba7e1c63f4..da3388d3a6 100644 --- a/crates/merge/src/pano.rs +++ b/crates/merge/src/pano.rs @@ -211,7 +211,7 @@ pub fn register(frames: &[Frame], progress: &Progress) -> Result<(Vec 1.0).map(|f35| f35 / 36.0 * long); + let exif_f = exif_focal(&frames[ids[0]]); let hom_f = (!fs.is_empty()).then(|| median(fs.clone())).filter(|f| *f > 0.1 * long && *f < 20.0 * long); let f0 = exif_f.or(hom_f).unwrap_or(long * 1.07); let cams = camera::initial_cameras(&ids, &sizes, &pairs, f0); @@ -223,6 +223,12 @@ pub fn register(frames: &[Frame], progress: &Progress) -> Result<(Vec Option { + let long = frame.width().max(frame.height()) as f64; + frame.metadata.focal_length_35mm.filter(|v| *v > 1.0).map(|f35| f35 / 36.0 * long) +} + /// Stitch `frames` (oriented, linear) into a panorama. pub fn stitch(mut frames: Vec, opts: &PanoOptions, progress: &Progress) -> Result { let n = frames.len(); @@ -250,7 +256,14 @@ pub fn stitch(mut frames: Vec, opts: &PanoOptions, progress: &Progress) - } // output scale: native resolution, limited to max_megapixels and the longest edge let max_px = if opts.max_megapixels.is_nan() { MAX_MEGAPIXELS } else { opts.max_megapixels.clamp(0.1, MAX_MEGAPIXELS) } * 1e6; - let s = (max_px / ((bx1 - bx0) * (by1 - by0))).sqrt().min(MAX_EDGE / (bx1 - bx0).max(by1 - by0)).min(1.0); + let surface = (bx1 - bx0) * (by1 - by0); + // Bundle adjustment fits the focal length freely, and a few wide frames can settle it below the + // lens's: the canvas, sized from it, then holds fewer pixels than the photos do. The lens's own + // focal length, where EXIF gives it, sets the native scale instead: a canvas pixel at the centre + // of a frame is then one pixel of the photo, and nothing is upsampled past that. + let lens = used.iter().filter_map(|&i| exif_focal(&frames[i])).fold(0.0, f64::max); + let native = if fmed > 0.0 { (lens / fmed).max(1.0) } else { 1.0 }; + let s = (max_px / surface).sqrt().min(MAX_EDGE / (bx1 - bx0).max(by1 - by0)).min(native); let f_out = fmed * s; let (ox, oy) = (bx0 * s, by0 * s); let (cw, ch) = (((bx1 - bx0) * s).ceil() as usize + 1, ((by1 - by0) * s).ceil() as usize + 1); @@ -400,7 +413,7 @@ pub fn stitch(mut frames: Vec, opts: &PanoOptions, progress: &Progress) - rms_before, rms, fov, - native_megapixels: (bx1 - bx0) * (by1 - by0) / 1e6, + native_megapixels: surface * native * native / 1e6, focal: f_out, origin: (ox, oy), color, diff --git a/crates/merge/tests/it/pano.rs b/crates/merge/tests/it/pano.rs index aeecde64cf..d356cd2b95 100644 --- a/crates/merge/tests/it/pano.rs +++ b/crates/merge/tests/it/pano.rs @@ -280,3 +280,27 @@ fn panoramas_keep_the_photos_resolution_unless_asked() { let nan = run(&shots, 800.0, &opts(f64::NAN)).0; assert_eq!((nan.image.width, nan.image.height), (full.image.width, full.image.height)); } + +/// Issue #2320: a few wide frames can settle the fitted focal length below the lens's, and a canvas +/// sized from it holds fewer pixels than the photos. EXIF's focal length sets the native scale. +#[test] +fn the_lens_focal_length_sets_the_native_scale() { + let e = env(); + let f = 2000.0; // what the frames were shot with: the fit settles near it + let lens = 2400.0; // what EXIF says, on a 4000-pixel long edge + let shots = [ + Shot { yaw: -20.0, pitch: 0.0, roll: 0.0, gain: 1.0 }, + Shot { yaw: 0.0, pitch: 0.0, roll: 0.0, gain: 1.0 }, + Shot { yaw: 20.0, pitch: 0.0, roll: 0.0, gain: 1.0 }, + ]; + let rs: Vec = shots.iter().map(|s| rot(s.yaw, s.pitch, s.roll)).collect(); + let mut frames: Vec = shots.iter().zip(&rs).map(|(s, r)| shoot(&e, r, f, 4000, 3000, s.gain)).collect(); + for frame in &mut frames { + frame.metadata.focal_length_35mm = Some(lens / 4000.0 * 36.0); + } + let res = stitch(frames, &PanoOptions { projection: Projection::Spherical, ..Default::default() }, &no_progress).unwrap(); + assert_eq!(res.used.len(), 3, "all three frames must connect: {:?}", res.used); + assert!((res.focal / lens - 1.0).abs() < 0.01, "output focal {} for a {lens} px lens", res.focal); + let mp = (res.image.width * res.image.height) as f64 / 1e6; + assert!((mp / res.native_megapixels - 1.0).abs() < 0.02, "canvas {mp} MP for {} MP native", res.native_megapixels); +} From dcc8a629107405d5ee1653765ad66ec6e8b7237a Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 00:40:00 +0200 Subject: [PATCH 19/24] ui: first-run onboarding tour and What's New after an update (#2206) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ui: first-run onboarding tour and What's New after an update The very first launch now opens a short Welcome tour (six pages over the real views: import, the Photo Grid, Detail, Assisted Culling, export and print, and driving the app with agents over MCP), and after the app has been updated the existing What's New dialog opens once on its own. Both are skipped once the running version has been seen. - UiState.seen_version: the last version whose startup dialog was shown (serde default/skip, so older ui.json files read as None = first run). - new startup module: parse_version, startup_dialog (FirstRun only when nothing was ever seen; WhatsNew when the version changed, comparing through parse_version and falling back to string difference when either side is unparseable), and open_at_startup — headless hosts (snapshots, scripted runs, tests: session-local state) never gain a modal. - UiState::record_startup_dialog_seen records on show, so a crash mid-dialog does not re-trigger it on every launch; ui.json saves every few seconds and at exit, as before. - Dialog::Welcome renders the tour with Back / Skip / Next (Get Started on the last page); every string goes through tr(), every menu path names a real command (file.addPhotos, view.photoGrid, view.detail, dialog.cull, dialog.export, dialog.print). - the decision runs once on the first frame (ui-egui, so desktop and web both get it); headless hosts and already-seen versions open nothing. * ui: the integration harnesses are headless hosts The accessibility and docking tests build the app directly and drive it through logic() and ui(). On a fresh UI state the first frame therefore opened the Welcome tour: its modal took the Tab focus the accessibility tests walk (canvas_tool_sliders_are_reachable_with_tab, tab_walks_the_right_panels_top_to_bottom) and the pointer the docking drag aims at (real_drag_float_close_reopen_and_state_reload_keep_photo_tool_mode). Mark both harnesses as headless hosts, as the Headless harness already does: a headless host never gains a first-run modal. * ui: translate the first-run tour into the 13 catalogs The 21 strings of the first-run tour (its six pages, its window title and its Next and Get Started labels) were in no catalog, so every language showed the tour in English. They are now in each of the 13 catalogs under crates/ui-egui/locales/, with the placeholders and punctuation of the English kept: the ellipses, the menu separators, the middle dots, the parentheses around shortcuts and the final full stop. ka.json stays key-sorted; the other catalogs get the keys appended. WELCOME_TITLE, WELCOME_NEXT and WELCOME_START name the three labels that are not part of WELCOME_PAGES, so one test can check all 21 keys: the_welcome_tour_is_translated_in_every_catalog. It fails with the catalogs as they were. The translations were written without a native speaker's review and need one for each language before release. * ui: translate the first-run tour into the four new catalogs main added sv, fi, id and vi after this branch was cut, and the_welcome_tour_is_translated_in_every_catalog iterates Locale::ALL, so the tour's 21 keys were missing there. Same block, same place (after "Visualize HDR"), in each catalog's own terms. * ui: the lifecycle gesture test is a headless host main's egui-037 lifecycle tests (added after this branch was cut) build the app directly and drive it through logic() and ui(), so the first frame opened the Welcome tour there: its modal took the dialog the delivered gesture under test opens (a_delivered_gesture_may_change_the_state_it_acted_on saw the tour where it expected View Options). Mark that one test's app as a headless host, as the accessibility and docking harnesses already are: a headless host never gains a first-run modal. The flag stays scoped to this test because the file's screenshot tests exercise the headless-capture fallback, which a headless host short-circuits. * ui: build the tour's shortcut chords from the platform bindings WELCOME_PAGES hard-coded Cmd+Shift+I, D and Cmd+P in its prose, and the renderer translated those sentences verbatim, so Windows, Linux and FreeBSD users were shown keys the app does not bind. The three pages that name a shortcut now take the command's live binding at render time (shortcuts::shortcut_of) and paint it the way the menus paint theirs (menubar::shortcut_text: a symbol chord on macOS, Ctrl+... elsewhere); no key is written in the source strings any more. A command whose binding was removed shows the menu path alone. The chorded sentences move from the message catalogs into tr_format! messages (placeholders are format!-checked in every language), translated in all 17 catalogs' -formats.json; the catalog keys stay, chordless, as the no-binding fallback, and the_tour_is_translated_in_every_catalog pins both per language. * ui: the tour's Develop page names the Before/After command, not the Y key The page's prose still hard-coded Y as the before/after key: remap or remove that binding and the tour sends users to a command that no longer runs. The body now names View › Before/After Side by Side the way the other pages name their commands, and every catalog translates the new sentence with its own menu label. * ui: record the startup dialog once its input is not blocked * Keep headless UI tests independent of onboarding Assisted-by: OpenAI Codex * Tests: integration harnesses mark the app as a headless host Services has no headless field; the app does. Co-Authored-By: Claude Opus 5.5 * Tests: Find Similar waits for the worker to set the row total It lost that race twice on the Windows gate. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- apps/lightcraft-web/src/web.rs | 3 + apps/lightcraft/src/prefs.rs | 5 + apps/lightcraft/src/tests.rs | 36 +++ crates/ui-egui/locales/cs-formats.json | 3 + crates/ui-egui/locales/cs.json | 22 ++ crates/ui-egui/locales/de-formats.json | 5 +- crates/ui-egui/locales/de.json | 24 +- crates/ui-egui/locales/es-formats.json | 5 +- crates/ui-egui/locales/es.json | 24 +- crates/ui-egui/locales/fi-formats.json | 3 + crates/ui-egui/locales/fi.json | 22 ++ crates/ui-egui/locales/fr-formats.json | 5 +- crates/ui-egui/locales/fr.json | 24 +- crates/ui-egui/locales/id-formats.json | 3 + crates/ui-egui/locales/id.json | 22 ++ crates/ui-egui/locales/it-formats.json | 3 + crates/ui-egui/locales/it.json | 22 ++ crates/ui-egui/locales/ja-formats.json | 5 +- crates/ui-egui/locales/ja.json | 24 +- crates/ui-egui/locales/ka-formats.json | 3 + crates/ui-egui/locales/ka.json | 23 +- crates/ui-egui/locales/pl-formats.json | 3 + crates/ui-egui/locales/pl.json | 22 ++ crates/ui-egui/locales/pt-br-formats.json | 5 +- crates/ui-egui/locales/pt-br.json | 24 +- crates/ui-egui/locales/ru-formats.json | 5 +- crates/ui-egui/locales/ru.json | 24 +- crates/ui-egui/locales/sv-formats.json | 3 + crates/ui-egui/locales/sv.json | 22 ++ crates/ui-egui/locales/uk-formats.json | 5 +- crates/ui-egui/locales/uk.json | 24 +- crates/ui-egui/locales/vi-formats.json | 3 + crates/ui-egui/locales/vi.json | 22 ++ crates/ui-egui/locales/zh-hans-formats.json | 5 +- crates/ui-egui/locales/zh-hans.json | 24 +- crates/ui-egui/locales/zh-hant-formats.json | 5 +- crates/ui-egui/locales/zh-hant.json | 24 +- crates/ui-egui/src/app/frame.rs | 19 ++ crates/ui-egui/src/dialogs.rs | 162 +++++++++++- crates/ui-egui/src/dialogs/confirm.rs | 2 +- crates/ui-egui/src/dialogs/frame.rs | 1 + crates/ui-egui/src/i18n/tests.rs | 33 +++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/startup.rs | 242 ++++++++++++++++++ crates/ui-egui/src/state.rs | 17 ++ crates/ui-egui/src/state/dialog.rs | 6 + crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/drop_import.rs | 26 ++ crates/ui-egui/src/tests/find_similar.rs | 6 + crates/ui-egui/src/tests/lifecycle_037.rs | 7 + crates/ui-egui/src/tests/welcome.rs | 251 +++++++++++++++++++ crates/ui-egui/tests/it/accessibility.rs | 2 + crates/ui-egui/tests/it/dialog_role.rs | 3 +- crates/ui-egui/tests/it/docking_workflows.rs | 2 + crates/ui-egui/tests/it/local_places.rs | 1 + crates/ui-egui/tests/it/sidebar_names.rs | 3 + crates/ui-egui/tests/it/thumb_size_slider.rs | 1 + 57 files changed, 1269 insertions(+), 23 deletions(-) create mode 100644 crates/ui-egui/src/startup.rs create mode 100644 crates/ui-egui/src/tests/welcome.rs diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rs index 5b946c7d14..79773918b4 100644 --- a/apps/lightcraft-web/src/web.rs +++ b/apps/lightcraft-web/src/web.rs @@ -600,6 +600,9 @@ impl WebApp { let mut saved = serde_json::from_slice::(&ui_written).unwrap_or_default(); if let Some(fields) = saved.as_object_mut() { lightcraft_ui_egui::docking::drop_outdated(fields); + // a stored ui.json means an installation that has been run: due What's New, never + // the first-run tour (the same migration the desktop settings loader runs) + lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields); } if let Ok(ui) = serde_json::from_value::(saved) { app.ui = ui; diff --git a/apps/lightcraft/src/prefs.rs b/apps/lightcraft/src/prefs.rs index 5701bf1618..ba9396d36d 100644 --- a/apps/lightcraft/src/prefs.rs +++ b/apps/lightcraft/src/prefs.rs @@ -67,6 +67,11 @@ fn decode_saved_ui(bytes: &[u8]) -> Result<(UiState, bool), String> { if recovered { fields.remove("docking"); } + // A settings file from before the startup dialog existed has no `seenVersion` key: the file + // is there, so this is an installation that has been run, due What's New — never the + // first-run tour. Shared with the browser's loader, which runs the same migration on its + // stored `ui.json` (`startup::migrate_legacy_seen_version` carries the full story). + lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields); let ui = serde_json::from_value(saved).map_err(|error| error.to_string())?; Ok((ui, recovered)) } diff --git a/apps/lightcraft/src/tests.rs b/apps/lightcraft/src/tests.rs index ca90ebb5cc..e358ee15fe 100644 --- a/apps/lightcraft/src/tests.rs +++ b/apps/lightcraft/src/tests.rs @@ -223,6 +223,42 @@ fn memory_session_leaves_a_damaged_ui_json_alone() { let _ = std::fs::remove_dir_all(&d); } +/// A settings file from before the startup dialog existed (no `seenVersion`) belongs to an +/// installation that has been run: its first launch after the update shows What's New, never +/// the first-run tour. A file this version saved before the dialog was presented carries an +/// explicit `null` and is not migrated; only a missing file stays a first run as well. +#[test] +fn legacy_ui_json_shows_whats_new_not_the_first_run_tour() { + let d = dir("legacy-startup"); + let path = d.join("ui.json"); + std::fs::write(&path, br#"{"language":"en","settings":{"startupView":"detail"}}"#).unwrap(); + let (ui, warning, keep) = load_prefs_at(&path, true); + assert!(warning.is_none() && !keep); + let ui = ui.unwrap(); + assert_eq!(ui.seen_version.as_deref(), Some(lightcraft_ui_egui::startup::LEGACY_SEEN_VERSION)); + assert_eq!( + lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")), + Some(lightcraft_ui_egui::startup::StartupDialog::WhatsNew) + ); + // a file that already records the running version is migrated nowhere + std::fs::write(&path, format!(r#"{{"seenVersion":"{}"}}"#, env!("CARGO_PKG_VERSION"))).unwrap(); + let (ui, warning, _) = load_prefs_at(&path, true); + assert!(warning.is_none()); + assert_eq!(ui.unwrap().seen_version.as_deref(), Some(env!("CARGO_PKG_VERSION"))); + // an explicit `null` is this version's "not presented yet" (the launch chooser saves while + // the tour still waits): it stays a first run, not a pre-feature file + std::fs::write(&path, br#"{"language":"en","seenVersion":null}"#).unwrap(); + let (ui, warning, _) = load_prefs_at(&path, true); + assert!(warning.is_none()); + let ui = ui.unwrap(); + assert_eq!(ui.seen_version, None); + assert_eq!( + lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")), + Some(lightcraft_ui_egui::startup::StartupDialog::FirstRun) + ); + std::fs::remove_dir_all(d).unwrap(); +} + #[test] fn docking_survives_native_settings_file_reload() { use lightcraft_ui_egui::docking::Panel; diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index d642bc85ae..77c37c84fc 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -321,6 +321,9 @@ "Panel move was not applied: {error}": "Přesun panelu nebyl použit: {error}", "{name} is installed": "{name} je nainstalován", "{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto", + "Bring photos in with File › Import Photos… ({keys}).": "Fotografie importujete přes Soubor › Importovat fotografie… ({keys}).", + "View › Detail View ({keys}).": "Zobrazení › Zobrazení detailu ({keys}).", + "File › Export… · File › Print… ({keys}).": "Soubor › Exportovat… · Soubor › Tisk… ({keys}).", "{n} folder{} could not be read": "Složky, které se nepodařilo přečíst: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 5cb9ba0e45..ea10219217 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2450,5 +2450,27 @@ "Top bar": "Horní lišta", "Tool strip": "Pruh nástrojů", "Bottom bar": "Dolní lišta", + "Welcome to LightCraft": "Vítejte v LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Rychlá a nedestruktivní knihovna fotografií a vývojář RAW: originály zůstanou nedotčené a každou úpravu lze později znovu prohlédnout nebo vrátit.", + "Bring photos in with File › Import Photos…": "Fotografie importujete přes Soubor › Importovat fotografie…", + "Find and organize": "Najděte a uspořádejte", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Mřížka fotografií skládá knihovnu do zarovnaných řádků: hodnoťte, označujte barevnými štítky, filtrujte a řaďte fotografie do alb.", + "View › Photo Grid.": "Zobrazení › Mřížka fotografií.", + "Develop a photo": "Upravte fotografii", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Otevřete fotografii a upravte ji: expozice, barvy, detaily a masky, to vše nedestruktivně. Pomocí Zobrazení › Před/Po vedle sebe porovnáte stav před a po.", + "View › Detail View.": "Zobrazení › Zobrazení detailu.", + "Cull a shoot": "Vytřiďte sérii snímků", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Asistované třídění hodnotí ostrost a expozici, najde série a označí rozmazané snímky jako odmítnuté, takže nejlepší fotografie rychle vyniknou.", + "Photo › Assisted Culling…": "Fotografie › Asistované třídění…", + "Share your work": "Sdílejte svou práci", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Exportovat vytváří JPEG, PNG, TIFF, WebP a další formáty v požadované velikosti; Tisk rozloží fotografii na stránku jako PDF.", + "File › Export… · File › Print…": "Soubor › Exportovat… · Soubor › Tisk…", + "File › Export…": "Soubor › Exportovat…", + "Put agents to work": "Nechte agenty pracovat", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Vše v LightCraft je příkaz, takže AI agenti mohou přes MCP ovládat běžící aplikaci: třídit, upravovat a exportovat podle vašich pokynů.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Aplikaci spusťte s --control 7980 (nebo LIGHTCRAFT_CONTROL_PORT), poté lightcraft-cli mcp --connect připojí jednoho agenta.", + "Welcome": "Vítejte", + "Next": "Další", + "Get Started": "Začít", "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 8c119e8ec9..43d8da59b4 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -322,5 +322,8 @@ "Panel layout could not be restored: {error}": "Die Bereichsanordnung konnte nicht wiederhergestellt werden: {error}", "Panel move was not applied: {error}": "Das Verschieben des Bereichs wurde nicht ausgeführt: {error}", "{name} is installed": "{name} ist installiert", - "{name} is installed and in use: face recognition is on": "{name} ist installiert und in Gebrauch: Gesichtserkennung ist eingeschaltet" + "{name} is installed and in use: face recognition is on": "{name} ist installiert und in Gebrauch: Gesichtserkennung ist eingeschaltet", + "Bring photos in with File › Import Photos… ({keys}).": "Fotos holen Sie mit Datei › Fotos importieren… ({keys}) in die Bibliothek.", + "View › Detail View ({keys}).": "Ansicht › Detailansicht ({keys}).", + "File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys})." } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 12dae2c870..bc67606eb6 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3485,5 +3485,27 @@ "Top bar": "Obere Leiste", "Tool strip": "Werkzeugleiste", "Bottom bar": "Untere Leiste", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)", + "Welcome to LightCraft": "Willkommen bei LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Eine schnelle, zerstörungsfreie Fotobibliothek und Raw-Entwickler: Ihre Originale bleiben unberührt, und jede Bearbeitung lässt sich jederzeit ansehen oder zurücksetzen.", + "Bring photos in with File › Import Photos…": "Fotos holen Sie mit Datei › Fotos importieren…in die Bibliothek.", + "Find and organize": "Finden und ordnen", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Das Fotoraster ordnet die Bibliothek in bündigen Zeilen an: bewerten, markieren und farbig kennzeichnen, filtern und Fotos zu Alben sammeln.", + "View › Photo Grid.": "Ansicht › Fotoraster.", + "Develop a photo": "Ein Foto entwickeln", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Öffnen Sie ein Foto zum Entwickeln: Belichtung, Farbe, Details und Masken, alles zerstörungsfrei. Verwenden Sie Ansicht › Vorher/Nachher nebeneinander, um vorher und nachher zu vergleichen.", + "View › Detail View.": "Ansicht › Detailansicht.", + "Cull a shoot": "Eine Aufnahmeserie sichten", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Die Unterstützte Fotoauswahl bewertet Schärfe und Belichtung, erkennt Serienaufnahmen und markiert unscharfe Aufnahmen zum Ablehnen, damit die besten Fotos schnell auffallen.", + "Photo › Assisted Culling…": "Foto › Unterstützte Fotoauswahl…", + "Share your work": "Ihre Arbeit teilen", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Export erstellt JPEG, PNG, TIFF, WebP und weitere Formate in der gewünschten Größe; Drucken ordnet ein Foto als PDF auf einer Seite an.", + "File › Export… · File › Print…": "Datei › Exportieren… · Datei › Drucken…", + "File › Export…": "Datei › Exportieren…", + "Put agents to work": "Agenten an die Arbeit schicken", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Alles in LightCraft ist ein Befehl, daher können KI-Agenten die laufende App über MCP steuern: sortieren, bearbeiten und exportieren, auf Ihren Auftrag hin.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Starten Sie die App mit --control 7980 (oder LIGHTCRAFT_CONTROL_PORT), dann verbindet lightcraft-cli mcp --connect einen Agenten mit ihr.", + "Welcome": "Willkommen", + "Next": "Weiter", + "Get Started": "Loslegen" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 2a001f3891..bdfd440f1f 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -322,5 +322,8 @@ "Panel layout could not be restored: {error}": "No se pudo restablecer la disposición de paneles: {error}", "Panel move was not applied: {error}": "No se aplicó el movimiento del panel: {error}", "{name} is installed": "{name} está instalado", - "{name} is installed and in use: face recognition is on": "{name} está instalado y en uso: el reconocimiento facial está activado" + "{name} is installed and in use: face recognition is on": "{name} está instalado y en uso: el reconocimiento facial está activado", + "Bring photos in with File › Import Photos… ({keys}).": "Importa fotos con Archivo › Importar fotos… ({keys}).", + "View › Detail View ({keys}).": "Vista › Vista de detalle ({keys}).", + "File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys})." } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index b4aaf400a8..c34057bdfe 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2404,5 +2404,27 @@ "Top bar": "Barra superior", "Tool strip": "Barra de herramientas", "Bottom bar": "Barra inferior", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)", + "Welcome to LightCraft": "Bienvenido a LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Un gestor de fotos y revelado RAW rápido y no destructivo: tus originales permanecen intactos y cada edición se puede revisar o restablecer.", + "Bring photos in with File › Import Photos…": "Importa fotos con Archivo › Importar fotos…", + "Find and organize": "Encuentra y organiza", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "La cuadrícula de fotos organiza la biblioteca en filas justificadas: valora, marca y etiqueta por color, filtra y reúne las fotos en álbumes.", + "View › Photo Grid.": "Vista › Cuadrícula de fotos.", + "Develop a photo": "Revela una foto", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Abre una foto para revelarla: exposición, color, detalle y máscaras, todo de forma no destructiva. Usa Vista › Antes/Después lado a lado para comparar antes y después.", + "View › Detail View.": "Vista › Vista de detalle.", + "Cull a shoot": "Selecciona una sesión", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "La selección asistida valora el enfoque y la exposición, encuentra las ráfagas y marca las tomas borrosas como rechazadas, para que las mejores destaquen enseguida.", + "Photo › Assisted Culling…": "Foto › Selección asistida…", + "Share your work": "Comparte tu trabajo", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Exportar genera JPEG, PNG, TIFF, WebP y más, en el tamaño que elijas; Imprimir coloca una foto en una página como PDF.", + "File › Export… · File › Print…": "Archivo › Exportar… · Archivo › Imprimir…", + "File › Export…": "Archivo › Exportar…", + "Put agents to work": "Pon a trabajar a los agentes", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Todo en LightCraft es un comando, así que los agentes de IA pueden manejar la aplicación en marcha a través de MCP: seleccionar, editar y exportar cuando lo pidas.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicia la aplicación con --control 7980 (o LIGHTCRAFT_CONTROL_PORT), y lightcraft-cli mcp --connect conecta un agente a ella.", + "Welcome": "Bienvenido", + "Next": "Siguiente", + "Get Started": "Empezar" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 12cdf13df8..31f6c32b5d 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -318,6 +318,9 @@ "Panel move was not applied: {error}": "Paneelin siirtoa ei otettu käyttöön: {error}", "{name} is installed": "{name} on asennettu", "{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä", + "Bring photos in with File › Import Photos… ({keys}).": "Tuo kuvia valitsemalla Tiedosto › Tuo kuvia… ({keys}).", + "View › Detail View ({keys}).": "Näytä › Tarkastelunäkymä ({keys}).", + "File › Export… · File › Print… ({keys}).": "Tiedosto › Vie… · Tiedosto › Tulosta… ({keys}).", "{n} folder{} could not be read": "Kansiot, joita ei voitu lukea: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index d5dc27d8c0..59cc611cd6 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2151,6 +2151,28 @@ "Virtual Copy": "Virtuaalikopio", "Visible": "Näkyvä", "Visualize HDR": "Havainnollista HDR", + "Welcome to LightCraft": "Tervetuloa LightCraftiin", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Nopea, ei-tuhova kuvakirjasto ja RAW-kehittäjä: alkuperäiset tiedostot säilyvät koskemattomina, ja jokaiseen muokkaukseen voi palata tai sen voi nollata.", + "Bring photos in with File › Import Photos…": "Tuo kuvia valitsemalla Tiedosto › Tuo kuvia…", + "Find and organize": "Etsi ja järjestä", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Kuvaruudukko asettelee kirjaston tasattuihin riveihin: arvioi, merkitse ja väritä kuvia, suodata ja kokoaa niitä albumeihin.", + "View › Photo Grid.": "Näytä › Kuvaruudukko.", + "Develop a photo": "Kehitä kuva", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Avaa kuva kehitettäväksi: valotus, väri, yksityiskohdat ja maskit, kaikki ei-tuhovaa. Käytä Näytä › Ennen/jälkeen vierekkäin ennen- ja jälkikuvan vertailuun.", + "View › Detail View.": "Näytä › Tarkastelunäkymä.", + "Cull a shoot": "Karsi kuvaus", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Avustettu valinta pisteyttää terävyyden ja valotuksen, tunnistaa kuvasarjat ja merkitsee sumeat kuvat hylätyiksi, jotta parhaat nousevat nopeasti esille.", + "Photo › Assisted Culling…": "Kuva › Avustettu valinta…", + "Share your work": "Jaa työsi", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Vienti tuottaa JPEG-, PNG-, TIFF-, WebP- ja muita tiedostomuotoja haluamassasi koossa; Tulostus somittaa kuvan sivulle PDF:nä.", + "File › Export… · File › Print…": "Tiedosto › Vie… · Tiedosto › Tulosta…", + "File › Export…": "Tiedosto › Vie…", + "Put agents to work": "Pane agentit töihin", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Kaikki LightCraftissa on komento, joten tekoälyagentit voivat ohjata käynnissä olevaa sovellusta MCP:n kautta: karsintaa, kehitystä ja vientiä käskystäsi.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Käynnistä sovellus valitsimella --control 7980 (tai LIGHTCRAFT_CONTROL_PORT), minkä jälkeen lightcraft-cli mcp --connect yhdistää siihen yhden agentin.", + "Welcome": "Tervetuloa", + "Next": "Seuraava", + "Get Started": "Aloitetaan", "Visualize Spots": "Havainnollista täplät", "Visualize Spots (A)": "Havainnollista täplät (A)", "Visualize range": "Havainnollista alue", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index cc78f8331e..16782e3499 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -322,5 +322,8 @@ "Panel layout could not be restored: {error}": "La disposition des panneaux n'a pas pu être restaurée : {error}", "Panel move was not applied: {error}": "Le déplacement du panneau n'a pas été appliqué : {error}", "{name} is installed": "{name} est installé", - "{name} is installed and in use: face recognition is on": "{name} est installé et utilisé : la reconnaissance des visages est activée" + "{name} is installed and in use: face recognition is on": "{name} est installé et utilisé : la reconnaissance des visages est activée", + "Bring photos in with File › Import Photos… ({keys}).": "Importez des photos avec Fichier › Importer des photos… ({keys}).", + "View › Detail View ({keys}).": "Affichage › Vue de détail ({keys}).", + "File › Export… · File › Print… ({keys}).": "Fichier › Exporter… · Fichier › Imprimer… ({keys})." } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 8406d3e2ae..31e6814b6d 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3587,5 +3587,27 @@ "Top bar": "Barre supérieure", "Tool strip": "Barre d’outils", "Bottom bar": "Barre inférieure", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)", + "Welcome to LightCraft": "Bienvenue dans LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Une bibliothèque photo rapide et non destructive, et un outil de développement RAW : vos originaux restent intacts, et chaque modification peut être revue ou annulée.", + "Bring photos in with File › Import Photos…": "Importez des photos avec Fichier › Importer des photos…", + "Find and organize": "Trouver et organiser", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "La grille de photos organise la bibliothèque en rangées alignées : notez, marquez et étiquetez par couleur, filtrez, et regroupez les photos en albums.", + "View › Photo Grid.": "Affichage › Grille de photos.", + "Develop a photo": "Développer une photo", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Ouvrez une photo pour la développer : exposition, couleur, détails et masques, le tout de façon non destructive. Utilisez Affichage › Avant/Après côte à côte pour comparer avant et après.", + "View › Detail View.": "Affichage › Vue de détail.", + "Cull a shoot": "Trier une séance", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Le tri assisté évalue la netteté et l'exposition, repère les rafales et marque les photos floues comme rejetées, pour que les meilleures ressortent vite.", + "Photo › Assisted Culling…": "Photo › Tri assisté…", + "Share your work": "Partager votre travail", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "L'export produit du JPEG, PNG, TIFF, WebP et d'autres formats, à la taille voulue ; Imprimer met une photo en page sur une feuille au format PDF.", + "File › Export… · File › Print…": "Fichier › Exporter… · Fichier › Imprimer…", + "File › Export…": "Fichier › Exporter…", + "Put agents to work": "Mettre les agents au travail", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Tout dans LightCraft est une commande : des agents IA peuvent piloter l'application en cours via MCP, pour trier, modifier et exporter à votre demande.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Démarrez l'application avec --control 7980 (ou LIGHTCRAFT_CONTROL_PORT), puis lightcraft-cli mcp --connect y connecte un agent.", + "Welcome": "Bienvenue", + "Next": "Suivant", + "Get Started": "Commencer" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 85c06ed3e1..7bd027cc35 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -321,6 +321,9 @@ "Creates {stacks} stack{} from {photos} of {scope}": "Membuat {stacks} tumpukan dari {photos} foto ({scope}){:.0}", "{n} selected photo{} · {pages} page{}": "{n} foto dipilih · {pages} halaman{:.0}{:.0}", "{n} photo{} in view · {slides} slide{} · {time}": "{n} foto di tampilan · {slides} slide · {time}{:.0}{:.0}", + "Bring photos in with File › Import Photos… ({keys}).": "Masukkan foto melalui File › Impor foto… ({keys}).", + "View › Detail View ({keys}).": "Tampilan › Tampilan Detail ({keys}).", + "File › Export… · File › Print… ({keys}).": "File › Ekspor… · File › Cetak… ({keys}).", "{n} folder{} could not be read": "Folder yang tidak bisa dibaca: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 8805697868..52705328cc 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2145,6 +2145,28 @@ "Virtual Copy": "Salinan virtual", "Visible": "Terlihat", "Visualize HDR": "Visualisasikan HDR", + "Welcome to LightCraft": "Selamat datang di LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Pustaka foto yang cepat dan pengembangan raw yang non-destruktif: berkas asli Anda tetap tak tersentuh, dan setiap penyuntingan dapat ditinjau ulang atau diatur ulang.", + "Bring photos in with File › Import Photos…": "Masukkan foto melalui File › Impor foto…", + "Find and organize": "Temukan dan rapikan", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Grid foto menyusun pustaka menjadi baris yang rapi: beri peringkat, tandai dan beri label warna, saring, serta kumpulkan foto ke dalam album.", + "View › Photo Grid.": "Tampilan › Grid foto.", + "Develop a photo": "Kembangkan satu foto", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Buka foto untuk mengembangkannya: eksposur, warna, detail dan masker, semuanya non-destruktif. Gunakan Tampilan › Sebelum/Sesudah berdampingan untuk membandingkan sebelum dan sesudah.", + "View › Detail View.": "Tampilan › Tampilan Detail.", + "Cull a shoot": "Seleksi hasil pemotretan", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Seleksi foto berbantuan memberi skor fokus dan eksposur, menemukan rangkaian foto, dan menandai foto buram sebagai ditolak, sehingga foto terbaik tampil lebih cepat.", + "Photo › Assisted Culling…": "Foto › Seleksi foto berbantuan…", + "Share your work": "Bagikan karya Anda", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Ekspor menghasilkan JPEG, PNG, TIFF, WebP dan lainnya, dengan ukuran sesuai keinginan; Cetak menata foto pada halaman sebagai PDF.", + "File › Export… · File › Print…": "File › Ekspor… · File › Cetak…", + "File › Export…": "File › Ekspor…", + "Put agents to work": "Pekerjakan agen", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Semua di LightCraft adalah perintah, sehingga agen AI dapat mengendalikan aplikasi yang berjalan melalui MCP: seleksi, pengembangan, dan ekspor atas perintah Anda.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Jalankan aplikasi dengan --control 7980 (atau LIGHTCRAFT_CONTROL_PORT), lalu lightcraft-cli mcp --connect menghubungkan satu agen kepadanya.", + "Welcome": "Selamat Datang", + "Next": "Berikutnya", + "Get Started": "Mulai", "Visualize Spots": "Visualisasikan bintik", "Visualize Spots (A)": "Visualisasikan bintik (A)", "Visualize range": "Visualisasikan rentang", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index c3227a1aa4..922bac810d 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -321,6 +321,9 @@ "Panel move was not applied: {error}": "Lo spostamento del pannello non è stato applicato: {error}", "{name} is installed": "{name} è installato", "{name} is installed and in use: face recognition is on": "{name} è installato e in uso: il riconoscimento dei volti è attivo", + "Bring photos in with File › Import Photos… ({keys}).": "Importa le foto con File › Importa foto… ({keys}).", + "View › Detail View ({keys}).": "Visualizza › Vista dettaglio ({keys}).", + "File › Export… · File › Print… ({keys}).": "File › Esporta… · File › Stampa… ({keys}).", "{n} folder{} could not be read": "Cartelle non leggibili: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 617b0d9fea..5b0ccc0cee 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2568,5 +2568,27 @@ "Top bar": "Barra superiore", "Tool strip": "Barra degli strumenti", "Bottom bar": "Barra inferiore", + "Welcome to LightCraft": "Benvenuto in LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Una libreria fotografica veloce e non distruttiva, e uno sviluppatore RAW: gli originali restano intatti e ogni modifica si può rivedere o annullare.", + "Bring photos in with File › Import Photos…": "Importa le foto con File › Importa foto…", + "Find and organize": "Trova e organizza", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "La Griglia foto dispone la libreria in righe allineate: valuta, contrassegna ed etichetta per colore, filtra e raccogli le foto negli album.", + "View › Photo Grid.": "Visualizza › Griglia foto.", + "Develop a photo": "Sviluppa una foto", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Apri una foto per svilupparla: esposizione, colore, dettagli e maschere, tutto in modo non distruttivo. Usa Visualizza › Prima/Dopo affiancati per confrontare prima e dopo.", + "View › Detail View.": "Visualizza › Vista dettaglio.", + "Cull a shoot": "Seleziona una sessione", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "La Selezione assistita valuta messa a fuoco ed esposizione, trova le serie di scatti e segna come scartate le foto mosse, così le migliori emergono subito.", + "Photo › Assisted Culling…": "Foto › Selezione assistita…", + "Share your work": "Condividi il tuo lavoro", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Esporta crea JPEG, PNG, TIFF, WebP e altri formati, nella dimensione che preferisci; Stampa impagina una foto su una pagina come PDF.", + "File › Export… · File › Print…": "File › Esporta… · File › Stampa…", + "File › Export…": "File › Esporta…", + "Put agents to work": "Metti al lavoro gli agenti", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Tutto in LightCraft è un comando, quindi gli agenti IA possono controllare l'app in esecuzione tramite MCP: selezionare, modificare ed esportare su tua richiesta.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Avvia l'app con --control 7980 (o LIGHTCRAFT_CONTROL_PORT), poi lightcraft-cli mcp --connect vi collega un agente.", + "Welcome": "Benvenuto", + "Next": "Avanti", + "Get Started": "Inizia", "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 2cf2c0f83a..bc6ce0e60a 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -322,5 +322,8 @@ "Panel layout could not be restored: {error}": "パネル配置を復元できませんでした:{error}", "Panel move was not applied: {error}": "パネルの移動は適用されませんでした:{error}", "{name} is installed": "{name} をインストールしました", - "{name} is installed and in use: face recognition is on": "{name} をインストールして使用中です:顔認識はオンです" + "{name} is installed and in use: face recognition is on": "{name} をインストールして使用中です:顔認識はオンです", + "Bring photos in with File › Import Photos… ({keys}).": "ファイル › 写真を読み込む… ({keys}) で写真を読み込みます。", + "View › Detail View ({keys}).": "表示 › 詳細表示 ({keys})。", + "File › Export… · File › Print… ({keys}).": "ファイル › 書き出す… · ファイル › 印刷… ({keys})。" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 9178aad528..97c15dd019 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2402,5 +2402,27 @@ "Top bar": "上部バー", "Tool strip": "ツールバー", "Bottom bar": "下部バー", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)", + "Welcome to LightCraft": "LightCraft へようこそ", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "高速で非破壊の写真ライブラリと RAW 現像ソフトです。元の写真は変わらず、どの編集もあとから見直したり元に戻したりできます。", + "Bring photos in with File › Import Photos…": "ファイル › 写真を読み込む…で写真を読み込みます。", + "Find and organize": "見つけて整理", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "写真グリッドは、写真を高さのそろった行に並べます。評価、旗、カラーラベルを付けたり、絞り込んだり、写真をアルバムにまとめたりできます。", + "View › Photo Grid.": "表示 › 写真グリッド。", + "Develop a photo": "写真を現像する", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "写真を開いて現像します。露出、色、ディテール、マスクをすべて非破壊で調整できます。表示 › 編集前/編集後の左右表示で編集前と編集後を比べられます。", + "View › Detail View.": "表示 › 詳細表示。", + "Cull a shoot": "撮影分を選別する", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "写真の選別を補助する機能は、ピントと露出を採点し、連写をまとめ、ぶれた写真を不採用にするので、残す写真がすぐ見つかります。", + "Photo › Assisted Culling…": "写真 › 写真の選別を補助…", + "Share your work": "作品を共有する", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "書き出しは JPEG、PNG、TIFF、WebP などを好みのサイズで出力します。印刷は、写真をページに配置して PDF にします。", + "File › Export… · File › Print…": "ファイル › 書き出す… · ファイル › 印刷…", + "File › Export…": "ファイル › 書き出す…", + "Put agents to work": "エージェントに仕事を任せる", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "LightCraft のすべての操作はコマンドなので、AI エージェントは MCP 経由で起動中のアプリを操作できます。選別、編集、書き出しをあなたの指示どおりに行えます。", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "アプリを --control 7980 (または LIGHTCRAFT_CONTROL_PORT) で起動してから、lightcraft-cli mcp --connect でエージェントを接続できます。", + "Welcome": "ようこそ", + "Next": "次へ", + "Get Started": "始める" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index c058aa9b04..b13dc07d30 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -324,6 +324,9 @@ "Panel move was not applied: {error}": "პანელის გადატანა არ შესრულდა: {error}", "{name} is installed": "{name} დაინსტალირებულია", "{name} is installed and in use: face recognition is on": "{name} დაინსტალირებულია და გამოიყენება: სახეების ამოცნობა ჩართულია", + "Bring photos in with File › Import Photos… ({keys}).": "ფოტოების შემოსატანად გამოიყენეთ ფაილი › ფოტოების იმპორტი… ({keys}).", + "View › Detail View ({keys}).": "ხედი › დეტალური ხედი ({keys}).", + "File › Export… · File › Print… ({keys}).": "ფაილი › ექსპორტი… · ფაილი › დაბეჭდვა… ({keys}).", "{n} folder{} could not be read": "საქაღალდეები, რომლებიც ვერ წაიკითხა: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index e7e3e6e9c5..30769b60fa 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -62,6 +62,7 @@ "A blank template keeps the original names.": "ცარიელი შაბლონი ორიგინალ სახელებს ინარჩუნებს.", "A change that can't be saved to disk (full or unplugged drive) is no longer silent: the command reports": "ცვლილება, რომლის დისკზე შენახვაც ვერ ხერხდება (სავსე ან გამორთული დისკი), აღარ რჩება შეუმჩნეველი: ბრძანება იტყობინება", "A dialog taller than the window no longer runs off it (issue #781): on a 1366×768 screen the Export dialog's title": "ფანჯარაზე მაღალი დიალოგი აღარ გადის მის საზღვრებს გარეთ (ხარვეზი #781): 1366×768 ეკრანზე ექსპორტის დიალოგის სათაური", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "სწრაფი, არადესტრუქციული ფოტობიბლიოთეკა და RAW-დამუშავების ინსტრუმენტი: ორიგინალები უცვლელი რჩება, ყოველი რედაქტირების ნახვა ან გაუქმება კი შესაძლებელია.", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "ფილტრი მალავს ამ ხედის ფოტოებს: შეცვალეთ ან გაასუფთავეთ იგი (ხედი → ფილტრების გასუფთავება)", "A folder is already being synchronized": "საქაღალდე უკვე სინქრონიზდება", "A folder is being synchronized": "საქაღალდე სინქრონიზდება", @@ -198,6 +199,7 @@ "Aspect Ratio": "თანაფარდობა", "Aspect Ratio (a 24 MP photo cropped to a square is 16 MP).": "თანაფარდობა (24 MP ფოტო, კვადრატად ჩამოჭრილი, 16 MP-ია).", "Assisted Culling": "დამხმარე გადარჩევა", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "დამხმარე გადარჩევა აფასებს ფოკუსსა და ექსპოზიციას, პოულობს სერიებს და ბუნდოვან კადრებს უარყოფილებად მონიშნავს, რომ საუკეთესო ფოტოები სწრაფად გამოჩნდეს.", "Assisted Culling…": "დამხმარე გადარჩევა…", "Auto": "ავტომატური", "Auto Advance": "ავტომატური გადასვლა", @@ -277,6 +279,7 @@ "Bridge and Photo Supreme (its Formatted Vocabulary File) use the same files, so keyword lists move between them and": "Bridge და Photo Supreme (მისი Formatted Vocabulary File) იმავე ფაილებს იყენებს, ასე რომ საკვანძო სიტყვების სიები მათსა და", "Bright & Airy": "ნათელი და ჰაეროვანი", "Bring All to Front": "ყველას წინა პლანზე გადატანა", + "Bring photos in with File › Import Photos…": "ფოტოების შემოსატანად გამოიყენეთ ფაილი › ფოტოების იმპორტი…", "Bring the library up to date with this folder and the folders inside it:": "ბიბლიოთეკის განახლება ამ საქაღალდისა და მასში არსებული საქაღალდეების მიხედვით:", "Browse Folder": "საქაღალდის დათვალიერება", "Browse Folder…": "საქაღალდის დათვალიერება…", @@ -500,6 +503,7 @@ "Crop, Rotate, Geometry": "ჩამოჭრა, შემობრუნება, გეომეტრია", "Cropped": "ჩამოჭრილი", "Cross Process": "ჯვარედინი დამუშავება", + "Cull a shoot": "სერიის გადარჩევა", "Culling": "გადარჩევა", "Cull": "გადარჩევა", "Create Stacks": "დასტების შექმნა", @@ -594,6 +598,7 @@ "Detect Faces": "სახეების ამოცნობა", "Detect Faces (Photo menu) needs it: a small one-time download.": "სახეების ამოცნობას (მენიუ „ფოტო“) ეს სჭირდება: მცირე, ერთჯერადი ჩამოტვირთვა.", "Develop": "დამუშავება", + "Develop a photo": "ფოტოს დამუშავება", "Diagonal": "დიაგონალური", "Dialogs": "დიალოგები", "Dialogs fit the window": "დიალოგები ფანჯარაში ეტევა", @@ -690,6 +695,7 @@ "Erase": "წაშლა", "Evaluate Face Recognition": "სახეების ამოცნობის შეფასება", "Every EXIF, GPS and XMP field in the file": "ფაილის ყველა EXIF, GPS და XMP ველი", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "LightCraft-ში ყველაფერი ბრძანებაა, ამიტომ AI აგენტებს MCP-ის მეშვეობით შეუძლიათ გაშვებული აპლიკაციის მართვა: გადარჩევა, რედაქტირება და ექსპორტი თქვენი მითითებით.", "Existing previews": "არსებული წინასწარი ხედები", "Existing smart previews are refreshed when their originals are online, and cached renders are redrawn.": "არსებული ჭკვიანი წინასწარი ხედები ახლდება, როცა მათი ორიგინალები ხელმისაწვდომია, ხოლო ქეშირებული რენდერები ხელახლა იხატება.", "Exit": "გასვლა", @@ -716,6 +722,7 @@ "Export as JPEG XL (issue #247): Format ▸ JPEG XL in the Export dialog, `format: \"jxl\"` for agents and the CLI": "ექსპორტი JPEG XL-ად (ხარვეზი #247): ფორმატი → JPEG XL ექსპორტის დიალოგში, `format: \"jxl\"` აგენტებისა და CLI-სთვის", "Export can write PSD too (flat, 8- or 16-bit).": "ექსპორტს PSD-ის ჩაწერაც შეუძლია (ერთშრიანი, 8 ან 16 ბიტი).", "Export file names use the Rename Photos tokens ({title}, {seq:2}, {date:%Y-%m-%d}…), plus new {num}, {folder}, {lens}, {iso}, {rating}, {creator}.": "ექსპორტირებული ფაილების სახელები იყენებს ფოტოების გადარქმევის ტეგებს ({title}, {seq:2}, {date:%Y-%m-%d}…) და ახალ {num}, {folder}, {lens}, {iso}, {rating}, {creator}-ს.", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "ექსპორტი ქმნის JPEG, PNG, TIFF, WebP და სხვა ფორმატებს სასურველი ზომით; დაბეჭდვა ფოტოს PDF-ად გვერდზე განათავსებს.", "Export stopped unexpectedly": "ექსპორტი მოულოდნელად შეწყდა", "Export with Preset": "ექსპორტი პრესეტით", "Export with Previous": "ექსპორტი წინა პარამეტრებით", @@ -764,6 +771,8 @@ "File extensions match whatever their letter case: `IMG_0001.JPG` and `DSC_0002.NEF` as Nikon writes them, `.Jpg`": "ფაილის გაფართოებები ემთხვევა ასოთა რეგისტრის მიუხედავად: `IMG_0001.JPG` და `DSC_0002.NEF`, როგორც Nikon წერს, `.Jpg`", "File name": "ფაილის სახელი", "File types:": "ფაილის ტიპები:", + "File › Export… · File › Print…": "ფაილი › ექსპორტი… · ფაილი › დაბეჭდვა…", + "File › Export…": "ფაილი › ექსპორტი…", "File → Import Lightroom Catalog… opens `.lrcat` directly, with originals referenced in place.": "ფაილი → Lightroom-ის კატალოგის იმპორტი… პირდაპირ ხსნის `.lrcat`-ს, ორიგინალებზე მათ ადგილას მიმართვით.", "File ▸ Import Keywords… and Export Keywords… read and write keyword list files as Lightroom Classic does (a keyword": "ფაილი → საკვანძო სიტყვების იმპორტი… და საკვანძო სიტყვების ექსპორტი… კითხულობს და წერს საკვანძო სიტყვების სიის ფაილებს, როგორც Lightroom Classic (თითო საკვანძო სიტყვა", "File ▸ New Library… asks for a name, then where to put it, and opens the new library (issue #902).": "ფაილი → ახალი ბიბლიოთეკა… ითხოვს სახელს, შემდეგ მდებარეობას და ხსნის ახალ ბიბლიოთეკას (ხარვეზი #902).", @@ -789,6 +798,7 @@ "Find Missing Photos": "დაკარგული ფოტოების მოძებნა", "Find Missing Photos…": "დაკარგული ფოტოების მოძებნა…", "Find Similar Photos": "მსგავსი ფოტოების მოძებნა", + "Find and organize": "მოძებნეთ და დაალაგეთ", "Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps": "ამ საქაღალდეში დისკზე დამატებული ან მისგან გამქრალი ფოტოების და სხვა აპების მიერ შეცვლილი XMP თანმხლები ფაილების მოძებნა", "Find tools and commands…": "ხელსაწყოებისა და ბრძანებების ძებნა…", "Finding faces": "სახეების ძებნა", @@ -854,6 +864,7 @@ "Generated demo photo": "სადემონსტრაციო ფოტო", "Geometry": "გეომეტრია", "Get Develop Settings": "დამუშავების პარამეტრების აღება", + "Get Started": "დაწყება", "Global Hue": "გლობალური ფერის ტონი", "Global Luminance": "გლობალური სიკაშკაშე", "Global Saturation": "გლობალური გაჯერება", @@ -1314,6 +1325,7 @@ "New name": "ახალი სახელი", "New time": "ახალი დრო", "New…": "ახალი…", + "Next": "შემდეგი", "Next Appearance Mode": "შემდეგი იერსახის რეჟიმი", "Next History Step": "ისტორიის შემდეგი ნაბიჯი", "Next Keyword Set": "საკვანძო სიტყვების შემდეგი ნაკრები", @@ -1409,6 +1421,7 @@ "Open Log Folder": "ჟურნალების საქაღალდის გახსნა", "Open Original in Other Editor (RAW, no copy)": "ორიგინალის გახსნა სხვა რედაქტორში (RAW, ასლის გარეშე)", "Open Recent Library": "ბოლოს გახსნილი ბიბლიოთეკის გახსნა", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "გახსენით ფოტო დასამუშავებლად: ექსპოზიცია, ფერი, დეტალები და ნიღბები, ყველაფერი არადესტრუქციულად. გამოიყენეთ ხედი › მანამდე/შემდეგ გვერდიგვერდ დამუშავებამდე და დამუშავების შემდეგ შედარებისთვის.", "Open in": "გახსნა:", "Open in Detail": "დეტალურ ხედში გახსნა", "Open page": "გვერდის გახსნა", @@ -1487,6 +1500,7 @@ "Photo Merge": "ფოტოების გაერთიანება", "Photo Merge of Canon CR2 (and other raws whose colour LightCraft fits from the camera's own JPEG, such as NEF and": "Canon CR2-ის (და სხვა RAW ფაილების, რომელთა ფერსაც LightCraft კამერის საკუთარი JPEG-იდან არგებს, როგორიცაა NEF და", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "„ფოტო“ მენიუში. კადრების ზოლსაც აქვს ფოტოს კონტექსტური მენიუ. ახლახან წაშლილში მყოფი ფაილის ხელახლა დამატება აღარ", + "Photo › Assisted Culling…": "ფოტო › დამხმარე გადარჩევა…", "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "ფოტო → რედაქტირება სხვა პროგრამაში → რედაქტირება PhotoCraft-ში (⇧⌘E, ან მარჯვენა დაწკაპუნება ფოტოზე) არენდერებს ასლს თქვენი ცვლილებებით, ორიგინალთან ერთ დასტაში აერთიანებს და PhotoCraft-ში ხსნის. იქ შენახვისას ასლი აქაც განახლდება. PSD-ის შემთხვევაში PhotoCraft პირდაპირ მასში ინახავს. მდებარეობა ცარიელი დატოვეთ, თუ პორტატულ ასლს არ იყენებთ.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "ფოტო → რედაქტირება გარე რედაქტორში (⇧⌘E) ქმნის 16-ბიტიან TIFF ასლს, ორიგინალთან ერთად დასტაში აერთიანებს და აქ ხსნის (macOS-ზე აპის სახელი, სხვაგან — პროგრამის მისამართი).", "Photos": "ფოტოები", @@ -1577,7 +1591,7 @@ "Set Keyword Shortcut…": "საკვანძო სიტყვების მალსახმობის დაყენება…", "Add or Remove Keyword Shortcut": "საკვანძო სიტყვების მალსახმობის დამატება ან მოხსნა", "Keyword Shortcut": "საკვანძო სიტყვების მალსახმობი", - "Part of the keyword shortcut": "საკვანძო სიტყვების მალსახმობის ნაწილი", + "Part of the keyword shortcut": "საკვანძო სიტყვების მალსახმობის ნაწილი", "Put agents to work": "აგენტების სამუშაოზე დაყენება", "Put the locations you removed from Local back (no files change)": "ლოკალურიდან მოშორებული მდებარეობების დაბრუნება (ფაილები არ იცვლება)", "Quality": "ხარისხი", "Query Photos": "ფოტოების მოთხოვნა", @@ -1903,6 +1917,7 @@ "Shadows Saturation": "ჩრდილების გაჯერება", "Shadows Tint": "ჩრდილების ტონირება", "Shadows split": "ჩრდილების გაყოფა", + "Share your work": "გააზიარეთ თქვენი ნამუშევარი", "Sharpen": "გამკვეთრება", "Sharpening": "გამკვეთრება", "Sharpness": "სიმკვეთრე", @@ -2096,6 +2111,7 @@ "The Hasselblad Lunar's raws (a Sony NEX-7 inside) now develop from their sensor data with every editing tool,": "Hasselblad Lunar-ის (შიგნით Sony NEX-7) RAW ფაილები ახლა სენსორის მონაცემებიდან მუშავდება ყველა რედაქტირების ხელსაწყოთი,", "The Import Photos review opens bigger and can be resized; its photo grid fills it (issue #337). Shift-click checks": "ფოტოების იმპორტის მიმოხილვა უფრო დიდი იხსნება და მისი ზომის შეცვლა შეიძლება; ფოტოების ბადე მას ავსებს (ხარვეზი #337). Shift-დაწკაპუნება", "The Keywords panel ends with a Keyword List, as in Lightroom Classic: every keyword with its photo count, those no": "საკვანძო სიტყვების პანელი საკვანძო სიტყვების სიით სრულდება, როგორც Lightroom Classic-ში: ყველა საკვანძო სიტყვა ფოტოების რაოდენობით, მათ შორის ისეთებიც,", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "ფოტოების ბადე ბიბლიოთეკას სწორი რიგებით აწყობს: შეაფასეთ, მონიშნეთ დროშებით და ფერებით, გაფილტრეთ და ფოტოები ალბომებად შეაგროვეთ.", "The Presets panel builds only the rows in view (and their thumbnails) instead of every preset on every frame; the": "პრესეტების პანელი აგებს მხოლოდ ხილულ რიგებს (და მათ ესკიზებს) ყოველ კადრზე ყველა პრესეტის ნაცვლად;", "The SAM 3 model is installed: Object and Describe masks are ready.": "SAM 3 მოდელი დაინსტალირებულია: „ობიექტის“ და „აღწერის“ ნიღბები მზადაა.", "The Tint slider works the right way round (issues #188, #321): left adds green, right adds magenta, as its track": "ტონირების სლაიდერი სწორი მიმართულებით მუშაობს (ხარვეზები #188, #321): მარცხნივ მწვანეს ამატებს, მარჯვნივ მეწამულს, როგორც მისი ზოლი", @@ -2233,6 +2249,8 @@ "Video Duration": "ვიდეოს ხანგრძლივობა", "Videos": "ვიდეოები", "View": "ხედი", + "View › Detail View.": "ხედი › დეტალური ხედი.", + "View › Photo Grid.": "ხედი › ფოტოების ბადე.", "Viewing and sharing": "ნახვა და გაზიარება", "Vignette": "ვინიეტი", "Vignetting": "ვინიეტირება", @@ -2257,6 +2275,8 @@ "We": "ოთხ", "Web / Portfolio": "ვებ / პორტფოლიო", "Wednesday": "ოთხშაბათი", + "Welcome": "მოგესალმებით", + "Welcome to LightCraft": "კეთილი იყოს მობრძანება LightCraft-ში", "What's New": "რა არის ახალი", "When GPU rendering is on but no graphics processor can be found, LightCraft now says so once at start-up instead": "როცა GPU რენდერი ჩართულია, მაგრამ გრაფიკული პროცესორი ვერ მოიძებნა, LightCraft ახლა ამას გაშვებისას ერთხელ გეუბნებათ, ნაცვლად იმისა,", "When a folder holds several file types, the Import Photos review has a toggle per type (`ARW · 120`, `JPG · 120`):": "როცა საქაღალდეში რამდენიმე ტიპის ფაილია, ფოტოების იმპორტის მიმოხილვას თითო ტიპზე გადამრთველი აქვს (`ARW · 120`, `JPG · 120`):", @@ -2522,6 +2542,7 @@ "library open now stays, and LightCraft says \"This is a Lightroom catalog, not a LightCraft library\" and offers": "გახსნილი ბიბლიოთეკა რჩება, LightCraft კი ამბობს: „ეს Lightroom-ის კატალოგია და არა LightCraft-ის ბიბლიოთეკა“ და გთავაზობთ", "library) are written atomically and saved as soon as you open another library, not only at quit. Quitting while": "ბიბლიოთეკა) ატომურად იწერება და ინახება, როგორც კი სხვა ბიბლიოთეკას გახსნით, და არა მხოლოდ გასვლისას. გასვლა, როცა", "light: Silver or Paper). New and existing installs stay dark; following the system is opt-in.": "ღია: ვერცხლისფერი ან ქაღალდი). ახალი და არსებული ინსტალაციები ბნელი რჩება; სისტემის მიყოლა არჩევითია.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "გაუშვით აპლიკაცია --control 7980 (ან LIGHTCRAFT_CONTROL_PORT) პარამეტრით, შემდეგ lightcraft-cli mcp --connect მას ერთ აგენტთან აკავშირებს.", "like a photo that can't be opened, with the reason, instead of rendering forever; its thumbnail stops waiting too.": "როგორც ფოტო, რომლის გახსნაც შეუძლებელია, მიზეზით, უსასრულო რენდერის ნაცვლად; მისი ესკიზიც წყვეტს ლოდინს.", "like the HDR AVIF: the same brightness, with SDR white at 203 cd/m², and content light levels recorded.": "როგორც HDR AVIF: იგივე სიკაშკაშე, SDR თეთრით 203 cd/m²-ზე, და ჩაწერილი შიგთავსის სინათლის დონეებით.", "lit by the chosen white comes out grey and saturated colours move as the camera records them. The eyedropper and": "თეთრით განათებული ნაცრისფერი ნაცრისფერი გამოდის, გაჯერებული ფერები კი ისე იცვლება, როგორც კამერა ჩაწერს. პიპეტი და", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 3ca9d0503d..f03219ae1e 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -321,6 +321,9 @@ "Panel move was not applied: {error}": "Przeniesienie panelu nie zostało zastosowane: {error}", "{name} is installed": "{name} jest zainstalowany", "{name} is installed and in use: face recognition is on": "{name} jest zainstalowany i używany: rozpoznawanie twarzy jest włączone", + "Bring photos in with File › Import Photos… ({keys}).": "Zdjęcia importujesz przez Plik › Importuj zdjęcia… ({keys}).", + "View › Detail View ({keys}).": "Widok › Widok szczegółów ({keys}).", + "File › Export… · File › Print… ({keys}).": "Plik › Eksportuj… · Plik › Drukuj… ({keys}).", "{n} folder{} could not be read": "Nie udało się odczytać folderów: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 27eca8dfc1..dbc29a1941 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2326,5 +2326,27 @@ "Top bar": "Górny pasek", "Tool strip": "Pasek narzędzi", "Bottom bar": "Dolny pasek", + "Welcome to LightCraft": "Witamy w LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Szybka biblioteka zdjęć i nieniszczący program do obróbki RAW: oryginały pozostają nietknięte, a każdą edycję można później obejrzeć lub cofnąć.", + "Bring photos in with File › Import Photos…": "Zdjęcia importujesz przez Plik › Importuj zdjęcia…", + "Find and organize": "Znajdź i uporządkuj", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Siatka zdjęć układa bibliotekę w równe rzędy: oceniaj, oznaczaj flagami i kolorami, filtruj i zbieraj zdjęcia w albumach.", + "View › Photo Grid.": "Widok › Siatka zdjęć.", + "Develop a photo": "Obrób zdjęcie", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Otwórz zdjęcie, by je obrobić: ekspozycja, kolor, szczegóły i maski, wszystko w sposób nieniszczący. Użyj Widok › Przed/Po obok siebie, by porównać przed i po.", + "View › Detail View.": "Widok › Widok szczegółów.", + "Cull a shoot": "Wybierz zdjęcia z sesji", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Wspomagana selekcja ocenia ostrość i ekspozycję, wykrywa serie i oznacza rozmyte ujęcia jako odrzucone, dzięki czemu najlepsze zdjęcia szybko się wyróżniają.", + "Photo › Assisted Culling…": "Zdjęcie › Wspomagana selekcja…", + "Share your work": "Udostępnij swoją pracę", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Eksport zapisuje JPEG, PNG, TIFF, WebP i inne formaty w wybranym rozmiarze; Drukuj układa zdjęcie na stronie jako PDF.", + "File › Export… · File › Print…": "Plik › Eksportuj… · Plik › Drukuj…", + "File › Export…": "Plik › Eksportuj…", + "Put agents to work": "Zaprzęgnij agentów do pracy", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Wszystko w LightCraft to polecenia, dlatego agenci AI mogą sterować działającą aplikacją przez MCP: wybierać zdjęcia, edytować je i eksportować na twoje polecenie.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Uruchom aplikację z --control 7980 (lub LIGHTCRAFT_CONTROL_PORT), a lightcraft-cli mcp --connect podłączy do niej jednego agenta.", + "Welcome": "Witamy", + "Next": "Dalej", + "Get Started": "Zaczynamy", "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 5ac3194d78..cecd8149c0 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -322,5 +322,8 @@ "Panel layout could not be restored: {error}": "Não foi possível restaurar a disposição dos painéis: {error}", "Panel move was not applied: {error}": "A movimentação do painel não foi aplicada: {error}", "{name} is installed": "{name} está instalado", - "{name} is installed and in use: face recognition is on": "{name} está instalado e em uso: o reconhecimento facial está ativado" + "{name} is installed and in use: face recognition is on": "{name} está instalado e em uso: o reconhecimento facial está ativado", + "Bring photos in with File › Import Photos… ({keys}).": "Traga fotos com Arquivo › Importar fotos… ({keys}).", + "View › Detail View ({keys}).": "Exibir › Exibição de detalhe ({keys}).", + "File › Export… · File › Print… ({keys}).": "Arquivo › Exportar… · Arquivo › Imprimir… ({keys})." } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 82d695bba8..3aedd82906 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2248,5 +2248,27 @@ "Top bar": "Barra superior", "Tool strip": "Barra de ferramentas", "Bottom bar": "Barra inferior", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)", + "Welcome to LightCraft": "Bem-vindo ao LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Uma biblioteca de fotos rápida e não destrutiva e um revelador RAW: seus originais permanecem intactos, e cada edição pode ser revista ou desfeita.", + "Bring photos in with File › Import Photos…": "Traga fotos com Arquivo › Importar fotos…", + "Find and organize": "Encontre e organize", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "A Grade de fotos organiza a biblioteca em linhas justificadas: avalie, sinalize e marque com cores, filtre e reúna as fotos em álbuns.", + "View › Photo Grid.": "Exibir › Grade de fotos.", + "Develop a photo": "Revele uma foto", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Abra uma foto para revelá-la: exposição, cor, detalhes e máscaras, tudo de forma não destrutiva. Use Exibir › Antes/Depois lado a lado para comparar antes e depois.", + "View › Detail View.": "Exibir › Exibição de detalhe.", + "Cull a shoot": "Selecione uma sessão", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "A Seleção assistida avalia foco e exposição, encontra rajadas e marca como rejeitadas as fotos borradas, para que as melhores apareçam logo.", + "Photo › Assisted Culling…": "Foto › Seleção assistida…", + "Share your work": "Compartilhe seu trabalho", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Exportar gera JPEG, PNG, TIFF, WebP e mais, no tamanho que você escolher; Imprimir dispõe uma foto em uma página como PDF.", + "File › Export… · File › Print…": "Arquivo › Exportar… · Arquivo › Imprimir…", + "File › Export…": "Arquivo › Exportar…", + "Put agents to work": "Ponha os agentes para trabalhar", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Tudo no LightCraft é um comando, então agentes de IA podem controlar o aplicativo em execução pelo MCP: selecionar, editar e exportar quando você pedir.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicie o aplicativo com --control 7980 (ou LIGHTCRAFT_CONTROL_PORT) e o lightcraft-cli mcp --connect conecta um agente a ele.", + "Welcome": "Bem-vindo", + "Next": "Próximo", + "Get Started": "Começar" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 0bcc2d98f8..d6156cc1fa 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -322,5 +322,8 @@ "Panel layout could not be restored: {error}": "Не удалось восстановить расположение панелей: {error}", "Panel move was not applied: {error}": "Перемещение панели не применено: {error}", "{name} is installed": "Модель {name} установлена", - "{name} is installed and in use: face recognition is on": "Модель {name} установлена и используется: распознавание лиц включено" + "{name} is installed and in use: face recognition is on": "Модель {name} установлена и используется: распознавание лиц включено", + "Bring photos in with File › Import Photos… ({keys}).": "Фотографии добавляются через Файл › Импорт фото… ({keys}).", + "View › Detail View ({keys}).": "Вид › Режим детализации ({keys}).", + "File › Export… · File › Print… ({keys}).": "Файл › Экспорт… · Файл › Печать… ({keys})." } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index a34312643d..b3df02470e 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2610,5 +2610,27 @@ "Top bar": "Верхняя панель", "Tool strip": "Панель инструментов", "Bottom bar": "Нижняя панель", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)", + "Welcome to LightCraft": "Добро пожаловать в LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Быстрая библиотека фотографий и неразрушающий проявитель RAW: оригиналы остаются нетронутыми, а каждую правку можно просмотреть или сбросить.", + "Bring photos in with File › Import Photos…": "Фотографии добавляются через Файл › Импорт фото…", + "Find and organize": "Находите и упорядочивайте", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Сетка фото выстраивает библиотеку ровными рядами: оценивайте, отмечайте флагами и цветовыми метками, фильтруйте и собирайте фотографии в альбомы.", + "View › Photo Grid.": "Вид › Сетка фото.", + "Develop a photo": "Обработайте фотографию", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Откройте фото для обработки: экспозиция, цвет, детализация и маски, всё неразрушающе. Используйте Вид › До/после рядом, чтобы сравнить до и после.", + "View › Detail View.": "Вид › Режим детализации.", + "Cull a shoot": "Отберите снимки съёмки", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Автоматический отбор оценивает резкость и экспозицию, находит серии и помечает размытые кадры как отклонённые, чтобы лучшие снимки сразу бросались в глаза.", + "Photo › Assisted Culling…": "Фото › Автоматический отбор…", + "Share your work": "Поделитесь результатом", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Экспорт сохраняет JPEG, PNG, TIFF, WebP и другие форматы нужного размера; Печать размещает фото на странице в виде PDF.", + "File › Export… · File › Print…": "Файл › Экспорт… · Файл › Печать…", + "File › Export…": "Файл › Экспорт…", + "Put agents to work": "Поручите работу агентам", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Всё в LightCraft — команды, поэтому ИИ-агенты могут управлять запущенным приложением через MCP: отбирать, редактировать и экспортировать по вашему слову.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустите приложение с --control 7980 (или LIGHTCRAFT_CONTROL_PORT), и команда lightcraft-cli mcp --connect подключит к нему одного агента.", + "Welcome": "Добро пожаловать", + "Next": "Далее", + "Get Started": "Начать" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index d6619228aa..124fcb3a18 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -321,6 +321,9 @@ "Creates {stacks} stack{} from {photos} of {scope}": "Skapar staplar: {stacks} · foton: {photos} av {scope}{:.0}", "{n} selected photo{} · {pages} page{}": "Markerade foton: {n} · sidor: {pages}{:.0}{:.0}", "{n} photo{} in view · {slides} slide{} · {time}": "Foton i vyn: {n} · bilder: {slides} · {time}{:.0}{:.0}", + "Bring photos in with File › Import Photos… ({keys}).": "Importera foton via Fil › Importera foton… ({keys}).", + "View › Detail View ({keys}).": "Visa › Detaljvy ({keys}).", + "File › Export… · File › Print… ({keys}).": "Fil › Exportera… · Fil › Skriv ut… ({keys}).", "{n} folder{} could not be read": "Mappar som inte gick att läsa: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index df2b0859ae..94b9e30333 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2334,6 +2334,28 @@ "Virtual Copy": "Virtuell kopia", "Visible": "Synlig", "Visualize HDR": "Visualisera HDR", + "Welcome to LightCraft": "Välkommen till LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Ett snabbt, icke-förstörande fotobibliotek och raw-utvecklarprogram: dina original förblir orörda, och varje redigering kan återbesökas eller återställas.", + "Bring photos in with File › Import Photos…": "Importera foton via Fil › Importera foton…", + "Find and organize": "Hitta och organisera", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Fotorutnätet lägger ut biblioteket som jämna rader: betygsätt, flagga och märk med färg, filtrera och samla foton i album.", + "View › Photo Grid.": "Visa › Fotorutnät.", + "Develop a photo": "Utveckla ett foto", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Öppna ett foto för att utveckla det: exponering, färg, detaljer och masker, allt icke-förstörande. Använd Visa › Före/efter sida vid sida för att jämföra före och efter.", + "View › Detail View.": "Visa › Detaljvy.", + "Cull a shoot": "Gallra en bildserie", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Assisterad gallring poängsätter skärpa och exponering, hittar bildserier och flaggar suddiga bilder som avvisade, så att de bästa kommer fram snabbt.", + "Photo › Assisted Culling…": "Foto › Assisterad gallring…", + "Share your work": "Dela ditt arbete", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Exportera skapar JPEG, PNG, TIFF, WebP med mera, i den storlek du vill; Skriv ut lägger ett foto på en sida som PDF.", + "File › Export… · File › Print…": "Fil › Exportera… · Fil › Skriv ut…", + "File › Export…": "Fil › Exportera…", + "Put agents to work": "Sätt agenterna i arbete", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Allting i LightCraft är ett kommando, så AI-agenter kan styra det körande programmet över MCP: gallring, utveckling och exportering på ditt ord.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Starta programmet med --control 7980 (eller LIGHTCRAFT_CONTROL_PORT), så kopplar lightcraft-cli mcp --connect en agent till det.", + "Welcome": "Välkommen", + "Next": "Nästa", + "Get Started": "Kom igång", "Visualize range": "Visualisera omfång", "Visualize Spots": "Visualisera fläckar", "Visualize Spots (A)": "Visualisera fläckar (A)", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 70dae2280f..ed5e041f82 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -322,5 +322,8 @@ "Panel layout could not be restored: {error}": "Не вдалося відновити розташування панелей: {error}", "Panel move was not applied: {error}": "Переміщення панелі не застосовано: {error}", "{name} is installed": "{name} установлено", - "{name} is installed and in use: face recognition is on": "{name} установлено й використовується: розпізнавання облич увімкнено" + "{name} is installed and in use: face recognition is on": "{name} установлено й використовується: розпізнавання облич увімкнено", + "Bring photos in with File › Import Photos… ({keys}).": "Фотографії імпортуйте через Файл › Імпортувати фото… ({keys}).", + "View › Detail View ({keys}).": "Вигляд › Детальне подання ({keys}).", + "File › Export… · File › Print… ({keys}).": "Файл › Експортувати… · Файл › Друк… ({keys})." } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 5980811b38..09b78fab1e 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2400,5 +2400,27 @@ "Top bar": "Верхня панель", "Tool strip": "Панель інструментів", "Bottom bar": "Нижня панель", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)", + "Welcome to LightCraft": "Ласкаво просимо до LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Швидка бібліотека фотографій і неруйнівна обробка RAW: оригінали залишаються недоторканими, а кожну зміну можна переглянути або скасувати.", + "Bring photos in with File › Import Photos…": "Фотографії імпортуйте через Файл › Імпортувати фото…", + "Find and organize": "Знаходьте та впорядковуйте", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Сітка фото розміщує бібліотеку у вирівняних рядках: оцінюйте, позначайте прапорцями й кольорами, фільтруйте та збирайте фото в альбоми.", + "View › Photo Grid.": "Вигляд › Сітка фото.", + "Develop a photo": "Оброблюйте фотографію", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Відкрийте фото для обробки: експозиція, колір, деталі та маски, усе неруйнівно. Використовуйте Вигляд › До/після поруч, щоб порівняти до і після.", + "View › Detail View.": "Вигляд › Детальне подання.", + "Cull a shoot": "Відберіть знімки із зйомки", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Допоміжний відбір оцінює різкість і експозицію, знаходить серії та позначає розмиті знімки як відхилені, щоб найкращі фото одразу помітили.", + "Photo › Assisted Culling…": "Фото › Допоміжний відбір…", + "Share your work": "Поділіться своєю роботою", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Експорт створює JPEG, PNG, TIFF, WebP та інші формати потрібного розміру; Друк розміщує фото на сторінці у форматі PDF.", + "File › Export… · File › Print…": "Файл › Експортувати… · Файл › Друк…", + "File › Export…": "Файл › Експортувати…", + "Put agents to work": "Залучіть агентів до роботи", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Усе в LightCraft є командами, тож ШІ-агенти можуть керувати запущеною програмою через MCP: відбирати, редагувати й експортувати за вашим дорученням.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустіть програму з --control 7980 (або LIGHTCRAFT_CONTROL_PORT), і lightcraft-cli mcp --connect під'єднає до неї одного агента.", + "Welcome": "Ласкаво просимо", + "Next": "Далі", + "Get Started": "Почати" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index a3a944ce39..d6c686c3b5 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -318,6 +318,9 @@ "Panel move was not applied: {error}": "Việc di chuyển bảng chưa được áp dụng: {error}", "{name} is installed": "{name} đã được cài đặt", "{name} is installed and in use: face recognition is on": "{name} đã được cài đặt và đang dùng: nhận diện khuôn mặt đã bật", + "Bring photos in with File › Import Photos… ({keys}).": "Đưa ảnh vào bằng Tệp › Nhập ảnh… ({keys}).", + "View › Detail View ({keys}).": "Xem › Chế độ xem chi tiết ({keys}).", + "File › Export… · File › Print… ({keys}).": "Tệp › Xuất… · Tệp › In… ({keys}).", "{n} folder{} could not be read": "Thư mục không đọc được: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 95369fa1f9..af27e9aa0a 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -1961,6 +1961,28 @@ "Virtual Copy": "Bản sao ảo", "Visible": "Hiển thị", "Visualize HDR": "Hình dung HDR", + "Welcome to LightCraft": "Chào mừng đến với LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Thư viện ảnh nhanh và bộ xử lý raw không phá hủy: bản gốc của bạn vẫn nguyên vẹn, và mọi chỉnh sửa đều có thể xem lại hoặc đặt lại.", + "Bring photos in with File › Import Photos…": "Đưa ảnh vào bằng Tệp › Nhập ảnh…", + "Find and organize": "Tìm và sắp xếp", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Lưới ảnh trình bày thư viện thành các hàng cân xứng: chấm điểm, gắn cờ và dán nhãn màu, lọc, và gom ảnh vào album.", + "View › Photo Grid.": "Xem › Lưới ảnh.", + "Develop a photo": "Phát triển một bức ảnh", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Mở ảnh để phát triển: độ phơi sáng, màu, chi tiết và mặt nạ, tất cả đều không phá hủy. Dùng Xem › Trước/Sau cạnh nhau để so sánh trước và sau.", + "View › Detail View.": "Xem › Chế độ xem chi tiết.", + "Cull a shoot": "Sàng lọc một buổi chụp", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Sàng lọc hỗ trợ chấm điểm độ nét và độ phơi sáng, tìm các chuỗi ảnh liên tiếp, và gắn cờ ảnh mờ thành đã loại, để những ảnh đạt nổi lên nhanh chóng.", + "Photo › Assisted Culling…": "Ảnh › Sàng lọc hỗ trợ…", + "Share your work": "Chia sẻ tác phẩm của bạn", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Xuất tạo JPEG, PNG, TIFF, WebP và nhiều định dạng khác, với kích thước tùy ý; In sắp ảnh lên trang thành PDF.", + "File › Export… · File › Print…": "Tệp › Xuất… · Tệp › In…", + "File › Export…": "Tệp › Xuất…", + "Put agents to work": "Cho agent vào việc", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Mọi thứ trong LightCraft đều là lệnh, nên agent AI có thể điều khiển ứng dụng đang chạy qua MCP: sàng lọc, phát triển và xuất ảnh theo lời bạn.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Khởi chạy ứng dụng với --control 7980 (hoặc LIGHTCRAFT_CONTROL_PORT), rồi lightcraft-cli mcp --connect sẽ gắn một agent vào đó.", + "Welcome": "Chào mừng", + "Next": "Tiếp theo", + "Get Started": "Bắt đầu", "Visualize Spots": "Hiển thị điểm bụi", "Visualize Spots (A)": "Hiển thị điểm bụi (A)", "Visualize range": "Hiển thị dải", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index b81b358848..2996e1a217 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -322,5 +322,8 @@ "Panel layout could not be restored: {error}": "无法恢复面板布局:{error}", "Panel move was not applied: {error}": "面板移动未应用:{error}", "{name} is installed": "{name} 已安装", - "{name} is installed and in use: face recognition is on": "{name} 已安装并在使用:人脸识别已开启" + "{name} is installed and in use: face recognition is on": "{name} 已安装并在使用:人脸识别已开启", + "Bring photos in with File › Import Photos… ({keys}).": "通过 文件 › 导入照片… ({keys}) 导入照片。", + "View › Detail View ({keys}).": "视图 › 详细视图 ({keys})。", + "File › Export… · File › Print… ({keys}).": "文件 › 导出… · 文件 › 打印… ({keys})。" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 995a204f4f..ca13d782a5 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2403,5 +2403,27 @@ "Set up name suggestions…": "设置姓名建议…", "Top bar": "顶部栏", "Tool strip": "工具栏", - "Bottom bar": "底部栏" + "Bottom bar": "底部栏", + "Welcome to LightCraft": "欢迎使用 LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "一款快速、非破坏性的照片库和 RAW 显影工具:原片保持不变,每次编辑都可以随时查看或还原。", + "Bring photos in with File › Import Photos…": "通过 文件 › 导入照片…导入照片。", + "Find and organize": "查找与整理", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "照片网格以等高行排列图库:可评分、标记旗标和颜色标签、筛选,并把照片归入相册。", + "View › Photo Grid.": "视图 › 照片网格。", + "Develop a photo": "编辑照片", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "打开照片进行编辑:曝光、色彩、细节和蒙版,全部非破坏性。使用 视图 › 修改前/修改后左右排列 对比编辑前后。", + "View › Detail View.": "视图 › 详细视图。", + "Cull a shoot": "筛选一次拍摄", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "辅助筛选会评估对焦与曝光,找出连拍组,并将模糊的照片标为排除,让保留的照片更快浮现。", + "Photo › Assisted Culling…": "照片 › 辅助筛选…", + "Share your work": "分享您的作品", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "导出可输出 JPEG、PNG、TIFF、WebP 等格式,并可按需调整尺寸;打印会将照片排版到页面上,输出为 PDF。", + "File › Export… · File › Print…": "文件 › 导出… · 文件 › 打印…", + "File › Export…": "文件 › 导出…", + "Put agents to work": "让智能体开始工作", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "LightCraft 中的一切都是命令,因此 AI 智能体可以通过 MCP 驱动正在运行的应用:按您的指示进行筛选、编辑和导出。", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 启动应用,lightcraft-cli mcp --connect 即可将一个智能体接入其中。", + "Welcome": "欢迎", + "Next": "下一步", + "Get Started": "开始使用" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index fc93b2b603..93f6d6fa00 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -322,5 +322,8 @@ "Panel layout could not be restored: {error}": "無法還原面板配置:{error}", "Panel move was not applied: {error}": "面板移動未套用:{error}", "{name} is installed": "{name} 已安裝", - "{name} is installed and in use: face recognition is on": "{name} 已安裝並在使用中:臉部辨識已開啟" + "{name} is installed and in use: face recognition is on": "{name} 已安裝並在使用中:臉部辨識已開啟", + "Bring photos in with File › Import Photos… ({keys}).": "透過 檔案 › 匯入照片… ({keys}) 匯入照片。", + "View › Detail View ({keys}).": "檢視 › 詳細檢視 ({keys})。", + "File › Export… · File › Print… ({keys}).": "檔案 › 匯出… · 檔案 › 列印… ({keys})。" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index d8b6d143b0..f3dfc422ec 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2404,5 +2404,27 @@ "Top bar": "頂部列", "Tool strip": "工具列", "Bottom bar": "底部列", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)", + "Welcome to LightCraft": "歡迎使用 LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "快速且非破壞性的照片庫與 RAW 顯影工具:原始檔保持不變,每次編輯都能隨時檢視或還原。", + "Bring photos in with File › Import Photos…": "透過 檔案 › 匯入照片…匯入照片。", + "Find and organize": "尋找與整理", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "照片格狀檢視以等高列排列圖庫:可評分、標記旗標與色彩標籤、篩選,並將照片歸入相簿。", + "View › Photo Grid.": "檢視 › 照片格狀檢視。", + "Develop a photo": "編輯照片", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "開啟照片進行編輯:曝光、色彩、細節與遮色片,全部為非破壞性。使用 檢視 › 編輯前/後左右檢視 比較編輯前後。", + "View › Detail View.": "檢視 › 詳細檢視。", + "Cull a shoot": "挑選一次拍攝的照片", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "輔助挑片會評估對焦與曝光、找出連拍組,並將模糊的照片標為排除,讓入選的照片更快浮現。", + "Photo › Assisted Culling…": "照片 › 輔助挑片…", + "Share your work": "分享您的作品", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "匯出可輸出 JPEG、PNG、TIFF、WebP 等格式,尺寸可自行設定;列印會將照片排版到頁面上,輸出為 PDF。", + "File › Export… · File › Print…": "檔案 › 匯出… · 檔案 › 列印…", + "File › Export…": "檔案 › 匯出…", + "Put agents to work": "讓代理程式開始工作", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "LightCraft 中的所有功能都是指令,因此 AI 代理程式可透過 MCP 操控正在執行的應用程式:依您的指示挑片、編輯與匯出。", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 啟動應用程式,lightcraft-cli mcp --connect 即可將一個代理程式連接到其中。", + "Welcome": "歡迎", + "Next": "下一步", + "Get Started": "開始使用" } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 798101a7ef..66e377a913 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -2,6 +2,7 @@ use super::{ LightcraftApp, docking, drop_overlay, export_task, focus_scan, import, lightroom_import, merge, monotonic_ms, panels, pick, recheck, shortcuts, slideshow_export, state, sync, tasks, theme, updates_ui, widgets, }; +use crate::startup; impl LightcraftApp { /// Install/refresh fonts once and watch the device and availability caches. Setup, not input. @@ -27,6 +28,24 @@ impl LightcraftApp { } else { self.fonts_ready = true; } + // First run ever, or a fresh version: the tour, or What's New. Never headless — + // snapshots and scripted runs hold session-local state and must not gain a modal. + // Every frame until it shows: another dialog open on the first frame (a delivered file) + // keeps its place, and so does the blocking library window (the launch chooser or a + // library error — it is not in `ui.dialog`). The startup dialog opens once that window + // closes or is dismissed. Choosing it here is only dueing it: the version is recorded + // when the dialog is actually presented (`dialogs::show`), so a host that runs `logic` + // and quits before a visible frame does not burn the tour. + if self.ui.dialog.is_none() + && self.library_problem.as_ref().is_none_or(|p| p.dismissed) + && let Some(dialog) = startup::open_at_startup(self.ui.seen_version.as_deref(), self.headless_host) + { + self.ui.dialog = Some(dialog); + // a drop queued on this same frame (a delivered file, a host drop on the first pass) + // arrived before the dialog did: mark it, so it waits behind the dialog and imports + // once it closes instead of taking the close-the-dialog refusal on the first UI pass + self.defer_dropped_files(); + } } /// 0.36 stored each `PanelState` under the panel's exact `Id`; 0.37 stores it under diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 3d37909022..91d9dd2611 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -52,6 +52,152 @@ pub const ABOUT_TABS: &[(&str, &str)] = &[("about", "About"), ("contributors", " /// Help ▸ What's New (docs/whats-new.md). pub const WHATS_NEW: &str = include_str!("../../../docs/whats-new.md"); +/// The tour's window title and the labels of its next and last-page buttons: translated in every +/// catalog, with the pages' text (the test that pins it reads these). +pub(crate) const WELCOME_TITLE: &str = "Welcome"; +pub(crate) const WELCOME_NEXT: &str = "Next"; +pub(crate) const WELCOME_START: &str = "Get Started"; + +/// The first-run tour's pages: (title, what it does, where to find it). Every menu path names a +/// real command (`file.addPhotos`, `view.photoGrid`, `view.detail`, `view.beforeAfter`, +/// `dialog.cull`, `dialog.export`, `dialog.print`); `›` paints (the menu triangle `▸` does not). +/// The pages that name a shortcut take the command's live binding at render time +/// ([`welcome_body`]) — no key is written here, so no platform is shown a chord its menus do +/// not bind. +pub(crate) const WELCOME_PAGES: [(&str, &str, &str); 6] = [ + ( + "Welcome to LightCraft", + "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.", + "Bring photos in with File › Import Photos…", + ), + ( + "Find and organize", + "The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.", + "View › Photo Grid.", + ), + ( + "Develop a photo", + "Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.", + "View › Detail View.", + ), + ( + "Cull a shoot", + "Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.", + "Photo › Assisted Culling…", + ), + ( + "Share your work", + "Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.", + "File › Export… · File › Print…", + ), + ( + "Put agents to work", + "Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.", + "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.", + ), +]; + +/// The tour page that names the desktop-only launch flow: an MCP agent attaches over a `--control` +/// port, which only the desktop app listens on. The browser build omits the page rather than +/// telling browser users to launch a desktop binary. +const WELCOME_DESKTOP_ONLY_PAGE: usize = 5; + +/// The tour's pages for `web_host` (the browser build) against the desktop's: the browser has no +/// `--control` port for `lightcraft-cli` to attach to, so its tour omits [`WELCOME_DESKTOP_ONLY_PAGE`]. +/// The parameter is the pure decision; the running host passes [`welcome_pages_host`]'s answer. +pub(crate) fn welcome_pages(web_host: bool) -> &'static [(&'static str, &'static str, &'static str)] { + if web_host { &WELCOME_PAGES[..WELCOME_DESKTOP_ONLY_PAGE] } else { &WELCOME_PAGES } +} + +/// The pages this build's host shows: the web build (wasm32) hides the desktop-only page. +fn welcome_pages_host() -> &'static [(&'static str, &'static str, &'static str)] { + welcome_pages(cfg!(target_arch = "wasm32")) +} + +/// The command whose shortcut a tour page's opening line names. +fn welcome_page_command(page: usize) -> Option<&'static str> { + match page { + 0 => Some("file.addPhotos"), + 2 => Some("view.detail"), + 4 => Some("dialog.print"), + _ => None, + } +} + +/// The tour page that names Print. The browser build's File menu disables Print +/// ([`crate::menus::ui_enabled`]), so that host's tour names Export alone in the opening line +/// ([`welcome_opening`]) instead of a menu item the host greys out. +const WELCOME_PRINT_PAGE: usize = 4; + +/// The opening line a tour page paints under its text: the pages that name a shortcut carry the +/// command's live binding (`keys`), the Share page names Export alone on the web host, and the +/// rest paint the page's own sentence. +pub(crate) fn welcome_opening(page: usize, opening: &str, keys: Option<&str>, web_host: bool) -> String { + match (page, keys, web_host) { + (WELCOME_PRINT_PAGE, _, true) => crate::i18n::tr("File › Export…").to_string(), + (0, Some(keys), _) => crate::i18n::tr_format!("Bring photos in with File › Import Photos… ({keys}).", keys = keys), + (2, Some(keys), _) => crate::i18n::tr_format!("View › Detail View ({keys}).", keys = keys), + (WELCOME_PRINT_PAGE, Some(keys), _) => crate::i18n::tr_format!("File › Export… · File › Print… ({keys}).", keys = keys), + _ => crate::i18n::tr(opening).to_string(), + } +} + +/// The first-run tour: one page at a time, Back / Skip / Next under it. `close` is set when the +/// tour is finished (Next on the last page) or skipped. +fn welcome_body(app: &LightcraftApp, ui: &mut egui::Ui, t: &Tokens, page: &mut usize, close: &mut bool) { + let pages = welcome_pages_host(); + let last = pages.len() - 1; + *page = (*page).min(last); + let (title, text, opening) = pages[*page]; + ui.add_space(2.0); + ui.label(egui::RichText::new(crate::i18n::tr(title)).font(t.semibold(16.0)).color(t.text)); + ui.label(egui::RichText::new(crate::i18n::tr(text)).color(t.text_label)); + ui.add_space(2.0); + // The pages that name a shortcut show the command's live binding, painted the way the menus + // paint theirs (`menubar::shortcut_text`: `⌘⇧I` on macOS, `Ctrl+Shift+I` elsewhere) — never + // a hard-coded key. A command whose binding was removed shows the menu path alone. + let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; + let keys = welcome_page_command(*page) + .and_then(|id| crate::shortcuts::shortcut_of(&app.ui.settings.keymap, id)) + .map(|sc| crate::menus::menubar::shortcut_text(sc, mac)); + let opening = welcome_opening(*page, opening, keys.as_deref(), cfg!(target_arch = "wasm32")); + ui.label(egui::RichText::new(opening).color(t.text_dim)); + ui.add_space(8.0); + // progress dots, centred: the active page's is the accent + let spacing = 12.0; + let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 8.0), egui::Sense::hover()); + let x0 = rect.center().x - spacing * (last as f32) / 2.0; + for i in 0..pages.len() { + let c = egui::pos2(x0 + i as f32 * spacing, rect.center().y); + ui.painter().circle_filled(c, if i == *page { 2.5 } else { 1.5 }, if i == *page { t.accent } else { t.text_dim }); + } + ui.add_space(8.0); + use crate::button::{Button, Kind}; + let back = Button::new(crate::i18n::tr("Back")).widget("button:welcomeBack").enabled(*page > 0).min_width(72.0); + let skip = Button::new(crate::i18n::tr("Skip")).kind(Kind::Ghost).widget("button:welcomeSkip").min_width(72.0); + let next_label = if *page == last { crate::i18n::tr(WELCOME_START) } else { crate::i18n::tr(WELCOME_NEXT) }; + let next = Button::new(next_label).kind(Kind::Primary).widget("button:welcomeNext").min_width(84.0); + let gap = ui.spacing().item_spacing.x; + let row_w = ui.available_width().max(ui.min_rect().width()).max(1.0); + let (skip_w, next_w) = (skip.desired_size(ui).x, next.desired_size(ui).x); + ui.allocate_ui_with_layout(egui::vec2(row_w, next.desired_size(ui).y), egui::Layout::left_to_right(egui::Align::Center), |ui| { + if back.show(ui).clicked() { + *page -= 1; + } + ui.add_space((ui.available_width() - skip_w - next_w - 2.0 * gap).max(0.0)); + if skip.show(ui).clicked() { + *close = true; + } + if next.show(ui).clicked() { + if *page == last { + *close = true; + } else { + *page += 1; + } + } + }); +} + /// The import review and Settings keep window ids of their own, so the size each is given /// doesn't carry over to the other dialogs. fn window_id(dialog: &Dialog) -> egui::Id { @@ -158,6 +304,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { Dialog::FaceModel { .. } => 460.0, Dialog::LightroomCatalog { .. } => 440.0, Dialog::LightroomDestination { .. } => 480.0, + Dialog::Welcome { .. } => 460.0, Dialog::LensDatabase { .. } => 440.0, Dialog::ManageEffects { .. } => 560.0, _ => 380.0, @@ -172,7 +319,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { } ui.spacing_mut().item_spacing.y = 8.0; body_h = dialog_body(ui, (!import && !print).then_some(title.as_str()), body_max, |ui| { - dialog_content(app, ui, &t, body_max, &mut confirm, &mut dlg) + dialog_content(app, ui, &t, body_max, &mut confirm, &mut close, &mut dlg) }); ui.add_space(4.0); // the confirm on the right with Cancel to its left (macOS and GNOME's order), filled with @@ -217,6 +364,14 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { if let Some(band) = title_bar { title_bar_handle(ctx, band, w.response.rect); } + // The startup dialog is recorded once it was presented, not when the logic tick picked + // it: a host that runs `logic` and quits before a visible frame does not burn the tour, + // and a crash while it is up still does not reopen it on every launch. A frame whose + // input a notice owns is not a presentation: the dialog is drawn but cannot be used, so + // the recording waits for a pass where the dialog actually takes input. + if !raw_blocked && matches!(at_start, Dialog::Welcome { .. } | Dialog::WhatsNew) { + app.ui.record_startup_dialog_seen(); + } } // (while the shortcuts editor records a key, it takes Esc itself to cancel; an open popup in // the dialog, such as a date picker's calendar, takes it to close itself) @@ -304,6 +459,7 @@ fn dialog_title(app: &LightcraftApp, dlg: &Dialog) -> String { Dialog::FaceModel { info, .. } if info["download"].is_string() => "Download Face Model", Dialog::FaceModel { .. } => "Add Face Model", Dialog::WhatsNew => "What's New", + Dialog::Welcome { .. } => WELCOME_TITLE, Dialog::Cull { .. } => "Assisted Culling", Dialog::SmartRules { id: None, .. } => "New Smart Album", Dialog::SmartRules { .. } => "Edit Smart Album", @@ -448,6 +604,7 @@ fn fixed_ok_label(app: &LightcraftApp, dlg: &Dialog, informational: bool) -> &'s Dialog::RemoveFolder { .. } => "Remove", Dialog::LightroomCatalog { .. } => "Import Lightroom Catalog…", d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::ok_label(d), + Dialog::Welcome { .. } => "", Dialog::LensDatabase { .. } => "Download", Dialog::SynchronizeFolder { .. } if informational => "Close", Dialog::SynchronizeFolder { .. } => "Synchronize", @@ -1919,11 +2076,12 @@ fn about_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut /// The body of the open dialog: what each kind of dialog shows between its title and its buttons. `confirm` is set /// by a dialog that is confirmed from its body (a text field's Return). -fn dialog_content(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, body_max: f32, confirm: &mut bool, dlg: &mut Dialog) { +fn dialog_content(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, body_max: f32, confirm: &mut bool, close: &mut bool, dlg: &mut Dialog) { match dlg { Dialog::AutoStack { .. } => auto_stack_body(app, ui, t, dlg), Dialog::Cull { .. } => cull_body(app, ui, t, dlg), Dialog::WhatsNew => whats_new_body(ui, t, dlg), + Dialog::Welcome { page } => welcome_body(app, ui, t, page, close), Dialog::DenoiseModel { info, accepted } => crate::panels::denoise::model_dialog(app, ui, t, info, accepted), Dialog::FaceModel { info, accepted, .. } => crate::panels::faces::model_dialog(app, ui, t, info, accepted), Dialog::LightroomResult { .. } => lightroom_result_body(ui, dlg), diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 5f8e2c0445..b0d816d25c 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -177,7 +177,7 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result app.run("stack.auto", json!({"gap": gap})), Dialog::DenoiseModel { info, accepted } => crate::panels::denoise::install(app, info, *accepted), Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted), - Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null), + Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew | Dialog::Welcome { .. } => Ok(serde_json::Value::Null), Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { app.ui.cull_burst = Some((*burst_gap, *similarity)); app.run("photo.analyze", cull_params(*reject_below, *pick_best, *burst_gap, *similarity)) diff --git a/crates/ui-egui/src/dialogs/frame.rs b/crates/ui-egui/src/dialogs/frame.rs index ea385f4336..d6e8ea8120 100644 --- a/crates/ui-egui/src/dialogs/frame.rs +++ b/crates/ui-egui/src/dialogs/frame.rs @@ -208,6 +208,7 @@ pub(super) fn only_shows(dlg: &Dialog) -> bool { | Dialog::SystemInfo { .. } | Dialog::AllMetadata { .. } | Dialog::WhatsNew + | Dialog::Welcome { .. } | Dialog::ManageEffects { .. } | Dialog::ViewOptions ) || matches!(dlg, Dialog::SynchronizeFolder { counts: Some(c), .. } if c.up_to_date()) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b7f4a00e6d..0b7f31cf9e 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -136,6 +136,33 @@ fn catalogs_agree_on_placeholders() { } } +/// The tour's text (its pages, and its window and button labels) is in every catalog: a language +/// missing one of these keys would show that line in English on the first launch. The pages that +/// name a shortcut carry the live chord through a format message (`menubar::shortcut_text` paints +/// it), so their `{keys}` forms are pinned in every `*-formats.json` too. +#[test] +fn the_welcome_tour_is_translated_in_every_catalog() { + use crate::dialogs::{WELCOME_NEXT, WELCOME_PAGES, WELCOME_START, WELCOME_TITLE}; + let keys: Vec<&str> = WELCOME_PAGES + .iter() + .flat_map(|(title, text, opening)| [*title, *text, *opening]) + .chain([WELCOME_TITLE, WELCOME_NEXT, WELCOME_START]) + .collect(); + let format_keys = [ + "Bring photos in with File \u{203a} Import Photos\u{2026} ({keys}).", + "View \u{203a} Detail View ({keys}).", + "File \u{203a} Export\u{2026} \u{b7} File \u{203a} Print\u{2026} ({keys}).", + ]; + for language in Locale::ALL.iter().copied().filter(|language| *language != Locale::En) { + let catalog = language.catalog(); + let missing: Vec<&str> = keys.iter().copied().filter(|key| !catalog.contains_key(*key)).collect(); + assert!(missing.is_empty(), "{}: no translation for {missing:?}", language.code()); + let own_formats = formats_catalog(language.code()); + let missing_formats: Vec<&str> = format_keys.iter().copied().filter(|key| !own_formats.contains_key(*key)).collect(); + assert!(missing_formats.is_empty(), "{}: no translation for {missing_formats:?}", language.code()); + } +} + /// Locale tags are matched leniently, so a system locale reaches a shipped language. /// The message box for a desktop start that failed (issue #260) names the error and the log /// file, in the UI language. @@ -679,6 +706,9 @@ fn german_ukrainian_italian_and_finnish_buttons_fit_the_bottom_bar_and_export_di let ctx = fonts_ctx(&[]); let services = crate::Services { pick_folder: Some(Box::new(|| None)), ..Default::default() }; let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + // a headless host never gains the first-run tour: this harness drives `ui` directly and + // measures the export dialog's own layout + app.headless_host = true; app.ui.language = language; let mut bounds = Vec::new(); for export in [false, true] { @@ -738,6 +768,7 @@ fn painted_text(ctx: &egui::Context, app: &mut crate::LightcraftApp, language: L _ => {} } } + app.headless_host = true; app.ui.language = language; let mut text = String::new(); for frame in 0..4 { @@ -827,6 +858,8 @@ fn the_ui_works_without_craft_fonts() { } }); let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + // a headless host never gains the first-run tour: this pass just warms every language up + app.headless_host = true; for language in Locale::ALL { app.ui.language = *language; for frame in 0..3 { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5bfccc8fb7..e1b3410556 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -46,6 +46,7 @@ pub mod shortcuts; pub mod sidebar; pub mod softpaint; pub mod space_hand; +pub mod startup; pub mod state; pub mod sync; pub mod tasks; diff --git a/crates/ui-egui/src/startup.rs b/crates/ui-egui/src/startup.rs new file mode 100644 index 0000000000..f68d476ab7 --- /dev/null +++ b/crates/ui-egui/src/startup.rs @@ -0,0 +1,242 @@ +//! Startup dialog selection for first-run onboarding and What's New. +//! +//! On first launch (`seen == None`) show `FirstRun`. After an update (the stored previous +//! version differs from the running version) show `WhatsNew`. Both are skipped when the +//! version was already seen. +//! +//! `UiState::record_startup_dialog_seen` uses record-on-show semantics (documented there): the +//! version is recorded when the dialog is presented in a UI pass, not when the logic tick +//! picks it. +//! +//! A settings file from before this existed migrates to [`LEGACY_SEEN_VERSION`], so an +//! existing installation is due What's New, never the first-run tour. + +use crate::state::Dialog; + +/// What to show at startup before the main UI takes over. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StartupDialog { + /// First launch ever: show the onboarding walkthrough. + FirstRun, + /// The app was updated since the last launch: show What's New. + WhatsNew, +} + +/// Parse "1.2.3" / "1.2.3-rc.1" / "0.8.0" into (major, minor, patch), ignoring any +/// prerelease suffix. Returns `None` when not parseable. +pub fn parse_version(version: &str) -> Option<(u64, u64, u64)> { + let core = version.split('-').next()?.trim(); + let parts: Vec<&str> = core.split('.').collect(); + if parts.len() != 3 { + return None; + } + let major = parts[0].parse::().ok()?; + let minor = parts[1].parse::().ok()?; + let patch = parts[2].parse::().ok()?; + Some((major, minor, patch)) +} + +/// The version a settings file from before the startup dialog existed migrates to: the file's +/// existence means an installation that has been run, so it is due What's New, never the +/// first-run tour. `None` stays reserved for no settings at all. +pub const LEGACY_SEEN_VERSION: &str = "0.0.0"; + +/// The legacy `seenVersion` migration both settings loaders share — the desktop settings file +/// (`lightcraft`'s `prefs`) and the browser's stored `ui.json` — applied to the parsed JSON +/// object before it deserializes into [`crate::state::UiState`]. A saved file from before the +/// startup dialog existed has no `seenVersion` key, and the file's existence means an +/// installation that has been run, due What's New — never the first-run tour. A file this +/// version saved before the dialog was presented carries an explicit `null` instead (that is +/// why `None` serializes) and is not migrated, and no file at all (no object) stays a first +/// run. +pub fn migrate_legacy_seen_version(fields: &mut serde_json::Map) { + if !fields.contains_key("seenVersion") { + fields.insert("seenVersion".into(), serde_json::json!(LEGACY_SEEN_VERSION)); + } +} + +/// The dialog to show for `seen` (the stored last-seen version, `None` = first run) against +/// `current` (the running version). +/// +/// `FirstRun` only when `seen == None`. `WhatsNew` when the version changed. `None` when +/// identical. +/// +/// Comparison goes through [`parse_version`]. When both sides parse, any numeric difference +/// (and a prerelease-vs-release string difference with the same numbers) is a change → +/// `WhatsNew`. When either side is unparseable, fall back to the string comparison: show +/// `WhatsNew` when the strings differ, `None` when identical — never `FirstRun` once +/// something was seen. +pub fn startup_dialog(seen: Option<&str>, current: &str) -> Option { + let Some(seen) = seen else { + return Some(StartupDialog::FirstRun); + }; + if seen == current { + return None; + } + // `seen` differs from `current`. `parse_version` confirms a real version-like change + // when both sides parse; when either side is unparseable we fall back to the string + // difference already established and show WhatsNew conservatively. + match (parse_version(seen), parse_version(current)) { + (Some(sv), Some(cv)) if sv != cv => Some(StartupDialog::WhatsNew), + _ => Some(StartupDialog::WhatsNew), + } +} + +/// The dialog the first frame opens for `seen` (the stored last-seen version): [`Dialog::Welcome`] +/// on the first run ever, [`Dialog::WhatsNew`] after an update, none once the running version was +/// seen. A headless host (snapshots, scripted runs, tests: their UI state is session-local, with +/// no stored version behind it) never gains a modal. +pub fn open_at_startup(seen: Option<&str>, headless: bool) -> Option { + if headless { + return None; + } + match startup_dialog(seen, env!("CARGO_PKG_VERSION")) { + Some(StartupDialog::FirstRun) => Some(Dialog::Welcome { page: 0 }), + Some(StartupDialog::WhatsNew) => Some(Dialog::WhatsNew), + None => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_version_plain() { + assert_eq!(parse_version("1.2.3"), Some((1, 2, 3))); + assert_eq!(parse_version("0.8.0"), Some((0, 8, 0))); + assert_eq!(parse_version("10.20.30"), Some((10, 20, 30))); + } + + #[test] + fn parse_version_prerelease() { + assert_eq!(parse_version("1.2.3-rc.1"), Some((1, 2, 3))); + assert_eq!(parse_version("0.8.0-beta.2"), Some((0, 8, 0))); + } + + #[test] + fn parse_version_garbage() { + assert_eq!(parse_version(""), None); + assert_eq!(parse_version("not-a-version"), None); + assert_eq!(parse_version("1.2"), None); + assert_eq!(parse_version("1.2.3.4"), None); + assert_eq!(parse_version("abc.2.3"), None); + } + + #[test] + fn startup_dialog_first_run() { + assert_eq!(startup_dialog(None, "0.8.0"), Some(StartupDialog::FirstRun)); + assert_eq!(startup_dialog(None, "1.0.0"), Some(StartupDialog::FirstRun)); + } + + #[test] + fn startup_dialog_equal() { + assert_eq!(startup_dialog(Some("0.8.0"), "0.8.0"), None); + assert_eq!(startup_dialog(Some("1.2.3"), "1.2.3"), None); + } + + #[test] + fn startup_dialog_version_changed() { + assert_eq!(startup_dialog(Some("0.7.9"), "0.8.0"), Some(StartupDialog::WhatsNew)); + } + + #[test] + fn startup_dialog_prerelease_vs_release() { + assert_eq!(startup_dialog(Some("1.2.3-rc.1"), "1.2.3"), Some(StartupDialog::WhatsNew)); + assert_eq!(startup_dialog(Some("1.2.3"), "1.2.3-rc.1"), Some(StartupDialog::WhatsNew)); + } + + #[test] + fn startup_dialog_unparseable_differing() { + assert_eq!(startup_dialog(Some("garbage"), "0.8.0"), Some(StartupDialog::WhatsNew)); + assert_eq!(startup_dialog(Some("0.8.0"), "garbage"), Some(StartupDialog::WhatsNew)); + } + + #[test] + fn startup_dialog_unparseable_identical() { + assert_eq!(startup_dialog(Some("garbage"), "garbage"), None); + } + + #[test] + fn ui_state_serde_round_trip_with_seen_version() { + let state = crate::state::UiState { seen_version: Some("0.8.0".to_string()), ..Default::default() }; + let json = serde_json::to_string(&state).expect("serialize"); + let back: crate::state::UiState = serde_json::from_str(&json).expect("deserialize"); + assert_eq!(back.seen_version, Some("0.8.0".to_string())); + } + + #[test] + fn ui_state_serde_serializes_an_unset_marker_as_null() { + // A file this version saved before the startup dialog was presented carries an explicit + // `null`, so the desktop loader can tell it apart from a pre-feature file (which lacks + // the key and migrates): null stays `None` — the tour, not What's New. + let state = crate::state::UiState::default(); + let json = serde_json::to_string(&state).expect("serialize"); + assert!(json.contains(r#""seenVersion":null"#), "{json}"); + let back: crate::state::UiState = serde_json::from_str(&json).expect("deserialize"); + assert_eq!(back.seen_version, None); + } + + #[test] + fn first_frame_opens_the_tour_or_whats_new_but_never_headless() { + assert!(matches!(super::open_at_startup(None, false), Some(crate::state::Dialog::Welcome { page: 0 }))); + assert!(matches!(super::open_at_startup(Some("0.0.1"), false), Some(crate::state::Dialog::WhatsNew))); + assert_eq!(super::open_at_startup(Some(env!("CARGO_PKG_VERSION")), false), None); + // session-local state: nothing stored behind it, so no modal + assert_eq!(super::open_at_startup(None, true), None); + } + + #[test] + fn ui_state_serde_older_json_without_field() { + // Older ui.json without seen_version deserializes fine (None = first run). + let json = r#"{"language":"en","view":"detail","left_panel":false}"#; + let back: crate::state::UiState = serde_json::from_str(json).expect("deserialize"); + assert_eq!(back.seen_version, None); + } + + /// A stored UiState serialized like both loaders receive it, with `seenVersion` rewritten. + fn saved_ui(seen_version: serde_json::Value) -> serde_json::Value { + let mut saved = serde_json::to_value(crate::state::UiState::default()).expect("serialize"); + saved.as_object_mut().expect("object").insert("seenVersion".into(), seen_version); + saved + } + + /// A settings file from before the startup dialog existed has no `seenVersion` key: the + /// shared migration the desktop settings loader and the browser loader both run marks the + /// installation as run (`LEGACY_SEEN_VERSION`), so it is due What's New, never the tour. + #[test] + fn legacy_settings_without_a_seen_version_get_whats_new() { + let mut saved = saved_ui(serde_json::Value::Null); + saved.as_object_mut().unwrap().remove("seenVersion"); + // without the migration it deserializes to a first run — exactly what the migration + // exists to prevent for an existing installation + let unmigrated: crate::state::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(unmigrated.seen_version, None); + super::migrate_legacy_seen_version(saved.as_object_mut().unwrap()); + let ui: crate::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(ui.seen_version.as_deref(), Some(LEGACY_SEEN_VERSION)); + assert_eq!(startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")), Some(StartupDialog::WhatsNew)); + } + + /// A file this version saved before the dialog was presented carries an explicit `null` + /// (that is why `None` serializes): it is not migrated, so the tour still runs. + #[test] + fn an_explicit_null_seen_version_stays_a_first_run() { + let mut saved = saved_ui(serde_json::Value::Null); + super::migrate_legacy_seen_version(saved.as_object_mut().unwrap()); + assert_eq!(saved["seenVersion"], serde_json::Value::Null); + let ui: crate::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(ui.seen_version, None); + assert_eq!(startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")), Some(StartupDialog::FirstRun)); + } + + /// A version already seen is left exactly as stored: no What's New, no tour. + #[test] + fn a_previously_seen_version_is_not_migrated() { + let mut saved = saved_ui(serde_json::json!("0.14.0")); + super::migrate_legacy_seen_version(saved.as_object_mut().unwrap()); + let ui: crate::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(ui.seen_version.as_deref(), Some("0.14.0")); + assert_eq!(startup_dialog(Some("0.14.0"), "0.15.0"), Some(StartupDialog::WhatsNew)); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 6d25426298..37a8c2d4bb 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -372,6 +372,12 @@ pub struct UiState { pub status: String, #[serde(skip)] pub dialog: Option, + /// The last app version whose startup dialog was shown; `None` = the dialog was never + /// presented (never run, pre-feature settings, or a file saved before it was shown — that is + /// why `None` serializes, as `null`, instead of being omitted: a settings file from this + /// version without a seen version must not read as a pre-feature file). + #[serde(default)] + pub seen_version: Option, /// The Print dialog's page, selection and drag. #[serde(skip)] pub print: crate::print_view::PrintUi, @@ -518,6 +524,7 @@ impl Default for UiState { #[cfg(test)] find_missing_test_delay: None, rechecked_library: None, + seen_version: None, lens_download_checked: false, lens_refreshed: None, lens_lookup_ids: Vec::new(), @@ -617,6 +624,16 @@ impl UiState { } self } + + /// Record that the startup dialog for the running version has been presented. + /// + /// Record-on-show semantics: `seen_version` is set when the dialog is laid out in a UI pass + /// (`dialogs::show`), not when the logic tick picks it — a host that quits before a visible + /// frame does not burn the tour — and a crash while the dialog is up does not re-trigger it + /// on every subsequent launch. + pub fn record_startup_dialog_seen(&mut self) { + self.seen_version = Some(env!("CARGO_PKG_VERSION").to_string()); + } } /// A list of ids read leniently: what isn't a list is none, and what isn't text in it is left out. diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index 30a2c08ffa..77f80a280c 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -165,6 +165,12 @@ pub enum Dialog { }, /// Help ▸ What's New. WhatsNew, + /// First launch: a short tour of the main views, one page at a time. + Welcome { + /// The page on show (0-based; clamped when rendered). + #[serde(default)] + page: usize, + }, /// Photo ▸ Assisted Culling: reject photos below this focus score (0 = none), pick the best /// of each burst; shots at most `burst_gap` seconds apart and at least `similarity` alike are /// a burst. diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index a9f8b72cba..e71ef8164a 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -97,6 +97,7 @@ mod tool_overlay; mod unsaved; mod view_cost; mod wb_selector; +mod welcome; mod zoom; mod zoom_keys; diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index ad661e9f19..ae043cb5f1 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -568,6 +568,32 @@ fn a_queued_drop_waits_for_a_dialog_opened_before_the_launch_list_closes() { assert!(h.app.dropped_files.is_empty(), "the deferred drop was consumed only when safe"); } +/// A drop delivered on the very first frame is queued by `raw_input_hook` before the same frame's +/// `logic` assigns the startup dialog. The dialog did not exist when the drop arrived, so the +/// drop must not take the "close the open dialog" refusal on the first UI pass that can see it: +/// it waits behind the startup dialog and is imported once the tour closes. +#[test] +fn a_drop_delivered_on_the_first_frame_waits_behind_the_startup_dialog() { + let dir = Scratch::new("startup-drop"); + write_png(&dir.path("trip/a.png"), 1); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(dir.path("library"), false).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, services()), [1300.0, 900.0], 1.0); + // a window host on its first launch, with the drop riding the first frame's raw input + h.app.headless_host = false; + h.app.drop_pending = vec![dir.path("trip/a.png")]; + h.step(); + assert!(matches!(h.app.ui.dialog, Some(Dialog::Welcome { page: 0 })), "{:?}", h.app.ui.dialog); + assert_eq!(h.app.dropped_files.len(), 1, "the first-frame drop is queued"); + h.step(); + assert!(matches!(h.app.ui.dialog, Some(Dialog::Welcome { .. })), "the tour stays: {:?}", h.app.ui.dialog); + assert_eq!(h.app.dropped_files.len(), 1, "the first-frame drop waits behind the startup dialog instead of being refused"); + assert!(h.app.import.is_none(), "nothing starts behind the dialog"); + h.app.ui.dialog = None; + assert!(h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the drop opens its review once the tour is closed"); + assert!(h.app.dropped_files.is_empty(), "the queued drop was consumed only when safe"); +} + /// A drop queued behind the launch list may be released while a Synchronize Folder runs. It /// waits for that run to finish instead of taking `import::start_paths`'s "A folder is being /// synchronized" refusal and being lost. A drop made while no barrier was up still gets that diff --git a/crates/ui-egui/src/tests/find_similar.rs b/crates/ui-egui/src/tests/find_similar.rs index b75995a1ca..5e2ffaf29e 100644 --- a/crates/ui-egui/src/tests/find_similar.rs +++ b/crates/ui-egui/src/tests/find_similar.rs @@ -104,6 +104,12 @@ fn a_search_from_the_menu_reads_off_the_ui_thread_and_the_window_goes_on() { // nothing has been read yet: the command and the frames waited for none of it assert!(t0.elapsed() < FRAMES, "the window waited for the files: {:?}", t0.elapsed()); assert_eq!(h.app.session.filter, Default::default(), "no answer before the files are read"); + // the worker sets the row's total when it starts, which a loaded machine can leave for later + let waited = Instant::now(); + while rows(&h)[0].total == 0 && waited.elapsed() < T { + h.step(); + std::thread::sleep(Duration::from_millis(1)); + } let row = &rows(&h)[0]; assert_eq!(row.label, LABEL); assert_eq!(row.total, PHOTOS); diff --git a/crates/ui-egui/src/tests/lifecycle_037.rs b/crates/ui-egui/src/tests/lifecycle_037.rs index dbff222044..e29946baa2 100644 --- a/crates/ui-egui/src/tests/lifecycle_037.rs +++ b/crates/ui-egui/src/tests/lifecycle_037.rs @@ -2029,6 +2029,9 @@ fn a_discarded_layout_does_not_publish_its_widget_registry() { fn a_gesture_replies_only_after_the_completed_pass_consumed_its_event() { let ctx = egui::Context::default(); let mut app = app(); + // a headless host never gains the first-run tour: its modal would sit over the passes this + // test drives (screenshot tests elsewhere in this file need the host not headless) + app.headless_host = true; frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx())); app.logic(&ctx); assert!(app.fonts_ready); @@ -2057,6 +2060,10 @@ fn a_gesture_replies_only_after_the_completed_pass_consumed_its_event() { fn a_delivered_gesture_may_change_the_state_it_acted_on() { let ctx = egui::Context::default(); let mut app = app(); + // a headless host never gains the first-run tour: its modal would take the dialog this + // delivered gesture opens (screenshot tests elsewhere in this file need the host not + // headless, so the flag is scoped to this test) + app.headless_host = true; frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx())); app.logic(&ctx); assert!(app.fonts_ready); diff --git a/crates/ui-egui/src/tests/welcome.rs b/crates/ui-egui/src/tests/welcome.rs new file mode 100644 index 0000000000..993a10192a --- /dev/null +++ b/crates/ui-egui/src/tests/welcome.rs @@ -0,0 +1,251 @@ +//! The first-run Welcome tour: Back / Next walk its pages, Skip and the last page's Get Started +//! close it. (The auto-open at launch is decided by `startup::open_at_startup`, unit-tested there: +//! a headless host never gains the modal, so the tour is placed by hand here.) + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; +use serde_json::json; +use std::time::Duration; + +const T: Duration = Duration::from_secs(20); + +/// The app with the tour open on `page` (the last page of [`crate::panels::dialogs::WELCOME_PAGES`] +/// is `WELCOME_PAGES.len() - 1`). +fn tour(page: usize) -> Headless { + let services = Services { png: None, ..Default::default() }; + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + app.ui.dialog = Some(Dialog::Welcome { page }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + // fonts land on the second frame, and the dialog window settles its place a frame or two later; + // clicks must aim at the settled layout + h.step(); + h.settle(Duration::from_secs(5)); + h +} + +fn page_of(h: &Headless) -> Option { + match &h.app.ui.dialog { + Some(Dialog::Welcome { page }) => Some(*page), + _ => None, + } +} + +/// Click an automation id and let the injected press/release play out (they can straddle a frame). +fn click(h: &mut Headless, id: &str) { + let r = h.request("ui.clickWidget", json!({"id": id}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); +} + +#[test] +fn welcome_pages_walk_back_next_and_skip_closes() { + let mut h = tour(0); + // Back is disabled on the first page: the click lands on nothing and the tour stays. + click(&mut h, "button:welcomeBack"); + assert_eq!(page_of(&h), Some(0), "{:?}", h.app.ui.dialog); + click(&mut h, "button:welcomeNext"); + assert_eq!(page_of(&h), Some(1), "{:?}", h.app.ui.dialog); + click(&mut h, "button:welcomeBack"); + assert_eq!(page_of(&h), Some(0), "{:?}", h.app.ui.dialog); + click(&mut h, "button:welcomeSkip"); + assert!(h.app.ui.dialog.is_none(), "{:?}", h.app.ui.dialog); +} + +#[test] +fn welcome_last_page_gets_started_closes() { + let last = crate::panels::dialogs::WELCOME_PAGES.len() - 1; + let mut h = tour(last); + click(&mut h, "button:welcomeNext"); + assert!(h.app.ui.dialog.is_none(), "{:?}", h.app.ui.dialog); +} + +/// The web build omits the tour page that names the desktop-only launch flow (`--control`, +/// `lightcraft-cli mcp --connect`): a browser has no control port for an agent to attach to. +/// The host is a compile-time fact (wasm32), so this harness — native, a desktop host — tests +/// the pure decision ([`crate::dialogs::welcome_pages`]) for both answers. +#[test] +fn the_web_tour_omits_the_desktop_only_mcp_page() { + let all = crate::dialogs::WELCOME_PAGES.as_slice(); + assert_eq!(crate::dialogs::welcome_pages(false), all, "the desktop shows every page"); + let web = crate::dialogs::welcome_pages(true); + assert_eq!(web, &all[..all.len() - 1], "the web tour drops the last page"); + // the dropped page is the desktop-only one: its opening names the launch flow + let (_, _, opening) = all.last().unwrap(); + assert!(opening.contains("--control 7980") && opening.contains("lightcraft-cli"), "{opening}"); +} + +/// The first frame decides the launch dialog, but records nothing until the dialog is presented: +/// a window host with no stored version gets the tour; a headless host (the harness, snapshots, +/// scripted runs) gets nothing; a version already seen gets nothing; a version that changed gets +/// What's New. +#[test] +fn the_first_frame_opens_the_tour_for_a_window_host_only() { + let ctx = egui::Context::default(); + let logic = |app: &mut LightcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.logic(ui.ctx())); + out.textures_delta.clear(); + }; + let fresh = || LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + + let mut window = fresh(); + logic(&mut window); + assert!(matches!(window.ui.dialog, Some(Dialog::Welcome { page: 0 })), "{:?}", window.ui.dialog); + assert_eq!(window.ui.seen_version, None, "chosen, not yet presented"); + + let mut headless = fresh(); + headless.headless_host = true; + logic(&mut headless); + assert!(headless.ui.dialog.is_none(), "{:?}", headless.ui.dialog); + assert_eq!(headless.ui.seen_version, None); + + let mut seen = fresh(); + seen.ui.seen_version = Some(env!("CARGO_PKG_VERSION").to_string()); + logic(&mut seen); + assert!(seen.ui.dialog.is_none(), "{:?}", seen.ui.dialog); + + let mut updated = fresh(); + updated.ui.seen_version = Some("0.0.1".to_string()); + logic(&mut updated); + assert!(matches!(updated.ui.dialog, Some(Dialog::WhatsNew)), "{:?}", updated.ui.dialog); +} + +/// The version is recorded when the dialog is presented, not when the logic tick picks it: a +/// hidden host that runs `logic` and quits before a visible frame must not burn the tour. +#[test] +fn the_startup_dialog_is_recorded_when_presented_not_when_chosen() { + let ctx = egui::Context::default(); + let frame = |app: &mut LightcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + app.logic(ui.ctx()); + // the presentation pass (`ui` waits for the fonts, so frame one only runs `logic`) + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let mut held = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + + frame(&mut held); + assert!(matches!(held.ui.dialog, Some(Dialog::Welcome { page: 0 })), "{:?}", held.ui.dialog); + assert_eq!(held.ui.seen_version, None, "not presented yet, not recorded"); + + frame(&mut held); + assert!(matches!(held.ui.dialog, Some(Dialog::Welcome { page: 0 })), "{:?}", held.ui.dialog); + assert_eq!(held.ui.seen_version.as_deref(), Some(env!("CARGO_PKG_VERSION"))); + + // shown once: closing it does not bring it back + held.ui.dialog = None; + frame(&mut held); + assert!(held.ui.dialog.is_none(), "{:?}", held.ui.dialog); +} + +/// Another dialog open on the first frame keeps its place: the tour is not chosen that frame and +/// nothing is recorded. Once that dialog closes, the tour opens and is recorded then — shown, not +/// merely due. +#[test] +fn the_tour_waits_for_a_dialog_that_is_already_open() { + let ctx = egui::Context::default(); + let logic = |app: &mut LightcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.logic(ui.ctx())); + out.textures_delta.clear(); + }; + let present = |app: &mut LightcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let mut held = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + held.ui.dialog = Some(Dialog::ViewOptions); + + logic(&mut held); + assert!(matches!(held.ui.dialog, Some(Dialog::ViewOptions)), "{:?}", held.ui.dialog); + assert_eq!(held.ui.seen_version, None, "not shown, not recorded"); + + held.ui.dialog = None; + logic(&mut held); + assert!(matches!(held.ui.dialog, Some(Dialog::Welcome { page: 0 })), "{:?}", held.ui.dialog); + assert_eq!(held.ui.seen_version, None, "chosen behind the other dialog's turn, not yet presented"); + present(&mut held); + assert_eq!(held.ui.seen_version.as_deref(), Some(env!("CARGO_PKG_VERSION"))); + + // shown once: closing it does not bring it back + held.ui.dialog = None; + logic(&mut held); + assert!(held.ui.dialog.is_none(), "{:?}", held.ui.dialog); +} + +/// The launch chooser or a library error is the blocking library window, and it is not in +/// `ui.dialog`: it must still hold the startup dialog back, or the chooser's New Library name +/// prompt (a `ui.dialog` of its own) would take the tour's place with the version already +/// recorded. Once the window closes or is dismissed, the tour opens and is recorded then. +#[test] +fn the_tour_waits_for_the_launch_window_too() { + let ctx = egui::Context::default(); + let logic = |app: &mut LightcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.logic(ui.ctx())); + out.textures_delta.clear(); + }; + let present = |app: &mut LightcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let mut held = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + held.library_problem = Some(crate::panels::library_problem::LibraryProblem::new("", "the last library did not open")); + + logic(&mut held); + assert!(held.ui.dialog.is_none(), "{:?}", held.ui.dialog); + assert_eq!(held.ui.seen_version, None, "not shown behind the library window, not recorded"); + + held.library_problem = None; + logic(&mut held); + assert!(matches!(held.ui.dialog, Some(Dialog::Welcome { page: 0 })), "{:?}", held.ui.dialog); + assert_eq!(held.ui.seen_version, None, "chosen, not yet presented"); + present(&mut held); + assert_eq!(held.ui.seen_version.as_deref(), Some(env!("CARGO_PKG_VERSION"))); + + // shown once: closing it does not bring it back + held.ui.dialog = None; + logic(&mut held); + assert!(held.ui.dialog.is_none(), "{:?}", held.ui.dialog); +} + +/// A dismissed library window (Continue Without Saving) shows the banner instead of the window: +/// it no longer blocks, so the startup dialog opens over it as usual. +#[test] +fn the_tour_opens_once_the_library_window_is_dismissed() { + let ctx = egui::Context::default(); + let frame = |app: &mut LightcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let mut held = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut problem = crate::panels::library_problem::LibraryProblem::new("", "the last library did not open"); + problem.dismissed = true; + held.library_problem = Some(problem); + + frame(&mut held); + assert!(matches!(held.ui.dialog, Some(Dialog::Welcome { page: 0 })), "{:?}", held.ui.dialog); + assert_eq!(held.ui.seen_version, None, "chosen this frame, presented once the fonts are in"); + frame(&mut held); + assert_eq!(held.ui.seen_version.as_deref(), Some(env!("CARGO_PKG_VERSION"))); +} + +/// The browser build's File menu disables Print (`menus::ui_enabled` turns `dialog.print` off on +/// wasm), so the Share page's opening line names Export alone instead of a menu item the host +/// greys out. The desktop keeps both menu paths and the live Print binding. +#[test] +fn the_web_tour_names_export_alone_not_the_desktop_print_menu() { + use crate::panels::dialogs::welcome_opening; + assert_eq!(welcome_opening(4, "File › Export… · File › Print…", Some("Ctrl+P"), true), "File › Export…"); + assert_eq!(welcome_opening(4, "File › Export… · File › Print…", Some("Ctrl+P"), false), "File › Export… · File › Print… (Ctrl+P)."); + assert_eq!(welcome_opening(4, "File › Export… · File › Print…", None, false), "File › Export… · File › Print…"); +} diff --git a/crates/ui-egui/tests/it/accessibility.rs b/crates/ui-egui/tests/it/accessibility.rs index d86aa9487e..6b0e840af1 100644 --- a/crates/ui-egui/tests/it/accessibility.rs +++ b/crates/ui-egui/tests/it/accessibility.rs @@ -11,6 +11,8 @@ use lightcraft_ui_egui::{ fn harness(view: ViewMode, right: RightPanel) -> Harness<'static, LightcraftApp> { let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + // a headless host never gains the first-run tour: its modal would take the Tab focus under test + app.headless_host = true; app.ui.left_panel = true; app.ui.view = view; app.ui.right = right; diff --git a/crates/ui-egui/tests/it/dialog_role.rs b/crates/ui-egui/tests/it/dialog_role.rs index a36cc96fe9..5856c5bffa 100644 --- a/crates/ui-egui/tests/it/dialog_role.rs +++ b/crates/ui-egui/tests/it/dialog_role.rs @@ -6,7 +6,8 @@ use egui_kittest::{Harness, kittest::NodeT}; use lightcraft_ui_egui::{LightcraftApp, Services}; fn harness() -> Harness<'static, LightcraftApp> { - let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + app.headless_host = true; let mut h = Harness::builder().with_size(vec2(1500.0, 950.0)).build_ui_state( |ui, app: &mut LightcraftApp| { app.logic(&ui.ctx().clone()); diff --git a/crates/ui-egui/tests/it/docking_workflows.rs b/crates/ui-egui/tests/it/docking_workflows.rs index 54ad8f186f..75f845ede0 100644 --- a/crates/ui-egui/tests/it/docking_workflows.rs +++ b/crates/ui-egui/tests/it/docking_workflows.rs @@ -8,6 +8,8 @@ use std::time::{Duration, Instant}; fn harness(state: Option, width: f32, scale: f32) -> Harness<'static, LightcraftApp> { let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + // a headless host never gains the first-run tour: its modal would take the pointer the drags aim at + app.headless_host = true; if let Some(state) = state { app.ui = state; } else { diff --git a/crates/ui-egui/tests/it/local_places.rs b/crates/ui-egui/tests/it/local_places.rs index 11e20de3bf..6fe45f92c3 100644 --- a/crates/ui-egui/tests/it/local_places.rs +++ b/crates/ui-egui/tests/it/local_places.rs @@ -35,6 +35,7 @@ impl Drop for Scratch { fn harness(places: Vec<(String, String)>, kept: Vec) -> Harness<'static, LightcraftApp> { let services = Services { local_places: Some(places), pick_folder: Some(Box::new(|| None)), ..Default::default() }; let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), services); + app.headless_host = true; app.ui.left_panel = true; app.ui.local_roots = kept; let mut h = Harness::builder().with_size(vec2(1000.0, 800.0)).build_ui_state( diff --git a/crates/ui-egui/tests/it/sidebar_names.rs b/crates/ui-egui/tests/it/sidebar_names.rs index e063a42b74..a6e35aca2a 100644 --- a/crates/ui-egui/tests/it/sidebar_names.rs +++ b/crates/ui-egui/tests/it/sidebar_names.rs @@ -13,6 +13,7 @@ use lightcraft_ui_egui::{ fn sidebar() -> Harness<'static, LightcraftApp> { let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + app.headless_host = true; app.ui.left_panel = true; app.ui.view = ViewMode::PhotoGrid; app.ui.right = RightPanel::None; @@ -51,6 +52,7 @@ fn a_month_triangle_names_its_year() { session.catalog.apply(lightcraft_catalog::Op::SetCaptured { id, captured: Some(captured.into()) }).expect("the capture time is set"); } let mut app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + app.headless_host = true; app.ui.left_panel = true; app.ui.view = ViewMode::PhotoGrid; app.ui.right = RightPanel::None; @@ -85,6 +87,7 @@ fn a_keyword_list_triangle_names_its_keyword() { session.execute("keyword.create", ¶ms).expect("a keyword is created"); } let mut app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + app.headless_host = true; app.ui.left_panel = false; app.ui.view = ViewMode::PhotoGrid; app.ui.right = RightPanel::Keywords; diff --git a/crates/ui-egui/tests/it/thumb_size_slider.rs b/crates/ui-egui/tests/it/thumb_size_slider.rs index c16837d84f..040ab427ea 100644 --- a/crates/ui-egui/tests/it/thumb_size_slider.rs +++ b/crates/ui-egui/tests/it/thumb_size_slider.rs @@ -12,6 +12,7 @@ const NAME: &str = "Thumbnail size"; fn grid() -> Harness<'static, LightcraftApp> { let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + app.headless_host = true; app.ui.view = ViewMode::PhotoGrid; app.ui.right = RightPanel::None; let mut h = Harness::builder().with_size(vec2(1500.0, 950.0)).build_ui_state( From 96f3fd2d6120c9e0730cf6f768a0491645ea540d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 23:45:53 +0100 Subject: [PATCH 20/24] Tests: the next folder drop gets 20 seconds to land (#3834) It checked the file on the frame after the drop, which failed on busy Windows runners. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/tests/folder_drop.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/folder_drop.rs b/crates/ui-egui/src/tests/folder_drop.rs index 11b5ae2f7f..ba1dc5c501 100644 --- a/crates/ui-egui/src/tests/folder_drop.rs +++ b/crates/ui-egui/src/tests/folder_drop.rs @@ -339,7 +339,9 @@ fn dont_ask_again_moves_the_next_drop_at_once() { let target = folder_row(&h, &home).unwrap(); drop_beach(&mut h, dunes, target); assert!(h.app.ui.dialog.is_none(), "not asked"); - assert!(home.join("dunes.png").is_file(), "moved at once"); + // no question comes first, but the file itself can take a moment on a busy machine + let moved = home.join("dunes.png"); + assert!(h.step_until(std::time::Duration::from_secs(20), |_| moved.is_file()), "moved without a question"); let _ = std::fs::remove_dir_all(&root); } From 0429844cd9dbdf320d78262b0a4ad64ee21f3447 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 01:29:41 +0200 Subject: [PATCH 21/24] never-crash: deny the panic lints in every crate root; GPU asserts become fail paths (#2137) (#2170) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * never-crash: deny the panic lints in every crate root; GPU asserts become fail paths (#2137) The never-crash policy was documented but not machine-checked for the two largest crates: engine and meta carried only #![forbid(unsafe_code)], so a future unwrap/expect/panic would pass cargo xtask ci. Both crate roots now also carry as does xtask (previously un-annotated); the guarded expects in meta/src/xmp.rs and xtask's parity.rs / root() now use the documented #[allow(clippy::expect_used)] + invariant form. crates/gpu: the three production asserts become fail(FailKind::Fatal, ..) + return, so a binding-count mismatch, an over-long readback, or a wrong-length curve fails the render over to the CPU instead of crashing (finish_and_read also early-returns on len == 0, which would have issued a zero-size copy_buffer_to_buffer that wgpu rejects). xtask: new roots check (in ci) verifies every workspace lib root and every binary main.rs carries both attributes; crates/sysmem is the documented exception for forbid(unsafe_code) only. A panic in placement or readback is a fail, not a crash. * audit fixes: roots covers binary and cdylib/rlib roots; render gates on failed() after finish_block (#2137) Two reviewers audited the first commit; both highs it found are fixed here: - roots scanner: the by_ref().any()/any() pair consumed the kind iterator hunting for "lib", so every bin-only root (both app mains, the sam3-worker bin, xtask itself) and the cdylib/rlib web root was silently unchecked — the check covered 29 of the 33 real roots. Kind detection now collects the kinds once and matches lib/rlib/dylib/cdylib/staticlib, with a root_paths regression test over bin, lib and cdylib/rlib targets; unreadable root files now fail with the I/O error instead of a fake policy violation. - render.rs: the caller gates on failed() right after finish_block, so the malformed-curve fail path can no longer reach the band loop's p[y0_at] index on the empty block. - finish_and_read: the len == 0 path now submits the encoder before returning zeros, so a failure staged in the same render stays detectable (the old zero-size copy failed loudly via the error scopes; a bare return would have hidden it). - docs: finish_block and finish_and_read state their failure contracts; USAGE and AGENTS.md name the new roots step in the ci enumeration. * xtask: check a library root at the source path that cargo metadata reports The roots check read src/lib.rs for every library target, so a package that sets its library path was checked on the wrong file. Libraries now use the reported source path, with the same default as binaries when none is given. * xtask: match the crate-root deny lints by whole name, ignoring a trailing comment A lint named only in a trailing comment, or a lint whose name contains another (clippy::panic inside clippy::panic_in_result_fn), satisfied the deny check. Lint names are now compared whole and a trailing comment is ignored. * xtask: read the crate-root attributes from the header, not a fixed 30 lines The roots check read only the first 30 lines of each crate root, so a root whose attributes came after a longer doc header was reported as missing them. The check now reads the inner attributes at the top of the file: it skips blank lines and comments, reads each attribute whole, and stops at the first item. A multi-line list is read in full and a commented-out attribute does not count. * xtask: reword two comments in the roots check Comments only: the lint-name match and the source-path default are described without naming a lint or a build tool. No code changes. * xtask: report a root attribute that overrides the required denies * xtask: accept a runtime manifest dir only when it has a parent * xtask: render the overridden deny attribute without literal braces The write! escaped the braces around the substituted attribute and lint, so the violation printed `#![{allow}({clippy::panic})]`; assert the rendered message in the allow-override test. * Tests: new test helpers meet the crate-root panic lints Main added test helpers after this branch; the deny at the crate root now applies to them. Co-Authored-By: Claude Opus 5.5 * roots: crates/wincolor is the second crate allowed unsafe Main added it for the Windows colour APIs after this branch; its module docs already say so. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 15 +- CLAUDE.md | 6 +- crates/engine/src/denoise.rs | 5 +- crates/engine/src/denoise/builtin/tests.rs | 1 + crates/engine/src/export/tests.rs | 2 +- crates/engine/src/face_download.rs | 5 +- crates/engine/src/lensfun_download.rs | 2 + crates/engine/src/lib.rs | 1 + crates/engine/src/lightroom_catalog/tests.rs | 2 +- crates/engine/src/model_download.rs | 5 +- crates/engine/src/tests/import.rs | 2 +- crates/gpu/src/ctx.rs | 58 ++- crates/gpu/src/params.rs | 17 +- crates/gpu/src/render.rs | 3 + crates/meta/src/lib.rs | 1 + crates/meta/src/xmp.rs | 9 +- xtask/src/ci.rs | 3 +- xtask/src/ci_quick.rs | 2 +- xtask/src/main.rs | 50 ++- xtask/src/parity.rs | 1 + xtask/src/roots.rs | 432 +++++++++++++++++++ 21 files changed, 592 insertions(+), 30 deletions(-) create mode 100644 xtask/src/roots.rs diff --git a/AGENTS.md b/AGENTS.md index 72858c816d..f179510775 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,10 +50,15 @@ of it. - **Last-resort guard:** a panic hook plus `catch_unwind` around command dispatch and import/export turns an escaped panic into an error dialog and keeps the document. It's a safety net, not a licence; keep `panic = "unwind"` on native. - **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix. -- Enforced by clippy: root `clippy.toml` allows unwrap/expect/panic in tests only; indexing is not denied. Every production crate - root (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, - clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Not `[workspace.lints]`: those would also hit - integration tests, examples and benches. New crates start with the attribute. +- Enforced by clippy: root `clippy.toml` keeps unwrap/expect/panic allowances scoped to tests; indexing is not denied. The workspace + denies `cognitive_complexity`, `too_many_arguments` and `wildcard_imports`; members inherit them with + `[lints] workspace = true`, and `sysmem` repeats those denies in its local lint table. Every production crate root + (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, + clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include + `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include + the attribute before modules or other crate items; crate-level `//!` documentation may precede it. `cargo xtask roots` + (part of `ci` and `ci --quick`) machine-checks that every root, including binary-only crates and the `cdylib`/`rlib` + web build, carries both this and the `#![forbid(unsafe_code)]` above (`crates/sysmem` is the one forbid exception). ## Non-negotiables - **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…). @@ -62,7 +67,7 @@ of it. - **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP all dispatch by id. Every slider is a `develop` control spec. - **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match. - **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm). +- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, roots, wasm). - **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment. ## Assets: icons, images, fonts (ABSOLUTE RULE — never violate) diff --git a/CLAUDE.md b/CLAUDE.md index 5aac6471de..6ef579697e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,9 @@ of it. (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include - the attribute before modules or other crate items; crate-level `//!` documentation may precede it. + the attribute before modules or other crate items; crate-level `//!` documentation may precede it. `cargo xtask roots` + (part of `ci` and `ci --quick`) machine-checks that every root, including binary-only crates and the `cdylib`/`rlib` + web build, carries both this and the `#![forbid(unsafe_code)]` above (`crates/sysmem` is the one forbid exception). ## Non-negotiables - **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…). @@ -71,7 +73,7 @@ of it. - **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match. - **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Quality gates** before every commit: `cargo xtask ci --quick` (fmt, clippy -D warnings, the changed packages' - tests, layers, assets, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR + tests, layers, assets, roots, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR (`.github/workflows/ci.yml`); run the full one locally before merging branches (below) or when `--quick` can't see the risk. One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`). - **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment. diff --git a/crates/engine/src/denoise.rs b/crates/engine/src/denoise.rs index d12c97f6ff..1eb2544d4b 100644 --- a/crates/engine/src/denoise.rs +++ b/crates/engine/src/denoise.rs @@ -64,5 +64,8 @@ pub(crate) use settings::{Settings, forget_gpu_set_ups, installed_models, read_c pub(crate) use state::State; pub use state::{Pace, PhotoState}; -#[cfg(all(test, feature = "denoise"))] +// Two stacked cfgs (not `all(test, feature = …)`): clippy only recognises a plain `cfg(test)` +// module as test code, so the `allow-*-in-tests` settings in clippy.toml apply to its helpers. +#[cfg(test)] +#[cfg(feature = "denoise")] mod gpu_tests; diff --git a/crates/engine/src/denoise/builtin/tests.rs b/crates/engine/src/denoise/builtin/tests.rs index ef85e8559f..e5416bfd00 100644 --- a/crates/engine/src/denoise/builtin/tests.rs +++ b/crates/engine/src/denoise/builtin/tests.rs @@ -2,6 +2,7 @@ use super::*; use crate::denoise::forget_gpu_set_ups; /// A folder of the test's own: the card's set-up leaves its marker in it. +#[allow(clippy::unwrap_used)] fn folder(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("lc-engine-builtin-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index 86600ddb57..d1d387b26f 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -225,7 +225,7 @@ fn sharpened_pixels_are_pinned() { let samples = src.data.iter().flat_map(|p| [p[0], p[1], p[2]].map(|v| u16::from(v) * 257)).collect(); let mut deep = DeepImage { width: src.width, height: src.height, samples: DeepSamples::U16(samples), space: OutputSpace::Srgb }; output_sharpen_deep(&mut deep, target, SharpenAmount::Standard); - let DeepSamples::U16(v) = &deep.samples else { unreachable!() }; + let DeepSamples::U16(v) = &deep.samples else { panic!("expected U16 samples") }; got.push(fnv(&v.iter().flat_map(|s| s.to_le_bytes()).collect::>())); } assert_eq!(got, SHARPENED, "{got:#x?}"); diff --git a/crates/engine/src/face_download.rs b/crates/engine/src/face_download.rs index f5d0dd5fcb..46d3a845ca 100644 --- a/crates/engine/src/face_download.rs +++ b/crates/engine/src/face_download.rs @@ -246,7 +246,10 @@ fn run(spec: &Download, mirror: &str, staging: &Path, shared: &Shared) { } } -#[cfg(all(test, not(target_arch = "wasm32")))] +// Two stacked cfgs (not `all(test, …)`): clippy only recognises a plain `cfg(test)` +// module as test code, so the `allow-*-in-tests` settings in clippy.toml apply to its helpers. +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] mod tests { use super::*; use lightcraft_faces::hash::sha256_hex; diff --git a/crates/engine/src/lensfun_download.rs b/crates/engine/src/lensfun_download.rs index c24b07f7a9..9eb382526f 100644 --- a/crates/engine/src/lensfun_download.rs +++ b/crates/engine/src/lensfun_download.rs @@ -608,6 +608,7 @@ mod tests { let _ = std::fs::remove_file(beside(&dir, LOCK)); } + #[allow(clippy::unwrap_used)] 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)] { @@ -618,6 +619,7 @@ mod tests { } /// A local server answering `GET /db/` with that file's body (404 otherwise). + #[allow(clippy::unwrap_used)] fn serve(files: Vec<(&'static str, Vec)>) -> String { let l = TcpListener::bind("127.0.0.1:0").unwrap(); let base = format!("http://{}/db", l.local_addr().unwrap()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b0e3d2b9e5..53077f95c6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -9,6 +9,7 @@ //! of decoded source proxies. Rendering is done by [`RenderJob`]s that are `Send` so frontends can //! run them off the UI thread. #![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] // Model/cache types remain available without linking the optional inference crate. #[cfg(not(feature = "denoise"))] diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 06739138c1..e2952fd000 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -1122,7 +1122,7 @@ fn record(values: &[SqlValue]) -> Vec { body.extend(s.as_bytes()); 13 + 2 * s.len() as u64 } - _ => unreachable!(), + _ => panic!("unexpected SqlValue in a test record: {value:?}"), }; header.extend(varint(serial)); } diff --git a/crates/engine/src/model_download.rs b/crates/engine/src/model_download.rs index 96f5eb1c74..9dcf025a3d 100644 --- a/crates/engine/src/model_download.rs +++ b/crates/engine/src/model_download.rs @@ -226,7 +226,10 @@ fn run(spec: &Download, mirror: &str, staging: &Path, shared: &Shared) { } } -#[cfg(all(test, not(target_arch = "wasm32")))] +// Two stacked cfgs (not `all(test, …)`): clippy only recognises a plain `cfg(test)` +// module as test code, so the `allow-*-in-tests` settings in clippy.toml apply to its helpers. +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] mod tests { use super::*; use lightcraft_denoise::hash::sha256_hex; diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 49176077fb..5df2ac680d 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -853,7 +853,7 @@ fn import_rename_sequence_keeps_flushed_copy_and_move_results() { assert!(paths[3].is_file(), "the failed source remains in place"); assert_eq!(r["moved"].as_array().map(Vec::len), Some(3), "{r}"); } - _ => unreachable!(), + other => panic!("no such mode: {other}"), } let _ = std::fs::remove_dir_all(base); } diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 2735116e39..290b95ac99 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -556,8 +556,12 @@ impl Gpu { } /// Submit command buffers, then make the buffers this thread dropped before reusable. + /// Nothing is submitted once this render has failed: the render is discarded and recomputed + /// on the CPU, and the failure contract says no further GPU work runs after a fatal failure. pub fn submit(&self, cmds: impl IntoIterator) { - self.queue.submit(cmds); + if !failed() { + self.queue.submit(cmds); + } let retired = take_retired(); self.pool(retired); } @@ -610,6 +614,12 @@ impl Gpu { pub fn upload(&self, data: &[T]) -> Buf { let bytes: &[u8] = bytemuck::cast_slice(data); let len = bytes.len() / 4; + // A failed render runs no further GPU work (`Gpu::submit` skips the submission and the + // render is redone on the CPU): staging the bytes would still queue a copy for the next + // submission, so the caller gets the placeholder with the requested length instead. + if failed() { + return Buf { buf: Some(Tracked::new(self.placeholder())), len }; + } if bytes.is_empty() { return self.buffer(1); } @@ -715,7 +725,12 @@ impl Gpu { fail(FailKind::Fatal, format!("unknown kernel {name}")); return; }; - assert_eq!(bufs.len(), k.nbuf, "{name}: binding count"); + if bufs.len() != k.nbuf { + // a caller/kernel mismatch would bind the wrong buffers: fail this render over to the + // CPU instead of crashing + fail(FailKind::Fatal, format!("{name}: binding count {} != {}", bufs.len(), k.nbuf)); + return; + } let params = self.init_buffer(bytemuck::cast_slice(if p.is_empty() { &[0u32] } else { p }), wgpu::BufferUsages::STORAGE); let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: params.as_entire_binding() }]; for (i, b) in bufs.iter().enumerate() { @@ -731,15 +746,27 @@ impl Gpu { /// Submit `enc`, then read back the first `len` 32-bit values of `src`. /// - /// A failed readback (device lost, map error, timeout) fails the render ([`FailKind::Fatal`]) - /// and returns zeros, which the caller discards; after an earlier failure in the same render - /// nothing more is submitted. + /// A failed readback (device lost, map error, timeout) or a `len` past the buffer's end fails + /// the render ([`FailKind::Fatal`]) and returns zeros, which the caller discards; after an + /// earlier failure in the same render nothing more is submitted. `T` is always a 32-bit type + /// at the call sites (the copy and the readback tail are defined in 32-bit words). pub fn finish_and_read(&self, mut enc: wgpu::CommandEncoder, src: &Buf, len: usize) -> Vec { - assert!(len <= src.len, "readback of {len} values from a buffer of {}", src.len); let zeros = || vec![::zeroed(); len]; if failed() { return zeros(); } + // a zero-length readback would issue a `copy_buffer_to_buffer` of size 0, which wgpu + // rejects as an invalid copy: submit the (possibly staged) work untouched and return + // zeros instead + if len == 0 { + self.submit([enc.finish()]); + return zeros(); + } + if len > src.len { + // a caller bug would read past the buffer: fail this render over to the CPU + fail(FailKind::Fatal, format!("readback of {len} values from a buffer of {}", src.len)); + return zeros(); + } let size = (len * 4) as u64; let staging = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), @@ -1193,6 +1220,25 @@ mod tests { let back: Vec<[u32; 3]> = g.finish_and_read(g.encoder(), &b, data.len()); assert!(back.len() == 1 << 20 && back.as_flattened() == data.as_slice()); } + /// An upload after this render has failed keeps the failure contract (`Gpu::submit` skips the + /// submission, so nothing further runs on the GPU): the caller gets the placeholder with the + /// requested length instead of a staging buffer holding a copy of the data for a submission + /// that will never happen. + #[test] + fn an_upload_after_a_failure_returns_the_placeholder() { + let Some(g) = crate::device() else { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + return; + }; + super::fail(super::FailKind::Fatal, "simulated failure before an upload".into()); + assert!(super::failed()); + let b = g.upload(&[7u32; 1024]); + assert_eq!(b.buf.as_ref().map(|t| t.0.size()), Some(16), "the placeholder, not a staged 4 KiB buffer"); + assert_eq!(b.len, 1024, "the requested length is preserved"); + // leave this thread's failure for nobody: later tests on the thread start unfailed + assert_eq!(super::take_failure().map(|f| f.kind), Some(super::FailKind::Fatal)); + } + /// Issue #1858: once a Vulkan or DX12 device is lost, wgpu 30 panics in `Device::poll` instead of /// returning an error. A render's readback panicked; while it unwound, a buffer's way back to /// the pool polls again from a destructor, and that second panic aborted the app. diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index 8c8624a23c..97244b6a04 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -5,6 +5,8 @@ use lightcraft_develop::VignetteStyle; use lightcraft_pipeline::colorops::POINT_WORDS; use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, srgb_lut}; +use crate::ctx::{FailKind, fail}; + /// Entries per tone-curve table (`lightcraft_pipeline::finish` builds them at this size). pub const CURVE_N: u32 = 1024; @@ -168,6 +170,9 @@ pub struct Present { /// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs | /// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms). +/// +/// A curve whose length is not [`CURVE_N`] fails the render ([`FailKind::Fatal`]) and returns an +/// empty parameter block with a truncated aux table, which the caller discards (CPU fallback). pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec, Vec) { let mut aux: Vec = fp.tone.lut().to_vec(); aux.extend_from_slice(fp.tone.chroma_lut()); @@ -176,7 +181,17 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr let curve_off = aux.len(); if let Some(c) = &fp.curves { for l in c { - assert_eq!(l.v.len(), CURVE_N as usize); + if l.v.len() != CURVE_N as usize { + // a wrong-length curve would shift every later aux offset (CURVE_OFF, MASK_OFF and + // the mask terms that follow) and make the kernel read the wrong data. `fail()` + // records the failure on this thread so the render falls back to the CPU; the + // partial `(p, aux)` returned here is never bound to a pipeline. + fail(FailKind::Fatal, format!("curve table has {} entries, expected {}", l.v.len(), CURVE_N)); + // `p` is only assembled below the curve loop, so an empty block is as good as any: + // the caller (render.rs) gates on `failed()` right after this returns and bails to + // the CPU fallback before indexing `p` or uploading `aux`. + return (Vec::new(), aux); + } aux.extend_from_slice(&l.v); } } diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 701cc3c5de..5a60e547ea 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -764,6 +764,9 @@ pub fn render( (None, None) => None, }; let (p, aux) = finish_block(&fp, &terms, &present); + if crate::ctx::failed() { + return None; // a malformed parameter block failed the render: the CPU fallback redoes it + } let aux = gpu.upload(&aux); // cleared, so that work which never ran cannot pass for an image (see the check below) let out = cx.zeroed(n); diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index ffa0d2f83b..91186e3d8c 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -12,6 +12,7 @@ //! - [`cr3`] — the Canon CR3 container (metadata blocks, XMP, the JPEG and raw tracks). //! - [`heif`] — the HEIF/HEIC/AVIF container's Exif and XMP items (no HEVC decoder needed). #![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod container; pub mod cr3; diff --git a/crates/meta/src/xmp.rs b/crates/meta/src/xmp.rs index bb23bfd1ff..958abed653 100644 --- a/crates/meta/src/xmp.rs +++ b/crates/meta/src/xmp.rs @@ -305,7 +305,7 @@ fn parse_tree(s: &str) -> Result { } } Event::End(_) if stack.len() > 1 => { - let n = stack.pop().expect("len > 1"); + let Some(n) = stack.pop() else { return Err(XmpError::Xml("end tag without an open element".into())) }; scopes.pop(); if let Some(parent) = stack.last_mut() { parent.children.push(n); @@ -340,10 +340,11 @@ fn parse_tree(s: &str) -> Result { } // close unterminated elements leniently while stack.len() > 1 { - let n = stack.pop().expect("len > 1"); - stack.last_mut().expect("root").children.push(n); + let Some(n) = stack.pop() else { return Err(XmpError::Xml("unterminated element without a node".into())) }; + let Some(parent) = stack.last_mut() else { return Err(XmpError::Xml("unterminated element without a parent".into())) }; + parent.children.push(n); } - Ok(stack.pop().expect("root")) + stack.pop().ok_or_else(|| XmpError::Xml("xmp packet without a root element".into())) } fn is_rdf_meta_attr(k: &str) -> bool { diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 6b55595706..556ea01b12 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -1,7 +1,7 @@ use super::layers::cmd_layers; use super::raw_samples::RAW_SAMPLES; use super::wasm::{cmd_wasm, cmd_wasm_for}; -use super::{Command, Path, PathBuf, USAGE, assets, cargo, ci_lock, ci_quick, ci_report, metadata, parity, root, run}; +use super::{Command, Path, PathBuf, USAGE, assets, cargo, ci_lock, ci_quick, ci_report, metadata, parity, root, roots, run}; /// CI build jobs: one per 1.5 GB of RAM available when CI starts, at most one per CPU, 4 when it /// is unknown. With line-table debuginfo, 4 jobs measured about 3 GB of RAM in use and 2 jobs @@ -339,6 +339,7 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { } steps.push(("layers", Box::new(cmd_layers))); steps.push(("assets", Box::new(|| assets::run(&root)))); + steps.push(("roots", Box::new(roots::run))); if wants("wasm") { match plan.as_ref().filter(|p| !p.workspace_wide) { Some(p) => steps.push(("wasm", Box::new(|| cmd_wasm_for(Some(&p.packages))))), diff --git a/xtask/src/ci_quick.rs b/xtask/src/ci_quick.rs index be3e5777df..2143d09bbb 100644 --- a/xtask/src/ci_quick.rs +++ b/xtask/src/ci_quick.rs @@ -4,7 +4,7 @@ //! parity check, ~23 minutes cold. `--quick` looks at what changed since the merge base with //! `origin/main` (or `--base REF`), committed or not, and runs: //! -//! - fmt, layers, assets: always (seconds); +//! - fmt, layers, assets, roots: always (seconds); //! - clippy on the whole workspace (check builds only; catches callers broken by an API change); //! - the tests of the changed packages only (not their dependents); //! - heif when `lightcraft-codecs` / `lightcraft-heif` changed; diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 153498a009..33b236b56d 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -2,6 +2,8 @@ //! //! Pure Rust (std + serde_json; flate2/brotli for the web bundle). External tools (`cargo`, `curl`, `tar`) are //! invoked through `std::process::Command`. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod assets; mod bench; @@ -11,6 +13,7 @@ mod ci_report; mod ico; mod layers; mod parity; +mod roots; mod stats; mod version; mod web; @@ -39,6 +42,8 @@ commands: ico ... pack square PNGs (<= 256 px) into a Windows .ico (see packaging/icons.sh) layers enforce the crate dependency layering (plan/architecture.md §3) + roots every production crate root carries #![forbid(unsafe_code)] and the six-lint + deny list (AGENTS.md; crates/sysmem is exempt from the forbid only) parity [--write] check docs/parity-checklist.md (every cmd:/ctl: id and path it cites exists) and print the Lightroom parity summary; --write refreshes the summary table in the document @@ -47,7 +52,7 @@ commands: build the browser app (apps/lightcraft-web) into /web-site/; --serve serves it on http://127.0.0.1: (default 8080) ci [--hardware] [--summary-md] [--quick [--base REF]] - fmt --check, clippy -D warnings, heif, test, GPU probe, parity refs, layers, assets, wasm + fmt --check, clippy -D warnings, heif, test, GPU probe, parity refs, layers, assets, roots, wasm (stops at first failure). Tests run under cargo test (cargo nextest with LIGHTCRAFT_NEXTEST=1), without examples, then doctests with cargo test --doc; after them it prints the translation gaps report (never a failure). Writes @@ -75,6 +80,7 @@ fn main() -> ExitCode { Some("ico") => ico::run(&rest), Some("version") => version::run(&root(), &rest), Some("layers") => cmd_layers(), + Some("roots") => roots::run(), Some("assets") => assets::run(&root()), Some("bench") => bench::run(&root(), &rest), Some("parity") => parity::run(&root(), rest.contains(&"--write")), @@ -117,9 +123,17 @@ fn cmd_raw_frame(files: &[&str]) -> Result<(), String> { pub fn root() -> PathBuf { // `cargo run` sets it at run time; prefer that over the compile-time value, which goes stale // when the checkout moves and the cached xtask binary isn't rebuilt - let dir = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from).filter(|d| d.join("Cargo.toml").is_file()); - let dir = dir.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR"))); - dir.parent().expect("xtask has a parent dir").to_path_buf() + workspace_root(std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from).filter(|d| d.join("Cargo.toml").is_file()), env!("CARGO_MANIFEST_DIR")) +} + +/// The workspace root for an xtask-crate directory. A runtime manifest dir (already checked to +/// carry Cargo.toml) wins only when it has a parent: a filesystem root or an empty path names no +/// crate below a workspace, and there is no directory above it. The compile-time fallback +/// (`/xtask`) always has a parent; without one the crate dir itself is the best +/// remaining answer. +fn workspace_root(runtime_manifest_dir: Option, compile_time_manifest_dir: &str) -> PathBuf { + let dir = runtime_manifest_dir.filter(|d| d.parent().is_some()).unwrap_or_else(|| PathBuf::from(compile_time_manifest_dir)); + dir.parent().map_or_else(|| dir.clone(), Path::to_path_buf) } pub fn cargo() -> Command { @@ -164,3 +178,31 @@ pub fn metadata() -> Result { } serde_json::from_slice(&out.stdout).map_err(|e| format!("cargo metadata: bad JSON: {e}")) } + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + + /// A runtime `CARGO_MANIFEST_DIR` without a parent (`/`, or an empty path) cannot name the + /// xtask crate: the parent lookup used to crash on it, and the workspace root falls back to + /// the compile-time value instead. + #[test] + fn a_runtime_manifest_dir_without_a_parent_is_not_the_workspace_root() { + let root = super::workspace_root(Some(PathBuf::from("/")), "/checkout/xtask"); + assert_eq!(root, Path::new("/checkout")); + let root = super::workspace_root(Some(PathBuf::from("")), "/checkout/xtask"); + assert_eq!(root, Path::new("/checkout")); + } + + #[test] + fn a_runtime_manifest_dir_names_its_own_workspace() { + let root = super::workspace_root(Some(PathBuf::from("/checkout/xtask")), "/elsewhere/xtask"); + assert_eq!(root, Path::new("/checkout")); + } + + #[test] + fn without_a_runtime_value_the_compile_time_manifest_dir_decides() { + let root = super::workspace_root(None, "/checkout/xtask"); + assert_eq!(root, Path::new("/checkout")); + } +} diff --git a/xtask/src/parity.rs b/xtask/src/parity.rs index 7adcfc6c02..4c85c0acaa 100644 --- a/xtask/src/parity.rs +++ b/xtask/src/parity.rs @@ -237,6 +237,7 @@ pub fn summarize(doc: &Doc) -> (Vec<(String, Counts)>, Counts) { if sections.last().is_none_or(|(s, _)| *s != r.section) { sections.push((r.section.clone(), Counts::default())); } + #[allow(clippy::expect_used)] // either non-empty above or a section was just pushed sections.last_mut().expect("pushed").1.add(r); total.add(r); } diff --git a/xtask/src/roots.rs b/xtask/src/roots.rs new file mode 100644 index 0000000000..440229bd16 --- /dev/null +++ b/xtask/src/roots.rs @@ -0,0 +1,432 @@ +//! Crate-root lint attributes: every production crate root carries both `#![forbid(unsafe_code)]` +//! and the deny list (`clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, +//! `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`). +//! +//! Machine-enforced so a future crate can't silently drop the never-crash policy (AGENTS.md). +//! `check` works on already-read file contents so it is unit-testable without the real tree. +//! +//! Exception: `crates/wincolor` calls Windows' colour APIs, so it is exempt too (see its module docs). +//! Exception (documented in AGENTS.md): `crates/sysmem` holds LightCraft's other allowed `unsafe` +//! (one FFI call), so it is exempt from `forbid(unsafe_code)` — it still needs the deny list, and +//! carries it. + +use std::path::PathBuf; + +const DENY_LINTS: &[&str] = + &["clippy::unwrap_used", "clippy::expect_used", "clippy::panic", "clippy::unimplemented", "clippy::todo", "clippy::unreachable"]; + +/// Crate roots exempt from `forbid(unsafe_code)` (they still need the deny list). +const UNSAFE_EXCEPTION: &[&str] = &["lightcraft-sysmem", "lightcraft-wincolor"]; + +#[derive(Debug, Clone)] +pub struct CrateRoot { + pub name: String, + /// The root source file (`src/lib.rs` for libs, `src/main.rs` for binaries). + pub root: PathBuf, + /// Its contents, already read (kept separate so `check` needs no filesystem). + pub src: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Violation { + MissingForbid { + name: String, + path: PathBuf, + }, + MissingDeny { + name: String, + path: PathBuf, + }, + /// A crate-root `allow`/`expect`/`warn` names a required lint: rustc applies the later + /// attribute over the deny list, so the lint is not denied after all. + OverriddenDeny { + name: String, + path: PathBuf, + attribute: String, + lint: String, + }, +} + +impl std::fmt::Display for Violation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Violation::MissingForbid { name, path } => { + write!(f, "{name}: missing `#![forbid(unsafe_code)]` in {}", path.display()) + } + Violation::MissingDeny { name, path } => { + write!(f, "{name}: missing `#![deny(...)]` with all six clippy lints in {}", path.display()) + } + Violation::OverriddenDeny { name, path, attribute, lint } => { + write!(f, "{name}: the crate-root `#![{attribute}({lint})]` overrides the required deny list in {}", path.display()) + } + } + } +} + +/// Check every crate root carries both attributes; violations sorted for stable output. +pub fn check(roots: &[CrateRoot]) -> Vec { + let mut out = Vec::new(); + for r in roots { + let is_unsafe_exception = UNSAFE_EXCEPTION.contains(&r.name.as_str()); + // the inner attributes before the first item, however long the doc header above them is + let attrs = inner_attrs(&r.src); + let has_forbid = attrs.iter().any(|a| a == "#![forbid(unsafe_code)]"); + let has_deny = + attrs.iter().any(|a| lint_list(a).is_some_and(|(verb, names)| verb == "deny" && DENY_LINTS.iter().all(|lint| names.contains(lint)))); + // a later crate-root `allow`/`expect`/`warn` naming a required lint applies over the deny + // list (rustc takes the later attribute), so the policy silently stops holding + let mut overridden: Option<(&str, &str)> = None; + for a in &attrs { + let Some((verb, names)) = lint_list(a) else { continue }; + if !matches!(verb, "allow" | "expect" | "warn") { + continue; + } + if let Some(lint) = names.iter().find(|n| DENY_LINTS.contains(n)) { + overridden = Some((verb, lint)); + break; + } + } + if !has_forbid && !is_unsafe_exception { + out.push(Violation::MissingForbid { name: r.name.clone(), path: r.root.clone() }); + } + if !has_deny { + out.push(Violation::MissingDeny { name: r.name.clone(), path: r.root.clone() }); + } + if let Some((attribute, lint)) = overridden { + out.push(Violation::OverriddenDeny { + name: r.name.clone(), + path: r.root.clone(), + attribute: attribute.to_string(), + lint: lint.to_string(), + }); + } + } + out.sort_by_key(|v| v.to_string()); + out.dedup(); + out +} + +/// The verb and the lint names of a root `#![verb(...)]` attribute, or `None` for anything else. +/// Names are compared whole, so a longer name that starts with a listed name does not count. +fn lint_list(attr: &str) -> Option<(&str, Vec<&str>)> { + let body = attr.strip_prefix("#![")?.strip_suffix(")]")?; + let (verb, names) = body.split_once('(')?; + Some((verb, names.split(',').map(str::trim).filter(|n| !n.is_empty()).collect())) +} + +/// The inner attributes (`#![...]`) at the top of a crate root, each with its whitespace removed. +/// Blank lines and comments before them are skipped, and the scan stops at the first item, so the +/// length of the doc header does not matter and an attribute inside a nested module is never read. +fn inner_attrs(src: &str) -> Vec { + let b = src.as_bytes(); + let mut out = Vec::new(); + let mut i = skip_trivia(b, 0); + while b.get(i..).is_some_and(|rest| rest.starts_with(b"#![")) { + let start = i; + let mut depth = 0usize; + let mut in_str = false; + while let Some(&c) = b.get(i) { + i += 1; + if in_str { + match c { + b'\\' => i += 1, + b'"' => in_str = false, + _ => {} + } + } else { + match c { + b'"' => in_str = true, + b'[' => depth += 1, + b']' => { + depth = depth.saturating_sub(1); + if depth == 0 { + break; + } + } + _ => {} + } + } + } + let Some(text) = src.get(start..i) else { break }; + out.push(text.split_whitespace().collect()); + i = skip_trivia(b, i); + } + out +} + +/// The first index at or after `i` that is neither whitespace nor part of a comment. +fn skip_trivia(b: &[u8], mut i: usize) -> usize { + loop { + while b.get(i).is_some_and(u8::is_ascii_whitespace) { + i += 1; + } + let rest = b.get(i..).unwrap_or_default(); + if rest.starts_with(b"//") { + while b.get(i).is_some_and(|&c| c != b'\n') { + i += 1; + } + } else if rest.starts_with(b"/*") { + i = skip_block_comment(b, i); + } else { + return i; + } + } +} + +/// The index just past the block comment that starts at `i` (block comments nest, as in Rust). +fn skip_block_comment(b: &[u8], mut i: usize) -> usize { + let mut depth = 0usize; + loop { + match b.get(i..) { + Some(rest) if rest.starts_with(b"/*") => { + depth += 1; + i += 2; + } + Some(rest) if rest.starts_with(b"*/") => { + depth = depth.saturating_sub(1); + i += 2; + if depth == 0 { + return i; + } + } + Some(_) => i += 1, + None => return i, + } + } +} + +/// Collect the (package name, root source path) pairs for every workspace lib/bin target. +/// `src_path` from the package metadata is absolute and is used as it is; without it, libs default to the +/// manifest's `src/lib.rs` and binaries to `src/main.rs`. +/// Library kinds include `rlib`/`cdylib` so roots like the web build's `crate-type = +/// ["cdylib", "rlib"]` are covered, and `proc-macro`, which cargo reports as a kind of its own. +pub fn root_paths(meta: &serde_json::Value) -> Result, String> { + let pkgs = meta["packages"].as_array().ok_or("metadata: no packages array")?; + let mut out: Vec<(String, PathBuf)> = Vec::new(); + for p in pkgs { + let name = p["name"].as_str().ok_or("package without name")?.to_owned(); + let manifest_dir = std::path::Path::new(p["manifest_path"].as_str().ok_or("package without manifest_path")?) + .parent() + .ok_or("manifest without parent")? + .to_path_buf(); + for t in p["targets"].as_array().into_iter().flatten() { + let kinds: Vec<&str> = t["kind"].as_array().into_iter().flatten().filter_map(|k| k.as_str()).collect(); + let is_lib = kinds.iter().any(|&k| matches!(k, "lib" | "rlib" | "dylib" | "cdylib" | "staticlib" | "proc-macro")); + let is_bin = kinds.contains(&"bin"); + if is_lib || is_bin { + let fallback = if is_lib { "src/lib.rs" } else { "src/main.rs" }; + let root = match t["src_path"].as_str() { + Some(s) => PathBuf::from(s), + None => manifest_dir.join(fallback), + }; + out.push((name.clone(), root)); + } + } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(out) +} + +/// Read each root's contents (separate from [`root_paths`] so the path-collection logic is +/// unit-testable without the real tree). +pub fn from_metadata(meta: &serde_json::Value) -> Result, String> { + let mut out = Vec::new(); + for (name, root) in root_paths(meta)? { + let src = std::fs::read_to_string(&root).map_err(|e| format!("roots: {}: {e}", root.display()))?; + out.push(CrateRoot { name, root, src }); + } + Ok(out) +} + +/// Run the roots check against the real workspace tree. +pub fn run() -> Result<(), String> { + let roots = from_metadata(&super::metadata()?)?; + let violations = check(&roots); + if violations.is_empty() { + println!("OK: {} crate roots carry both `#![forbid(unsafe_code)]` and the deny list.", roots.len()); + Ok(()) + } else { + Err(violations.iter().map(|v| format!(" {v}")).collect::>().join("\n")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn root(name: &str, src: &str) -> CrateRoot { + CrateRoot { name: name.into(), root: PathBuf::from(format!("src/{name}.rs")), src: src.into() } + } + + const DENY: &str = "clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable"; + + #[test] + fn both_attributes_pass() { + let src = format!("#![forbid(unsafe_code)]\n#![deny({DENY})]\nfn f() {{}}\n"); + assert!(check(&[root("lightcraft-foo", &src)]).is_empty()); + } + + #[test] + fn missing_forbid_reported() { + let src = format!("#![deny({DENY})]\nfn f() {{}}\n"); + let v = check(&[root("lightcraft-foo", &src)]); + assert!(matches!(&v[..], [Violation::MissingForbid { .. }]), "{v:?}"); + } + + #[test] + fn missing_deny_reported() { + let v = check(&[root("lightcraft-foo", "#![forbid(unsafe_code)]\nfn f() {}\n")]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn sysmem_exempt_from_forbid_but_not_deny() { + let good = format!("#![deny({DENY})]\nfn f() {{}}\n"); + assert!(check(&[root("lightcraft-sysmem", &good)]).is_empty()); + let v = check(&[root("lightcraft-sysmem", "#![forbid(unsafe_code)]\nfn f() {}\n")]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn root_paths_collects_bin_cdylib_and_lib_targets() { + let meta = serde_json::json!({ + "packages": [ + { "name": "lightcraft-bin-only", "manifest_path": "/ws/bin-only/Cargo.toml", + "targets": [ { "kind": ["bin"], "src_path": "/ws/bin-only/src/main.rs" } ] }, + { "name": "lightcraft-meta", "manifest_path": "/ws/meta/Cargo.toml", + "targets": [ { "kind": ["lib"], "src_path": "/ws/meta/src/lib.rs" } ] }, + { "name": "lightcraft-web", "manifest_path": "/ws/web/Cargo.toml", + "targets": [ { "kind": ["cdylib", "rlib"], "src_path": "/ws/web/src/lib.rs" } ] }, + ] + }); + let paths = root_paths(&meta).expect("metadata should parse"); + let names: Vec<_> = paths.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, vec!["lightcraft-bin-only", "lightcraft-meta", "lightcraft-web"]); + assert_eq!(paths[0].1, std::path::Path::new("/ws/bin-only/src/main.rs")); + assert_eq!(paths[1].1, std::path::Path::new("/ws/meta/src/lib.rs")); + assert_eq!(paths[2].1, std::path::Path::new("/ws/web/src/lib.rs")); + } + + #[test] + fn root_paths_collects_proc_macro_targets() { + let meta = serde_json::json!({ + "packages": [ + { "name": "lightcraft-macros", "manifest_path": "/ws/macros/Cargo.toml", + "targets": [ { "kind": ["proc-macro"], "src_path": "/ws/macros/src/derive.rs" } ] }, + { "name": "lightcraft-plain-macros", "manifest_path": "/ws/plain-macros/Cargo.toml", + "targets": [ { "kind": ["proc-macro"] } ] }, + ] + }); + let paths = root_paths(&meta).expect("metadata should parse"); + assert_eq!( + paths, + vec![ + ("lightcraft-macros".to_owned(), PathBuf::from("/ws/macros/src/derive.rs")), + ("lightcraft-plain-macros".to_owned(), PathBuf::from("/ws/plain-macros/src/lib.rs")), + ] + ); + } + + #[test] + fn deny_must_contain_all_six_lints() { + let v = check(&[root("lightcraft-foo", "#![forbid(unsafe_code)]\n#![deny(clippy::unwrap_used, clippy::expect_used)]\nfn f() {}\n")]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn a_root_allow_overriding_a_required_lint_is_reported() { + // rustc applies the later attribute, so the deny list above it no longer denies + let src = format!("#![forbid(unsafe_code)]\n#![deny({DENY})]\n#![allow(clippy::panic)]\nfn f() {{}}\n"); + let v = check(&[root("lightcraft-foo", &src)]); + assert!(matches!(&v[..], [Violation::OverriddenDeny { lint, .. }] if lint == "clippy::panic"), "{v:?}"); + assert_eq!( + v.first().map(|v| v.to_string()).as_deref(), + Some("lightcraft-foo: the crate-root `#![allow(clippy::panic)]` overrides the required deny list in src/lightcraft-foo.rs"), + "the rendered message shows the attribute, not literal braces", + ); + } + + #[test] + fn a_root_expect_overriding_a_required_lint_is_reported() { + let src = format!("#![forbid(unsafe_code)]\n#![deny({DENY})]\n#![expect(clippy::unwrap_used)]\nfn f() {{}}\n"); + let v = check(&[root("lightcraft-foo", &src)]); + assert!(matches!(&v[..], [Violation::OverriddenDeny { lint, .. }] if lint == "clippy::unwrap_used"), "{v:?}"); + } + + #[test] + fn an_item_level_allow_inside_a_function_is_not_an_override() { + // the documented guarded-expect form: the crate-level deny list stays intact + let src = format!( + "#![forbid(unsafe_code)]\n#![deny({DENY})]\nfn f() {{\n #[allow(clippy::expect_used)] // invariant\n let x: u8 = None.expect(\"checked above\");\n}}\n" + ); + assert!(check(&[root("lightcraft-foo", &src)]).is_empty()); + } + + #[test] + fn library_root_follows_the_declared_lib_path() { + let meta = serde_json::json!({ + "packages": [ + { "name": "lightcraft-custom", "manifest_path": "/ws/custom/Cargo.toml", + "targets": [ { "kind": ["lib"], "src_path": "/ws/custom/src/core.rs" } ] }, + ] + }); + let paths = root_paths(&meta).expect("metadata should parse"); + assert_eq!(paths, vec![("lightcraft-custom".to_owned(), PathBuf::from("/ws/custom/src/core.rs"))]); + } + + #[test] + fn a_lint_named_only_in_a_trailing_comment_does_not_count() { + let src = "#![forbid(unsafe_code)]\n#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo)] // clippy::unreachable\nfn f() {}\n"; + let v = check(&[root("lightcraft-foo", src)]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn lint_names_must_match_whole() { + let src = "#![forbid(unsafe_code)]\n#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic_in_result_fn, clippy::unimplemented, clippy::todo, clippy::unreachable)]\nfn f() {}\n"; + let v = check(&[root("lightcraft-foo", src)]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn attributes_after_a_long_header_are_found() { + let header: String = (0..40).map(|n| format!("//! header line {n}\n")).collect(); + let src = format!("{header}\n#![forbid(unsafe_code)]\n#![deny({DENY})]\nfn f() {{}}\n"); + assert!(check(&[root("lightcraft-foo", &src)]).is_empty()); + } + + #[test] + fn multi_line_deny_attribute_is_read() { + let src = "#![forbid(unsafe_code)]\n#![deny(\n clippy::unwrap_used,\n clippy::expect_used,\n clippy::panic,\n clippy::unimplemented,\n clippy::todo,\n clippy::unreachable,\n)]\nfn f() {}\n"; + assert!(check(&[root("lightcraft-foo", src)]).is_empty()); + } + + #[test] + fn attributes_of_a_nested_module_do_not_count() { + let src = format!("#![forbid(unsafe_code)]\nfn f() {{}}\nmod inner {{\n #![deny({DENY})]\n}}\n"); + let v = check(&[root("lightcraft-foo", &src)]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn a_commented_out_attribute_does_not_count() { + let src = format!("#![forbid(unsafe_code)]\n/*\n#![deny({DENY})]\n*/\nfn f() {{}}\n"); + let v = check(&[root("lightcraft-foo", &src)]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn targets_without_src_path_fall_back_to_the_default_files() { + let meta = serde_json::json!({ + "packages": [ + { "name": "lightcraft-plain", "manifest_path": "/ws/plain/Cargo.toml", + "targets": [ { "kind": ["lib"] } ] }, + { "name": "lightcraft-tool", "manifest_path": "/ws/tool/Cargo.toml", + "targets": [ { "kind": ["bin"] } ] }, + ] + }); + let paths = root_paths(&meta).expect("metadata should parse"); + assert_eq!(paths[0].1, PathBuf::from("/ws/plain/src/lib.rs")); + assert_eq!(paths[1].1, PathBuf::from("/ws/tool/src/main.rs")); + } +} From 826875470a94e5e1b1bf43c9e604497f01413c08 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:35:26 +0100 Subject: [PATCH 22/24] Paint clipped pixels red/blue when clipping warnings (J) are on (#3638) Fixes #3620 Co-authored-by: Claude Opus 5.5 --- crates/pipeline/src/visualize.rs | 51 +++++++++++++++++++++++-- crates/ui-egui/src/panels/detail.rs | 28 ++++---------- crates/ui-egui/src/tests/alt_preview.rs | 31 +++++++++++++++ 3 files changed, 86 insertions(+), 24 deletions(-) diff --git a/crates/pipeline/src/visualize.rs b/crates/pipeline/src/visualize.rs index 63bd7dc858..86d6ade16c 100644 --- a/crates/pipeline/src/visualize.rs +++ b/crates/pipeline/src/visualize.rs @@ -57,8 +57,16 @@ pub enum Overlay { SharpenDetail, /// The sharpening mask, white where sharpening applies (Alt-drag on Sharpening Masking). SharpenMask, + /// Clipping warnings (J): the photo with every pixel that has a channel at 255 painted + /// [`CLIP_HIGH`] and every other pixel with a channel at 0 painted [`CLIP_LOW`]. + ClipWarnings, } +/// [`Overlay::ClipWarnings`] colour of clipped highlights. +pub const CLIP_HIGH: [u8; 3] = [255, 0, 0]; +/// [`Overlay::ClipWarnings`] colour of clipped shadows. +pub const CLIP_LOW: [u8; 3] = [0, 0, 255]; + /// [`Overlay::HdrRange`] colours (sRGB) for 0–1, 1–2, 2–3 and ≥ 3 stops above SDR white. pub const HDR_BANDS: [[u8; 3]; 4] = [[255, 214, 92], [255, 150, 40], [235, 64, 52], [214, 60, 210]]; @@ -148,6 +156,7 @@ impl Overlay { Overlay::Grayscale => (8, 0.0), Overlay::SharpenDetail => (9, 0.0), Overlay::SharpenMask => (10, 0.0), + Overlay::ClipWarnings => (11, 0.0), } } @@ -171,6 +180,7 @@ impl Overlay { 8 => Overlay::Grayscale, 9 => Overlay::SharpenDetail, 10 => Overlay::SharpenMask, + 11 => Overlay::ClipWarnings, _ => Overlay::None, } } @@ -189,6 +199,7 @@ impl Overlay { Overlay::Grayscale => 0x5002, Overlay::SharpenDetail => 0x5003, Overlay::SharpenMask => 0x5004, + Overlay::ClipWarnings => 0x5005, } } @@ -208,7 +219,7 @@ impl Overlay { /// The clipping previews, which test the sRGB values the histogram counts (a render for a /// display profile draws them in sRGB, then converts). pub fn is_clipping(self) -> bool { - matches!(self, Overlay::ClipShadows | Overlay::ClipHighlights) + matches!(self, Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::ClipWarnings) } /// Whether the overlay draws from the render's detail planes ([`sharpen_plane`]). @@ -219,7 +230,10 @@ impl Overlay { /// Whether the overlay works pixel by pixel on the finished image, so a window render shows /// the same as the whole frame would. pub fn per_pixel(self) -> bool { - matches!(self, Overlay::None | Overlay::Mask { .. } | Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::Grayscale) + matches!( + self, + Overlay::None | Overlay::Mask { .. } | Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::ClipWarnings | Overlay::Grayscale + ) } /// The mask an [`Overlay::Mask`] shows (if it exists in `s` and has components). @@ -310,6 +324,7 @@ pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, plane: Option<&Plane> } Overlay::ClipShadows => clipping(img, false), Overlay::ClipHighlights => clipping(img, true), + Overlay::ClipWarnings => clip_warnings(img), Overlay::Grayscale => grayscale(img), Overlay::SharpenDetail | Overlay::SharpenMask => { if let Some(p) = plane.filter(|a| (a.width, a.height) == (img.width, img.height)) { @@ -362,6 +377,25 @@ pub fn clipping(img: &mut Rgba8, high: bool) { }); } +/// [`Overlay::ClipWarnings`]: pixels with a channel at 255 in [`CLIP_HIGH`], the rest with a +/// channel at 0 in [`CLIP_LOW`], everything else unchanged. +pub fn clip_warnings(img: &mut Rgba8) { + let w = img.width; + for_rows(&mut img.data, w, |_, row| { + for px in row.iter_mut() { + let c = &px[..3]; + let paint = if c.contains(&255) { + CLIP_HIGH + } else if c.contains(&0) { + CLIP_LOW + } else { + continue; + }; + *px = [paint[0], paint[1], paint[2], 255]; + } + }); +} + fn grayscale(img: &mut Rgba8) { let w = img.width; for_rows(&mut img.data, w, |_, row| { @@ -713,7 +747,8 @@ mod tests { assert!(Overlay::for_control(c).is_some(), "{c}"); } assert!(Overlay::ClipShadows.is_clipping() && Overlay::ClipHighlights.is_clipping() && !Overlay::Grayscale.is_clipping()); - let all = [Overlay::ClipShadows, Overlay::ClipHighlights, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask]; + let all = + [Overlay::ClipShadows, Overlay::ClipHighlights, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask, Overlay::ClipWarnings]; for o in all { let (k, v) = o.to_parts(); assert_eq!(Overlay::from_parts(k, v), o); @@ -721,6 +756,16 @@ mod tests { assert_ne!(o.key(), Overlay::HdrRange.key()); } assert!(Overlay::ClipShadows.per_pixel() && !Overlay::SharpenDetail.per_pixel()); + assert!(Overlay::ClipWarnings.is_clipping() && Overlay::ClipWarnings.per_pixel()); + } + + #[test] + fn clip_warnings_paint_clipped_pixels_only() { + let data = vec![[255, 255, 255, 255], [0, 0, 0, 255], [128, 128, 128, 255], [255, 40, 0, 255], [10, 0, 30, 255]]; + let mut img = Rgba8 { width: 5, height: 1, data }; + super::clip_warnings(&mut img); + let rgb: Vec<[u8; 3]> = img.data.iter().map(|p| [p[0], p[1], p[2]]).collect(); + assert_eq!(rgb, [super::CLIP_HIGH, super::CLIP_LOW, [128, 128, 128], super::CLIP_HIGH, super::CLIP_LOW]); } #[test] diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 534949ab00..b827d14306 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -344,7 +344,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // the line of a wipe over both draw_wipe_line(app.ui.before_after, &p, img_rect, line); let map = CanvasMap::new(&frame, img_rect); - let over = OverPhoto { photo: &photo, d: &d, map: &map, canvas, img_rect, fullscreen, crop_tool, clipping: !show_before }; + let over = OverPhoto { photo: &photo, d: &d, map: &map, canvas, img_rect, fullscreen, crop_tool }; photo_overlays(app, ui, &p, &over); // Cursor selection must also run on gesture frames, when tool input is suppressed. if !matches!(right, RightPanel::Crop | RightPanel::Masking | RightPanel::Remove | RightPanel::RedEye) { @@ -1064,17 +1064,12 @@ struct OverPhoto<'a> { img_rect: Rect, fullscreen: bool, crop_tool: bool, - /// the clipping overlay may show (not in the Before view) - clipping: bool, } -/// The overlays over the photo: clipping, layout image, info, filter pill, faces, focus point and +/// The overlays over the photo: layout image, info, filter pill, faces, focus point and /// the transform grid. fn photo_overlays(app: &mut LightcraftApp, ui: &mut egui::Ui, p: &egui::Painter, o: &OverPhoto) { let (canvas, img_rect) = (o.canvas, o.img_rect); - if app.ui.show_clipping && o.clipping && !o.fullscreen { - clipping_overlay(app, p, img_rect); - } // View ▸ Loupe Overlay ▸ Layout Image, over the photo (the After view in a before/after) super::layout_overlay::draw(app, p, img_rect); register(ui, "canvas:image", img_rect); @@ -1154,7 +1149,7 @@ fn targeted_drag(app: &mut LightcraftApp, resp: &egui::Response, map: &CanvasMap } /// The diagnostic overlay the loupe shows (an Alt-drag preview, the selected mask, Point Color's -/// visualized range, Visualize Spots). +/// visualized range, Visualize Spots, the clipping warnings). pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcraft_pipeline::Overlay { use lightcraft_pipeline::{MaskView, Overlay}; if app.ui.fullscreen { @@ -1198,20 +1193,11 @@ pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcra if edit && app.ui.hdr_visualize && d.hdr.enabled { return Overlay::HdrRange; } - Overlay::None -} - -fn clipping_overlay(app: &LightcraftApp, p: &egui::Painter, r: Rect) { - // Highlight clipped regions using the histogram's extremes isn't spatial; show a subtle frame hint. - if let Some(h) = app.renderer.textures.get(&Slot::Main).and_then(|t| t.histogram.as_ref()) { - let (lo, hi) = h.clipping(); - if hi > 0.003 { - p.rect_stroke(r, 0.0, Stroke::new(2.0, Color32::from_rgb(255, 60, 60)), StrokeKind::Outside); - } - if lo > 0.003 { - p.rect_stroke(r.expand(3.0), 0.0, Stroke::new(2.0, Color32::from_rgb(60, 120, 255)), StrokeKind::Outside); - } + // Clipping warnings (J): clipped highlights red, clipped shadows blue, on the photo itself + if app.ui.show_clipping { + return Overlay::ClipWarnings; } + Overlay::None } fn general_cursor(app: &LightcraftApp, ui: &egui::Ui, resp: &egui::Response, img: Rect, canvas: Rect) { diff --git a/crates/ui-egui/src/tests/alt_preview.rs b/crates/ui-egui/src/tests/alt_preview.rs index 7a212869fc..5997b41b43 100644 --- a/crates/ui-egui/src/tests/alt_preview.rs +++ b/crates/ui-egui/src/tests/alt_preview.rs @@ -69,3 +69,34 @@ fn alt_during_a_blacks_drag_shows_shadow_clipping_until_released() { let after = h.app.session.develop_of(h.app.session.active().expect("photo")).expect("develop").light.blacks; assert!(after < before, "the drag itself still moved Blacks: {before} → {after}"); } + +/// Share of the loupe render's pixels painted exactly `c`. +fn share_of(h: &Headless, c: [u8; 3]) -> f64 { + let t = h.app.renderer.textures.get(&crate::render::Slot::Main).expect("loupe render"); + let px = &t.pixels.as_ref().expect("pixels kept").pixels; + let n = px.iter().filter(|p| [p.r(), p.g(), p.b()] == c).count(); + n as f64 / px.len().max(1) as f64 +} + +/// Issue #3620: J (clipping warnings) paints the clipped pixels themselves, red where a channel +/// is blown to white and blue where one is crushed to black, not just a frame around the photo. +#[test] +fn j_paints_clipped_highlights_red_and_clipped_shadows_blue() { + let mut h = detail(); + let set = |h: &mut Headless, ev: f64| { + let r = h.request("engine.execute", json!({"command": "develop.set", "params": {"control": "light.exposure", "value": ev}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + }; + set(&mut h, 5.0); + let (red, blue) = ([255, 0, 0], [0, 0, 255]); + assert!(share_of(&h, red) < 0.1, "without J the blown photo is not painted red: {}", share_of(&h, red)); + let r = h.request("ui.key", json!({"key": "J"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.show_clipping); + assert!(share_of(&h, red) > 0.5, "blown highlights shown in red: {}", share_of(&h, red)); + set(&mut h, -5.0); + assert!(share_of(&h, blue) > 0.01, "crushed shadows shown in blue: {}", share_of(&h, blue)); + assert!(share_of(&h, red) < 0.01, "nothing blown at -5 EV: {}", share_of(&h, red)); +} From 68b464011ff128442ee572d2424f700cf69fefe2 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 02:23:04 +0200 Subject: [PATCH 23/24] Import review: an optional batch-edit recipe for newly imported photos (#2940) * Import: an optional batch-edit recipe for newly imported photos library.import takes a recipe, a list of develop control ids and values. Each control is set, clamped to its range like a slider's, on every photo the import actually adds, after the XMP sidecar, the camera default and the chosen preset, as one more History step named Import adjustments. Photos that are skipped as duplicates, restored from Recently Deleted or joined from a browsed folder are not touched, as the preset and keywords never touch them. A recipe names plain adjustments only. White balance is refused, because a temperature means Kelvin on a raw with colour matrices and a shift from the as-shot white on a rendered photo, so one number cannot name the same look for a whole batch, and the as-shot white balance of a raw is never touched. Geometry and crop controls are refused, because the slider refits the crop around a new angle and a batch write cannot. Per-photo controls such as pointColor.0.hueShift are refused, because a write to a photo without that instance is dropped. The rule is on the control's spec (a control of the shared list, outside the Geometry section, not white balance, and one that set accepts), so new controls follow it. An id named twice counts once, the last value winning, and a list longer than the control list is refused. ImportJob::new checks a recipe built in code the same way, before any file is read or placed. preset.saveRecipe saves a recipe as a user preset that stores only the settings the recipe names, including a control the recipe sets to its default, and refuses a recipe that stores nothing. The preset gets its id the way imported presets do (user.-, then -2, -3 ...), so no two presets share one: an id from the list length repeats once a preset is deleted, and the first preset with an id is the one that gets applied. A name or group over 100 characters is refused, and saving the same recipe under the same name and group again returns the preset that exists. * Import recipe: tests Cover a recipe on import (the values, the Import adjustments step, a render, one undo step), the refusals (unknown ids, malformed items, per-photo controls, geometry and crop, white balance, too many entries, by the command and by ImportJob::new), clamping and a repeated id, a raw's as-shot white balance staying as imported, a saved recipe preset giving the same settings as the recipe (including a reset to a default), the photos the recipe leaves alone (duplicates by path and by content, a restored photo, a browsed photo that joins; a photo imported afresh gets it), preset ids staying distinct after a delete and surviving a reopened library, and both commands being listed with their parameters. * Import review: a Batch edits section The import review gets a collapsible Batch edits section: sliders for the everyday adjustments (exposure, contrast, highlights, shadows, whites, blacks, vibrance, saturation, clarity, texture, dehaze, sharpening, grain, vignette). The controls moved off their default go to library.import as its recipe, only when there are any, and a summary beside the section counts them. The recipe stays in the dialog until the import runs, so cancelling changes neither the catalog nor the presets. Save as Preset, which needs a name and a recipe, saves the recipe with preset.saveRecipe. It leaves the review's own preset choice as it is, so a preset picked for the import is never replaced by the saved one. The name goes in a TextField, as new text boxes do. The summary line is a new tr_format message, added with a translation to every formats catalog; the other new messages are plain and show in English until a catalog translates them. * Import review recipe: tests Unit tests hold the dialog to the engine: every control it offers is one a recipe may name, a slider moved back to its default leaves the recipe, and start passes a recipe to library.import only when the dialog has one. Driving the real review, Save as Preset saves nothing without a name or without a recipe and with both saves exactly the recipe (leaving the review's preset choice and the catalog alone), cancelling the review discards the recipe, and confirming imports the photos with it as one undo step, or without an Import adjustments step when there is none. * Import recipe: tests for the disabled Save button and MCP reachability The disabled state of Save as Preset was not pinned: the engine refuses a nameless or empty recipe anyway, so the preset count stayed the same even with the button always on. The test now also expects no error toast, which only an enabled button that asked the engine would raise. A new MCP end-to-end test drives both commands through the public tools: list_commands documents them, run_command takes library.import with a recipe (a recipe naming white balance is a tool error that imports nothing), get_develop shows the values on the imported photo, and the generated cmd_preset_saveRecipe tool saves a recipe. * Import recipe: follow main's register(ui) and Id::unique after the rebase Upstream main changed widgets::register to take &egui::Ui (every other call site passes ui) and deprecated egui::Id::new in favour of Id::unique (same hash, so the stored open/closed state is unchanged). Adapt the batch-edit recipe section so lightcraft-ui-egui compiles again. * docs: parity row LR-IMP-RECIPE for batch edits during import * Keep HDR resets when a recipe is saved as a preset A recipe that resets an HDR control to its default was dropped when it was saved as a preset, because the HDR subtree is left out of the settings JSON while it is the default. The recipe's settings are now compared with the HDR subtree always present, so the reset is stored alone and next to other adjustments. Round-trip tests apply the saved preset to settings with a non-default headroom. * Address review findings * Address review findings * Import review: the imports the merge left in body.rs Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd.rs | 60 ++++ crates/engine/src/cmd/develop.rs | 130 ++++++++ crates/engine/src/cmd/library/import.rs | 1 + crates/engine/src/cmd/library/specs.rs | 2 +- crates/engine/src/import.rs | 3 +- crates/engine/src/import/commit.rs | 13 + crates/engine/src/import/job.rs | 2 + crates/engine/src/import/types.rs | 10 + crates/engine/src/tests/import.rs | 313 ++++++++++++++++++++ crates/mcp/tests/it/e2e.rs | 45 +++ crates/ui-egui/locales/de-formats.json | 1 + crates/ui-egui/locales/es-formats.json | 1 + crates/ui-egui/locales/fr-formats.json | 1 + crates/ui-egui/locales/ja-formats.json | 1 + crates/ui-egui/locales/pt-br-formats.json | 1 + crates/ui-egui/locales/ru-formats.json | 1 + crates/ui-egui/locales/uk-formats.json | 1 + crates/ui-egui/locales/zh-hans-formats.json | 1 + crates/ui-egui/locales/zh-hant-formats.json | 1 + crates/ui-egui/src/dialogs/import.rs | 58 +++- crates/ui-egui/src/dialogs/import/body.rs | 92 +++++- crates/ui-egui/src/dialogs/import/task.rs | 7 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/import_recipe.rs | 182 ++++++++++++ docs/gaps.md | 1 + docs/parity-checklist.md | 4 +- 26 files changed, 926 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/tests/import_recipe.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 0c93a56a65..d9e3466611 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -271,6 +271,66 @@ pub(crate) fn bool_or(p: &Value, key: &str, d: bool) -> bool { pub(crate) fn ok() -> Result { Ok(Value::Null) } + +/// A batch-edit recipe from a command's params: `[{id, value}, …]`, each `id` a develop control a +/// recipe may name ([`check_recipe`]). Empty when absent or null. A malformed item, a control a +/// recipe may not name, or more entries than there are controls is an error, so a typo is refused +/// rather than silently ignored. An id named twice counts once, the last value winning; the list +/// comes back in id order. +pub(crate) fn recipe_param(p: &Value, cmd: &str) -> Result> { + let Some(v) = p.get("recipe").filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; + let Some(items) = v.as_array() else { + return Err(bad(cmd, "`recipe` must be a list of {id, value}")); + }; + let most = lightcraft_develop::controls::CONTROLS.len(); + if items.len() > most { + return Err(bad(cmd, format!("a recipe has one entry per control, at most {most} (it has {})", items.len()))); + } + let mut by_id = std::collections::BTreeMap::new(); + for it in items { + let id = it.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad(cmd, "each recipe item needs an `id`"))?; + let value = it.get("value").and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("recipe `{id}` needs a numeric `value`")))?; + by_id.insert(id.to_string(), value); + } + let recipe: Vec<(String, f64)> = by_id.into_iter().collect(); + check_recipe(&recipe).map_err(|e| bad(cmd, e))?; + Ok(recipe) +} + +/// Whether every control of `recipe` is one a batch-edit recipe may name, else why not. The rule is +/// on the control's spec: a plain control of the shared list, writable on any photo's settings +/// (`set` takes it), outside the Geometry section and not white balance. +/// +/// - Per-photo instances (`pointColor.0.hueShift`, `redEye.0.pupilSize`) are not in the list; on a +/// photo without that instance a write is dropped. +/// - Geometry controls (`crop.angle`, `geometry.*`) need the photo's own size: the slider refits the +/// crop around a new angle, which a batch write cannot do. +/// - White balance means something else on each kind of file (Kelvin on a raw with matrices, +/// relative to the as-shot white on a rendered photo or a raw without them), so one temperature +/// cannot name the same look for every photo of a batch. +pub(crate) fn check_recipe(recipe: &[(String, f64)]) -> std::result::Result<(), String> { + use lightcraft_develop::{Section, controls}; + let mut scratch = lightcraft_develop::DevelopSettings::default(); + for (id, value) in recipe { + let Some(spec) = controls::CONTROLS.iter().find(|c| c.id == id.as_str()) else { + return Err(format!( + "unknown recipe control `{id}` (see develop.controls; a control that belongs to one photo, such as pointColor.0.hueShift, is not one)" + )); + }; + if spec.section == Section::Geometry { + return Err(format!("`{id}` is a geometry control: a recipe does not crop, straighten or transform photos")); + } + if id.starts_with("wb.") { + return Err(format!( + "`{id}` is white balance: a recipe does not set it, because a temperature means something else on a raw than on a rendered photo" + )); + } + if !controls::set(&mut scratch, id, *value) { + return Err(format!("recipe control `{id}` cannot be set")); + } + } + Ok(()) +} pub(crate) fn point(p: &Value, key: &str) -> Option { let a = p.get(key)?.as_array()?; Some(lightcraft_geom::Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?)) diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 5399aee9b8..5403ad6eb2 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -33,6 +33,58 @@ fn groups_param(p: &Value, c: &str) -> Result>> { } } +/// The leaves of `a` that differ from `b` (same shape), as a partial JSON object: `None` when they +/// are equal. Used to store only what a batch-edit recipe names, so applying the saved preset +/// later never overrides the settings the recipe doesn't name. +fn partial_diff(a: &Value, b: &Value) -> Option { + match (a, b) { + (Value::Object(x), Value::Object(y)) => { + let mut out = serde_json::Map::new(); + for (k, v) in x { + if let Some(d) = partial_diff(v, y.get(k).unwrap_or(&Value::Null)) { + out.insert(k.clone(), d); + } + } + (!out.is_empty()).then_some(Value::Object(out)) + } + (x, y) => (x != y).then(|| x.clone()), + } +} + +/// The settings as JSON with the HDR subtree always present: [`Hdr`] is left out while it is the default +/// (its JSON stays as it was), so a reset to a default HDR value would have nothing to compare with and +/// would be dropped from a saved preset. +fn full_json(s: &DevelopSettings) -> Value { + let mut v = s.to_json(); + if let Some(obj) = v.as_object_mut() { + obj.entry("hdr").or_insert_with(|| serde_json::to_value(s.hdr).unwrap_or(Value::Null)); + } + v +} + +/// The partial settings a batch-edit recipe names, with the values the import would give (clamped +/// by the control specs). Each named control is compared with the same control at a value it is not +/// set to, so a control the recipe sets to its default (a reset) is stored too, and nothing else is. +/// `None` when the recipe names nothing that is stored, or a control that cannot be written. +fn recipe_partial(recipe: &[(String, f64)]) -> Option { + let (mut named, mut other) = (DevelopSettings::default(), DevelopSettings::default()); + for (id, v) in recipe { + if !controls::set(&mut named, id, *v) { + return None; + } + } + for (id, _) in recipe { + let (spec, now) = (controls::find(id)?, controls::get(&named, id)?); + if !controls::set(&mut other, id, if now > spec.min { spec.min } else { spec.max }) { + return None; + } + } + partial_diff(&full_json(&named), &full_json(&other)) +} + +/// The longest name or group a saved recipe preset may have (characters). +const MAX_PRESET_TEXT: usize = 100; + fn crop_dims(s: &Session, id: PhotoId) -> (f64, f64) { let p = s.catalog.photo(id); let (w, h) = p.map(|p| (p.width.max(1) as f64, p.height.max(1) as f64)).unwrap_or((3.0, 2.0)); @@ -1162,6 +1214,41 @@ pub fn specs() -> Vec { s.presets.push(Preset::from_settings(&pid, name, group, &d, &groups)); Ok(json!({"id": pid})) }), + cmd!( + "preset.saveRecipe", + "Save Import Recipe as Preset", + [], + None, + "{name (up to 100 characters), group?: default Import Recipes, recipe: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}]} → {id, name} — save a batch-edit recipe (as library.import takes it) as a user preset, so it can be reused from the Preset list; only the settings the recipe names are stored, so applying it later never overrides the rest. The preset gets an id no other preset has; saving the same recipe under the same name and group again returns the preset that already is", + always, + |s, p| { + const C: &str = "preset.saveRecipe"; + let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(C, "missing name"))?.to_string(); + let group = str_param(p, "group").map(str::trim).filter(|g| !g.is_empty()).unwrap_or("Import Recipes").to_string(); + if name.chars().count() > MAX_PRESET_TEXT || group.chars().count() > MAX_PRESET_TEXT { + return Err(bad(C, format!("a name or group is at most {MAX_PRESET_TEXT} characters"))); + } + let recipe = super::recipe_param(p, C)?; + if recipe.is_empty() { + return Err(bad(C, "the recipe is empty")); + } + let settings = recipe_partial(&recipe).ok_or_else(|| bad(C, "the recipe sets nothing a preset can store"))?; + // presets get their ids as imported ones do (`user.-`, then -2, -3…): an id from the list's + // length repeats once a preset is deleted, and the first preset with an id is the one that gets applied + let preset = Preset { id: String::new(), name, group, settings, favorite: false, builtin: false }; + let id = match s.add_presets(vec![preset.clone()]).into_iter().next() { + Some(id) => id, + // the same recipe under the same name and group is already a preset + None => s + .presets + .iter() + .find(|q| !q.builtin && q.name == preset.name && q.group == preset.group && q.settings == preset.settings) + .map(|q| q.id.clone()) + .ok_or_else(|| bad(C, "the preset could not be saved"))?, + }; + Ok(json!({"id": id, "name": preset.name})) + } + ), cmd!("preset.delete", "Delete Preset", [], None, "{id}", always, |s, p| { let pid = str_param(p, "id").ok_or_else(|| bad("preset.delete", "missing id"))?; let i = s.presets.iter().position(|x| x.id == pid).ok_or_else(|| bad("preset.delete", "unknown preset"))?; @@ -1336,3 +1423,46 @@ fn has_history_after(s: &Session) -> std::result::Result<(), String> { Err("at the latest History step".into()) } } + +#[cfg(test)] +mod recipe_tests { + use super::*; + + /// Equal settings differ nowhere, so there is nothing to store; a difference comes back with + /// its path only. + #[test] + fn partial_diff_is_the_changed_leaves_only() { + let a = json!({"light": {"exposure": 1.0, "contrast": 0.0}, "color": {"vibrance": 5.0}}); + assert_eq!(partial_diff(&a, &a), None); + let b = json!({"light": {"exposure": 0.0, "contrast": 0.0}, "color": {"vibrance": 5.0}}); + assert_eq!(partial_diff(&a, &b), Some(json!({"light": {"exposure": 1.0}}))); + assert_eq!(partial_diff(&a, &json!({})), Some(a.clone()), "a leaf the other side lacks is a difference"); + } + + fn recipe(items: &[(&str, f64)]) -> Vec<(String, f64)> { + items.iter().map(|(id, v)| (id.to_string(), *v)).collect() + } + + /// A recipe that names nothing, or a control `set` would drop (a per-photo instance on fresh + /// settings), stores nothing: the command answers with an error, not an empty preset. + #[test] + fn a_recipe_that_stores_nothing_is_none() { + assert_eq!(recipe_partial(&[]), None); + assert_eq!(recipe_partial(&recipe(&[("pointColor.0.hueShift", 5.0)])), None, "set returns false for it"); + assert_eq!(recipe_partial(&recipe(&[("nope.nope", 5.0)])), None); + assert_eq!(recipe_partial(&recipe(&[("light.exposure", 0.5)])), Some(json!({"light": {"exposure": 0.5}}))); + // a reset to the control's default is stored + assert_eq!(recipe_partial(&recipe(&[("light.exposure", 0.0)])), Some(json!({"light": {"exposure": 0.0}}))); + } + + /// The HDR subtree is left out of the JSON while it is the default, so a reset of a headroom to its + /// default is stored in the preset by itself and next to another adjustment. + #[test] + fn an_hdr_reset_is_stored_alone_and_next_to_another_adjustment() { + let reset = recipe_partial(&recipe(&[("hdr.maxEv", 3.0)])).expect("a reset is stored"); + assert_eq!(reset.pointer("/hdr/max_ev"), Some(&json!(3.0)), "{reset}"); + let both = recipe_partial(&recipe(&[("hdr.maxEv", 3.0), ("light.exposure", 0.5)])).expect("both are stored"); + assert_eq!(both.pointer("/hdr/max_ev"), Some(&json!(3.0)), "{both}"); + assert_eq!(both.pointer("/light/exposure"), Some(&json!(0.5)), "{both}"); + } +} diff --git a/crates/engine/src/cmd/library/import.rs b/crates/engine/src/cmd/library/import.rs index 2a663b79de..188dc6ae99 100644 --- a/crates/engine/src/cmd/library/import.rs +++ b/crates/engine/src/cmd/library/import.rs @@ -82,6 +82,7 @@ pub fn import_params(s: &Session, p: &Value) -> Result { metadata_preset, convert_dng: bool_or(p, "dng", false), local: bool_or(p, "local", false), + recipe: crate::cmd::recipe_param(p, "library.import")?, }; let album_name = str_param(p, "albumName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); Ok(ImportRequest { paths, opts, album, album_name }) diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 7732b855ba..c725ac216b 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1348,7 +1348,7 @@ pub fn specs() -> Vec { "Import Photos", ["File"], Some("Cmd+Shift+I"), - "{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}", + "{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, recipe?: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}] (a batch-edit recipe: each control is set to its value, clamped to the control's range, on every photo this import adds, after its sidecar, camera default and preset, as one extra History step named Import adjustments; a photo the library already has — a duplicate, one restored from Recently Deleted, one joined from a browsed folder — is not changed; a control a recipe may not name is refused before anything is imported; preset.saveRecipe keeps a recipe for reuse), keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}", always, |s, p| { let req = import_params(s, p)?; diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index cd3123e522..96ce93d0c1 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -15,7 +15,8 @@ //! 6. Apply each photo's XMP sidecar (or a raw/DNG file's embedded XMP): the sidecar wins for //! metadata and develop settings are restored (see [`crate::sidecar`]). Its capture time fills //! in when the file has none (read before step 5, so it also files and names the copy). -//! 7. Optionally apply a preset and add keywords (the import dialog's options). +//! 7. Optionally apply a preset, then a batch-edit recipe (one more History step), and add +//! keywords (the import dialog's options). //! 8. Commit all new photos as one undoable op. (Undoing a move removes the catalog records; //! the files stay at the destination — undo never moves files back over a card.) //! 9. Copy and Move rename sequences use checked platform-sized numbers: the last number is usable once, and any diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index d283bb0ac4..104d1f63b9 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -291,6 +291,19 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare p.edited = Some(now.clone()); p.history.push(lightcraft_catalog::HistoryStep { label, settings: d }); } + // the batch-edit recipe goes on top of everything above (sidecar, camera default, + // preset): only the controls it names change, through the same specs the sliders use + if !opts.recipe.is_empty() { + let mut d = (*p.develop).clone(); + for (id, v) in &opts.recipe { + // (`ImportJob::new` refused any id `set` would not write, and `set` clamps to the range) + lightcraft_develop::controls::set(&mut d, id, *v); + } + let d = std::sync::Arc::new(d); + p.develop = d.clone(); + p.edited = Some(now.clone()); + p.history.push(lightcraft_catalog::HistoryStep { label: "Import adjustments".into(), settings: d }); + } report.imported.push(id.0); p.local = opts.local; if opts.local { diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index e8ed759dd2..ca906c6192 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -163,6 +163,8 @@ impl ImportJob { /// Snapshot what an import with `opts` needs from the session (no file-system calls). Takes /// the probes a preceding scan left ([`Session::import_probes`]). pub fn new(s: &mut Session, opts: ImportOptions) -> crate::Result { + // a recipe is checked before any file is read or placed, not when the photos are committed + crate::cmd::check_recipe(&opts.recipe).map_err(|e| crate::cmd::bad("library.import", e))?; let mode = opts.mode; // Only a library on disk has an `Originals/` folder. The browser build keeps the bytes of // every added file in its own storage already, so "copy" there means "add". diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index f342bf4c92..aab839931b 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -67,6 +67,16 @@ pub struct ImportOptions { pub metadata_preset: Option, /// Copy: raws are copied as DNG (Copy as DNG). pub convert_dng: bool, + /// A batch-edit recipe: develop control id / value pairs (e.g. `light.exposure` → 0.5), + /// applied to every imported photo *after* its XMP sidecar, camera default and import preset, + /// as one more History step (`Import adjustments`). Only the named controls change; the recipe + /// is a snapshot taken when the import starts, so editing a preset afterwards cannot change it. + /// It names plain adjustments only (no white balance, geometry or crop: `cmd::check_recipe`), + /// and [`ImportJob::new`] refuses anything else. + /// Empty (the default) = no recipe. A photo the library already has keeps its own settings: + /// one skipped as a duplicate, restored from Recently Deleted, or joined from a browsed + /// folder (Local) is never touched, as the preset and keywords never are. + pub recipe: Vec<(String, f64)>, } /// How copies are filed in the destination. The date is the capture time, else the time of the diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 5df2ac680d..34e301a6fd 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -3139,6 +3139,319 @@ fn a_file_arriving_beside_its_raws_stem_reads_its_own_sidecar() { let _ = std::fs::remove_dir_all(&src); } +/// A batch-edit recipe changes the imported photos' actual develop settings (not just an option +/// label), renders, is one undo step, and can be saved as a preset that stores only what it names. +#[test] +fn a_batch_edit_recipe_changes_imported_photos() { + let src = temp_dir("recipe"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("b.png"), 2); + let mut s = Session::new().with_fs(); + let r = s + .execute( + "library.import", + &json!({ + "paths": [src.to_string_lossy()], + "recipe": [{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}], + }), + ) + .unwrap(); + assert_eq!(ids(&r, "imported"), 2, "{r}"); + for p in s.catalog.photos() { + assert_eq!(p.develop.light.exposure, 0.5, "{}", p.file_name); + assert_eq!(p.develop.color.vibrance, 20.0, "{}", p.file_name); + assert!(p.history.iter().any(|h| h.label == "Import adjustments"), "{}", p.file_name); + } + // the edit really renders (the recipe is applied to the settings, not only recorded) + let id = s.catalog.photos().next().unwrap().id; + assert!(s.render_now(id, 32, 32).is_ok()); + // saving the recipe as a preset keeps only the settings it names + let p = s.execute("preset.saveRecipe", &json!({"name": "Warm Trip", "recipe": [{"id": "light.exposure", "value": 0.5}]})).unwrap(); + let saved = s.presets.iter().find(|x| x.id == p["id"].as_str().unwrap()).unwrap(); + assert_eq!(saved.settings.pointer("/light/exposure"), Some(&json!(0.5)), "{}", saved.settings); + assert!(saved.settings.get("color").is_none(), "an unnamed group is not stored: {}", saved.settings); + // one undo step for the whole import + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.len(), 0); + let _ = std::fs::remove_dir_all(&src); +} + +/// A malformed recipe, or one naming a control a recipe may not name, is refused before anything +/// is imported, and by the command that saves one: unknown ids, controls that belong to one photo, +/// geometry and crop controls (the slider refits the crop around them), white balance (a +/// temperature means something else on each kind of file), and lists longer than the control list. +#[test] +fn a_bad_recipe_is_refused() { + let mut s = Session::new().with_fs(); + let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": [{"id": "nope.nope", "value": 1}]})).unwrap_err(); + assert!(format!("{err}").contains("unknown recipe control"), "{err}"); + let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": "x"})).unwrap_err(); + assert!(format!("{err}").contains("recipe"), "{err}"); + assert_eq!(s.catalog.len(), 0); + let too_many: Vec = (0..lightcraft_develop::controls::CONTROLS.len() + 1).map(|_| json!({"id": "light.exposure", "value": 1})).collect(); + for (bad, why) in [ + (json!([{"value": 1}]), "needs an `id`"), + (json!([{"id": "light.exposure"}]), "numeric"), + (json!([{"id": "light.exposure", "value": "high"}]), "numeric"), + (json!([7]), "needs an `id`"), + (json!([{"id": "pointColor.0.hueShift", "value": 5}]), "unknown recipe control"), + (json!([{"id": "redEye.0.pupilSize", "value": 5}]), "unknown recipe control"), + (json!([{"id": "crop.angle", "value": 5}]), "geometry"), + (json!([{"id": "geometry.rotate", "value": 5}]), "geometry"), + (json!([{"id": "wb.temp", "value": 5200}]), "white balance"), + (json!([{"id": "wb.tint", "value": 5}]), "white balance"), + (json!([{"id": "light.exposure", "value": 1}, {"id": "crop.angle", "value": 5}]), "geometry"), + (json!(too_many), "at most"), + ] { + let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": bad})).unwrap_err().to_string(); + assert!(err.contains(why), "{why}: {err}"); + let before = s.presets.len(); + let err = s.execute("preset.saveRecipe", &json!({"name": "Bad", "recipe": bad})).unwrap_err().to_string(); + assert!(err.contains(why), "{why}: {err}"); + assert_eq!(s.presets.len(), before, "nothing saved for {why}"); + } + // the job itself refuses what the command would (a recipe built in code, not from JSON) + let opts = crate::import::ImportOptions { recipe: vec![("crop.angle".into(), 5.0)], ..Default::default() }; + assert!(crate::import::ImportJob::new(&mut s, opts).is_err()); + // no name, a name that is too long, or nothing in the recipe: no preset + let one = json!([{"id": "light.exposure", "value": 1}]); + for params in [json!({"recipe": one}), json!({"name": " ", "recipe": one}), json!({"name": "x".repeat(101), "recipe": one})] { + assert!(s.execute("preset.saveRecipe", ¶ms).is_err(), "{params}"); + } + assert!(s.execute("preset.saveRecipe", &json!({"name": "x".repeat(100), "recipe": one})).is_ok(), "a name of 100 characters is fine"); + assert!(s.execute("preset.saveRecipe", &json!({"name": "Empty", "recipe": []})).is_err()); + assert!(s.execute("preset.saveRecipe", &json!({"name": "Empty"})).is_err()); + assert!(!s.presets.iter().any(|p| p.name == "Empty")); +} + +/// The recipe's values go through the control specs like a slider's: past the range they stop at +/// it, for the photo and for the preset. A control named twice counts once, the last value wins. +#[test] +fn recipe_values_are_clamped_like_a_slider() { + let src = temp_dir("recipe-clamp"); + write_png(&src.join("a.png"), 1); + let mut s = Session::new().with_fs(); + let recipe = json!([{"id": "light.exposure", "value": 1}, {"id": "light.exposure", "value": 99}, {"id": "light.contrast", "value": -1000}]); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": recipe})).unwrap(); + let p = s.catalog.photos().next().unwrap(); + assert_eq!((p.develop.light.exposure, p.develop.light.contrast), (5.0, -100.0)); + let saved = s.execute("preset.saveRecipe", &json!({"name": "Clamped", "recipe": recipe})).unwrap(); + let saved = s.presets.iter().find(|x| x.id == saved["id"].as_str().unwrap()).unwrap(); + assert_eq!(saved.settings.pointer("/light/exposure"), Some(&json!(5.0)), "{}", saved.settings); + assert_eq!(saved.settings.pointer("/light/contrast"), Some(&json!(-100.0)), "{}", saved.settings); + let _ = std::fs::remove_dir_all(&src); +} + +/// A session whose files probe as DNG raws shot at 4800 K, tint +12 (the pixels stay the PNG's; +/// nothing here renders them), to see what an import does to a raw's as-shot white balance. +fn session_with_raw_probe() -> Session { + let mut s = Session::new().with_fs(); + let real = s.media.file_probe.clone().unwrap(); + s.media.file_probe = Some(std::sync::Arc::new(move |path: &str| { + let mut info = real(path)?; + info.kind = lightcraft_catalog::MediaKind::Raw; + info.format = "DNG".into(); + info.as_shot_wb = Some((4800.0, 12.0)); + Ok(info) + })); + s +} + +fn import_one(s: &mut Session, path: &Path, recipe: Value) -> lightcraft_catalog::PhotoId { + let r = s.execute("library.import", &json!({"paths": [path.to_string_lossy()], "recipe": recipe})).unwrap(); + lightcraft_catalog::PhotoId(r["imported"][0].as_u64().unwrap_or_else(|| panic!("{path:?} not imported: {r}"))) +} + +fn white_balance(s: &Session, id: lightcraft_catalog::PhotoId) -> lightcraft_develop::WhiteBalance { + s.catalog.photo(id).unwrap().develop.wb +} + +/// A recipe never touches white balance: a raw keeps the as-shot temperature, tint and scale it was +/// imported with, whatever else the recipe sets, and a recipe cannot name a temperature or tint. +#[test] +fn a_recipe_leaves_a_raws_as_shot_white_balance_alone() { + use lightcraft_develop::{WbMode, WbScale}; + let src = temp_dir("recipe-wb"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("b.png"), 2); + let mut s = session_with_raw_probe(); + let plain = import_one(&mut s, &src.join("a.png"), json!([])); + let w = white_balance(&s, plain); + assert_eq!((w.mode, w.temp, w.tint, w.scale), (WbMode::AsShot, 4800.0, 12.0, WbScale::Kelvin), "{w:?}"); + let with = import_one(&mut s, &src.join("b.png"), json!([{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 30}])); + assert_eq!(white_balance(&s, with), w, "the as-shot white balance is as the import left it"); + assert_eq!(s.catalog.photo(with).unwrap().develop.light.exposure, 0.5); + for id in ["wb.temp", "wb.tint"] { + let err = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": [{"id": id, "value": 5200}]})).unwrap_err(); + assert!(err.to_string().contains("white balance"), "{err}"); + } + let _ = std::fs::remove_dir_all(&src); +} + +/// Saved as a preset and applied to a photo as it was imported, a recipe gives the settings +/// importing with it gives (for a raw too), and the preset holds a control the recipe sets to its +/// default: that is a reset, not "nothing named". +#[test] +fn a_recipe_saved_as_a_preset_gives_what_the_recipe_gives() { + let src = temp_dir("recipe-preset"); + let recipes = [ + json!([{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}]), + json!([{"id": "light.exposure", "value": 99}]), + json!([{"id": "detail.sharpenAmount", "value": 0}, {"id": "grain.amount", "value": 30}]), + json!([{"id": "vignette.amount", "value": -25}, {"id": "effects.clarity", "value": 15}, {"id": "mixer.red.hue", "value": 10}]), + ]; + let mut s = session_with_raw_probe(); + for (i, recipe) in recipes.iter().enumerate() { + write_png(&src.join(format!("with{i}.png")), 2 * i as u8); + write_png(&src.join(format!("plain{i}.png")), 2 * i as u8 + 1); + let with = import_one(&mut s, &src.join(format!("with{i}.png")), recipe.clone()); + let plain = import_one(&mut s, &src.join(format!("plain{i}.png")), json!([])); + let saved = s.execute("preset.saveRecipe", &json!({"name": format!("Recipe {i}"), "recipe": recipe})).unwrap(); + s.selection = crate::Selection::single(plain); + s.execute("preset.apply", &json!({"id": saved["id"], "ids": [plain.0]})).unwrap(); + let (with, plain) = (s.catalog.photo(with).unwrap(), s.catalog.photo(plain).unwrap()); + assert_eq!(with.develop, plain.develop, "recipe {recipe}"); + } + // the sharpening reset (a raw's default is 40) is in the preset although 0 is the control's default + let reset = s.presets.iter().find(|p| p.name == "Recipe 2").unwrap(); + assert_eq!(reset.settings.pointer("/detail/sharpen_amount"), Some(&json!(0.0)), "{}", reset.settings); + assert_eq!(s.catalog.photos().find(|p| p.file_name == "with2.png").unwrap().develop.detail.sharpen_amount, 0.0); + let _ = std::fs::remove_dir_all(&src); +} + +/// The recipe applies to the photos an import adds. A file the library has (by path or by +/// content), a trashed one that comes back, and a browsed one that joins keep their own +/// settings; a trashed one imported afresh is a new photo and gets the recipe. +#[test] +fn a_recipe_only_touches_the_photos_an_import_adds() { + let src = temp_dir("recipe-skipped"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("b.png"), 2); + write_png(&src.join("c.png"), 3); + std::fs::copy(src.join("a.png"), src.join("a-copy.png")).unwrap(); // same bytes as a + let recipe = json!([{"id": "color.vibrance", "value": 20}]); + let adjusted = |s: &Session, name: &str| { + let p = s.catalog.photos().find(|p| p.file_name == name && !p.deleted).unwrap_or_else(|| panic!("no {name}")); + (p.develop.color.vibrance, p.history.iter().any(|h| h.label == "Import adjustments")) + }; + + let mut s = Session::new().with_fs(); + let first = import_one(&mut s, &src.join("a.png"), json!([])); + s.selection = crate::Selection::single(first); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 1.5})).unwrap(); + let a_before = s.catalog.photo(first).unwrap().develop.clone(); + + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": recipe})).unwrap(); + assert_eq!(ids(&r, "imported"), 2, "{r}"); // b and c + assert_eq!(ids(&r, "duplicates"), 2, "{r}"); // a (same path) and a-copy (same content) + assert_eq!(adjusted(&s, "b.png"), (20.0, true)); + assert_eq!(adjusted(&s, "c.png"), (20.0, true)); + assert_eq!(adjusted(&s, "a.png"), (0.0, false), "a duplicate is not edited"); + assert_eq!(s.catalog.photo(first).unwrap().develop, a_before, "nor is the photo it duplicates"); + assert_eq!(s.catalog.len(), 3); + + // in Recently Deleted: restored with its own settings, no recipe + s.execute("photo.delete", &json!({"ids": [first.0]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()], "recipe": recipe})).unwrap(); + assert_eq!((ids(&r, "imported"), ids(&r, "restored")), (0, 1), "{r}"); + assert_eq!(s.catalog.photo(first).unwrap().develop, a_before, "a restored photo keeps its edits"); + assert!(!s.catalog.photo(first).unwrap().history.iter().any(|h| h.label == "Import adjustments")); + + // …imported afresh, it is a new photo and gets the recipe + s.execute("photo.delete", &json!({"ids": [first.0]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()], "recipe": recipe, "onDeleted": "fresh"})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(adjusted(&s, "a.png"), (20.0, true)); + + // browsed first (Local), then imported: the record joins the library as it is, as it does for + // a preset or keywords + let other = temp_dir("recipe-browsed"); + write_png(&other.join("d.png"), 4); + s.execute("library.browse", &json!({"path": other.to_string_lossy()})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [other.join("d.png").to_string_lossy()], "recipe": recipe})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(adjusted(&s, "d.png"), (0.0, false), "a browsed photo that joins keeps its own settings"); + let _ = std::fs::remove_dir_all(&src); + let _ = std::fs::remove_dir_all(&other); +} + +/// A saved recipe never takes another preset's id: with presets A and B, A deleted, a recipe saved +/// as "B" is its own preset and applying it applies the recipe, not the older B. Saving the same +/// recipe under the same name again is that preset, and the presets are in presets.json. +#[test] +fn saved_recipe_presets_get_distinct_ids_and_survive_reopening() { + let lib = temp_dir("recipe-presets-lib"); + let src = temp_dir("recipe-presets-src"); + write_png(&src.join("a.png"), 1); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let photo = import_one(&mut s, &src.join("a.png"), json!([])); + s.selection = crate::Selection::single(photo); + let create = |s: &mut Session, name: &str| s.execute("preset.create", &json!({"name": name})).unwrap()["id"].as_str().unwrap().to_string(); + let (a, old_b) = (create(&mut s, "A"), create(&mut s, "B")); + s.execute("preset.delete", &json!({"id": a})).unwrap(); + let recipe = json!([{"id": "light.exposure", "value": 0.7}]); + let saved = s.execute("preset.saveRecipe", &json!({"name": "B", "group": "User Presets", "recipe": recipe})).unwrap(); + let new_b = saved["id"].as_str().unwrap().to_string(); + assert_ne!(new_b, old_b); + let mut all: Vec<&str> = s.presets.iter().map(|p| p.id.as_str()).collect(); + let n = all.len(); + all.sort(); + all.dedup(); + assert_eq!(all.len(), n, "every preset has its own id"); + s.execute("preset.apply", &json!({"id": new_b})).unwrap(); + assert_eq!(s.catalog.photo(photo).unwrap().develop.light.exposure, 0.7, "the saved recipe is what gets applied"); + // the same recipe, name and group: the preset it already is + let again = s.execute("preset.saveRecipe", &json!({"name": "B", "group": "User Presets", "recipe": recipe})).unwrap(); + assert_eq!(again["id"], saved["id"]); + assert_eq!(s.presets.iter().filter(|p| p.name == "B").count(), 2); + drop(s); + + let mut t = Session::new().with_fs(); + t.open_library(&lib, false).unwrap(); + let mut bs: Vec<&str> = t.presets.iter().filter(|p| p.name == "B").map(|p| p.id.as_str()).collect(); + bs.sort(); + let mut expected = [old_b.as_str(), new_b.as_str()]; + expected.sort(); + assert_eq!(bs, expected, "both are still there after reopening"); + assert!(!t.presets.iter().any(|p| p.name == "A"), "the deleted one stays deleted"); + drop(t); + let _ = std::fs::remove_dir_all(&lib); + let _ = std::fs::remove_dir_all(&src); +} + +/// Both commands are in the command list with their parameters documented, which is where the +/// control channel, the CLI and MCP's `list_commands` read them. +#[test] +fn the_recipe_commands_are_listed_with_their_parameters() { + let s = Session::new(); + let commands = s.commands(); + let import = commands.iter().find(|c| c.id == "library.import").unwrap(); + assert!(import.params.contains("recipe?: [{id:") && import.params.contains("Import adjustments"), "{}", import.params); + assert!(import.params.contains("no white balance, geometry or crop") && import.params.contains("is not changed"), "{}", import.params); + let save = commands.iter().find(|c| c.id == "preset.saveRecipe").expect("preset.saveRecipe is a command"); + assert!(save.enabled && save.params.contains("recipe: [{id:") && save.params.contains("name"), "{}", save.params); +} + +/// A saved recipe that resets an HDR control to its default is applied as the recipe would apply it: +/// alone, and next to another adjustment, on a photo whose HDR settings are not the default. +#[test] +fn a_saved_hdr_reset_applies_to_existing_hdr_settings() { + let mut s = Session::new(); + for recipe in [json!([{"id": "hdr.maxEv", "value": 3}]), json!([{"id": "hdr.maxEv", "value": 3}, {"id": "light.exposure", "value": 0.5}])] { + let p = s.execute("preset.saveRecipe", &json!({"name": format!("Reset {recipe}"), "recipe": recipe})).unwrap(); + let saved = s.presets.iter().find(|x| x.id == p["id"].as_str().unwrap()).unwrap().settings.clone(); + let mut base = lightcraft_develop::DevelopSettings::default(); + base.hdr.enabled = true; + base.hdr.max_ev = 1.5; + let out = lightcraft_develop::apply_partial(&base, &saved, 1.0); + assert_eq!(out.hdr.max_ev, 3.0, "{saved}"); + assert!(out.hdr.enabled, "the reset leaves the other HDR settings alone: {saved}"); + let want_exposure = if recipe.as_array().unwrap().len() > 1 { 0.5 } else { base.light.exposure }; + assert_eq!(out.light.exposure, want_exposure, "{saved}"); + } +} + /// A folder's one spelling: `.` is the current folder, `.` and `..` are taken out, never above the /// root (CodeRabbit on #3055 / #3080). #[test] diff --git a/crates/mcp/tests/it/e2e.rs b/crates/mcp/tests/it/e2e.rs index 2a8db44c7d..0e0bd98e5e 100644 --- a/crates/mcp/tests/it/e2e.rs +++ b/crates/mcp/tests/it/e2e.rs @@ -412,3 +412,48 @@ fn export_without_token_finishes_after_eof() { assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2); std::fs::remove_dir_all(dir).unwrap(); } + +/// A batch-edit recipe is reachable over MCP without a tool of its own: `run_command` takes +/// `library.import` with a `recipe`, the generated `cmd_preset_saveRecipe` tool saves one as a +/// preset, `list_commands` documents both, and a recipe naming white balance is a tool error that +/// imports nothing. +#[test] +fn a_batch_edit_recipe_is_reachable_over_mcp() { + let dir = std::env::temp_dir().join(format!("lightcraft-mcp-recipe-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8::from_fn(96, 64, |x, y| [(x * 2) as u8, (y * 3) as u8, 128, 255]); + lightcraft_mcp::write_image(&dir.join("gradient.png"), &img, 90).unwrap(); + let paths = json!([dir.to_string_lossy()]); + let mut server = Server::new(Box::new(Headless::default())); + let replies = session( + &mut server, + &[ + call(1, "list_commands", json!({"filter": "recipe"})), + call(2, "run_command", json!({"command": "library.import", "params": {"paths": paths, "recipe": [{"id": "wb.temp", "value": 5000}]}})), + call(3, "query_photos", json!({"limit": 5})), + call( + 4, + "run_command", + json!({"command": "library.import", "params": {"paths": paths, "recipe": [{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}]}}), + ), + call(5, "get_develop", json!({})), + call(6, "cmd_preset_saveRecipe", json!({"name": "Warm", "recipe": [{"id": "light.exposure", "value": 0.5}]})), + call(7, "list_commands", json!({"filter": "library.import"})), + ], + ); + let listed = |r: &Value| -> Vec { serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap() }; + let save = listed(&replies[0]).into_iter().find(|c| c["id"] == "preset.saveRecipe").expect("preset.saveRecipe is listed"); + assert!(save["params"].as_str().unwrap().contains("recipe: [{id:"), "{save}"); + assert_eq!(replies[1]["result"]["isError"], true, "{}", replies[1]); + assert!(replies[1]["result"]["content"][0]["text"].as_str().unwrap().contains("white balance"), "{}", replies[1]); + assert!(replies[2]["result"]["structuredContent"]["photos"].as_array().unwrap().is_empty(), "the refused import added nothing"); + assert_eq!(replies[3]["result"]["isError"], false, "{}", replies[3]); + assert_eq!(replies[3]["result"]["structuredContent"]["imported"].as_array().unwrap().len(), 1); + assert_eq!(replies[4]["result"]["structuredContent"]["light"]["exposure"], 0.5, "{}", replies[4]); + assert_eq!(replies[4]["result"]["structuredContent"]["color"]["vibrance"], 20.0, "{}", replies[4]); + assert_eq!(replies[5]["result"]["isError"], false, "{}", replies[5]); + assert_eq!(replies[5]["result"]["structuredContent"]["name"], "Warm"); + let import = listed(&replies[6]).into_iter().find(|c| c["id"] == "library.import").expect("library.import is listed"); + assert!(import["params"].as_str().unwrap().contains("recipe?: [{id:"), "{import}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 43d8da59b4..7e78396a1c 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "{n} Foto{} zu „Meine Fotos“ hinzugefügt", "Added {n} photo{} to “{}”": "{n} Foto{0} zu „{1}“ hinzugefügt", "Added {what} to {name}": "{what} zu {name} hinzugefügt", + "Adjustments: {n}": "Anpassungen: {n}", "Adding photos… {} of {}": "Fotos werden hinzugefügt… {} von {}", "All {n} selected photos move by the same amount.": "Alle {n} ausgewählten Fotos werden um denselben Betrag verschoben.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Bereits in der Bibliothek unter „Zuletzt gelöscht“: {} Foto{} ausgewählt · Rechtsklick → Wiederherstellen, oder endgültig löschen, um neu zu importieren", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index bdfd440f1f..77d40f0ec0 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "{n} foto{0} añadida{0} a Mis fotos", "Added {n} photo{} to “{}”": "{n} foto{0} añadida{0} a “{1}”", "Added {what} to {name}": "{what} añadido a {name}", + "Adjustments: {n}": "Ajustes: {n}", "Adding photos… {} of {}": "Añadiendo fotos… {} de {}", "All {n} selected photos move by the same amount.": "Las {n} fotos seleccionadas se desplazan la misma cantidad.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Ya en la biblioteca, en Eliminadas recientemente: {0} foto{1} seleccionada{1} · clic derecho → Restaurar, o Eliminar definitivamente para importar de nuevo", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 16782e3499..ba6bcc7b0f 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "{n} photo{} ajoutée(s) à Mes photos", "Added {n} photo{} to “{}”": "{n} photo{} ajoutée(s) à « {} »", "Added {what} to {name}": "{what} ajouté à {name}", + "Adjustments: {n}": "Réglages : {n}", "Adding photos… {} of {}": "Ajout des photos… {} sur {}", "All {n} selected photos move by the same amount.": "Les {n} photos sélectionnées se déplacent de la même valeur.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Déjà dans la bibliothèque, dans « Supprimés récemment » : {} photo{} sélectionnée(s) · clic droit → Restaurer, ou Supprimer définitivement pour importer à nouveau", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index bc6ce0e60a..9f7dd3fe7c 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": "。{outside}枚は記録時間の範囲外", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:PR {}件、コミット {}件、+{} / −{} 行(Δ {})、バイナリアセット +{} / −{}、{} – {}", "Added {what} to {name}": "{what}を{name}に追加しました", + "Adjustments: {n}": "調整:{n}", "Auto Import: added {} photo{}": "自動読み込み:{}枚の写真を追加しました{:.0}", "Building previews for {} photos…": "{}枚のプレビューを作成中…", "Couldn't open the editor: {e}": "エディターを開けませんでした:{e}", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index cecd8149c0..4227fe328a 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": "; {outside} fora do intervalo de tempo", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}: {} PRs, {} commits, +{} / −{} linhas (Δ {}), +{} / −{} arquivos binários, {} – {}", "Added {what} to {name}": "{what} adicionado a {name}", + "Adjustments: {n}": "Ajustes: {n}", "Auto Import: added {} photo{}": "Importação automática: {} foto{1} adicionada{1}", "Building previews for {} photos…": "Gerando prévias de {} fotos…", "Couldn't open the editor: {e}": "Não foi possível abrir o editor: {e}", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index d6156cc1fa..24134de944 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -25,6 +25,7 @@ "Added {n} photo{} to My Photos": "В «Мои фото» добавлено фото: {n}{:.0}", "Added {n} photo{} to “{}”": "В «{1}» добавлено фото: {n}{0:.0}", "Added {what} to {name}": "{what}: добавлено в {name}", + "Adjustments: {n}": "Корректировки: {n}", "Adding photos… {} of {}": "Добавление фото… {} из {}", "All {n} selected photos move by the same amount.": "Все выбранные фото ({n}) сдвигаются на одно и то же значение.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в библиотеке, в «Недавно удалённых»: выбрано фото: {}{:.0} · щёлкните правой кнопкой → Восстановить или Удалить навсегда, чтобы импортировать заново", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index ed5e041f82..d30091f2d2 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "До моїх фото додано: {n}{:.0}", "Added {n} photo{} to “{}”": "До «{1}» додано фото: {n}{0:.0}", "Added {what} to {name}": "{what}: додано до {name}", + "Adjustments: {n}": "Коригування: {n}", "Adding photos… {} of {}": "Додавання фото… {} з {}", "All {n} selected photos move by the same amount.": "Усі вибрані фото ({n}) зміщуються на однакове значення.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в бібліотеці, у нещодавно видалених: вибрано фото: {}{:.0} · права кнопка → Відновити або Видалити назавжди, щоб імпортувати заново", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 2996e1a217..1d5f27c576 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": ";{outside} 张不在其时间范围内", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:{} 个 PR,{} 次提交,+{} / −{} 行(Δ {}),+{} / −{} 个二进制资源,{} – {}", "Added {what} to {name}": "已将{what}添加到 {name}", + "Adjustments: {n}": "调整:{n}", "Auto Import: added {} photo{}": "自动导入:已添加 {0} 张照片{1:.0}", "Building previews for {} photos…": "正在为 {0} 张照片生成预览…", "Couldn't open the editor: {e}": "无法打开编辑器:{e}", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 93f6d6fa00..51fb1109ae 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": ";{outside} 張不在其時間範圍內", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:{} 個 PR,{} 次提交,+{} / −{} 行(Δ {}),+{} / −{} 個二進位資產,{} – {}", "Added {what} to {name}": "已將{what}加入 {name}", + "Adjustments: {n}": "調整:{n}", "Auto Import: added {} photo{}": "自動匯入:已新增 {} 張照片{:.0}", "Building previews for {} photos…": "正在為 {} 張照片建立預覽…", "Couldn't open the editor: {e}": "無法開啟編輯器:{e}", diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index 4336e5e82f..5ce31dacce 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -3,7 +3,8 @@ //! a grid of thumbnails with checkboxes (duplicates marked and unchecked; Shift-click sets a //! range), the destination (add in place / copy or move into the library's `Originals/` or a //! chosen folder, filed by day, by month, into one folder or by a custom folder template, -//! optionally renamed), an album (existing or new), a preset and keywords to apply. When the scan +//! optionally renamed), an album (existing or new), a preset, an optional batch-edit recipe +//! ("Batch edits": develop controls set on every new photo) and keywords to apply. When the scan //! left something out (a walk cut at its limit, folders it couldn't read, files that are not //! photos) one line under the count says so ([`scan_note`]). Importing runs on a worker thread //! (files are probed, copied or moved there) and its batches join the catalog between frames, with @@ -29,6 +30,7 @@ mod task; #[cfg(test)] pub(crate) use body::grid_height; +use body::recipe_items; pub(crate) use body::scan_note; #[cfg(test)] pub(crate) use body::thumb_edge; @@ -36,6 +38,8 @@ pub(crate) use body::thumb_edge; use body::{DEFAULT_BELOW_GRID, badge_rect, dup_counts}; pub use body::{DEFAULT_FOLDER_TEMPLATE, body, example_destination, source_summary}; pub(crate) use body::{DIALOG_SIZE, THUMB_SIZE_DEFAULT, note_dialog_bottom, thumb_size}; +#[cfg(test)] +use body::{RECIPE_CONTROLS, note_recipe_value}; pub(crate) use scan::StoppingScans; #[cfg(not(target_arch = "wasm32"))] pub(crate) use scan::cards_seen; @@ -63,6 +67,12 @@ pub struct ImportDialog { pub new_album: String, /// Preset id ("" = none). pub preset: String, + /// An optional batch-edit recipe: develop control id → value (only controls moved off their + /// default are kept), set on every photo this import adds, on top of its sidecar, camera + /// default and preset (the `recipe` param of `library.import`). + pub recipe: std::collections::BTreeMap, + /// Name typed for "Save as Preset" (the recipe saved for reuse). + pub recipe_name: String, /// Comma-separated keywords. pub keywords: String, /// Copy: destination folder ("" = the library's Originals/). @@ -384,4 +394,50 @@ mod tests { d.click(2, true); assert_eq!(d.checked, [true, true, false, false, true, true]); } + + /// The dialog offers only controls a recipe may name: `library.import` refuses the others + /// (white balance, geometry and crop, per-photo controls), so one offered here would make every + /// import with it fail. Each is moved off its default, as a slider drag does. + #[test] + fn every_offered_recipe_control_is_accepted_by_the_import() { + let session = lightcraft_engine::Session::new(); + let mut d = dialog(); + for id in RECIPE_CONTROLS { + let spec = lightcraft_develop::controls::find(id).unwrap_or_else(|| panic!("{id} is not a develop control")); + let moved = if spec.default < spec.max { spec.max } else { spec.min }; + note_recipe_value(&mut d.recipe, spec, moved); + } + assert_eq!(d.recipe.len(), RECIPE_CONTROLS.len(), "all named, none repeated"); + let params = json!({"paths": ["img0.jpg"], "recipe": recipe_items(&d.recipe)}); + let request = lightcraft_engine::cmd::library::import_params(&session, ¶ms).unwrap_or_else(|e| panic!("refused: {e}")); + assert_eq!(request.opts.recipe.len(), RECIPE_CONTROLS.len()); + } + + /// A slider moved off its default names its control in the recipe; moved back, it no longer does. + #[test] + fn a_slider_back_at_its_default_leaves_the_recipe() { + let spec = lightcraft_develop::controls::find("light.exposure").unwrap(); + let mut recipe = std::collections::BTreeMap::new(); + note_recipe_value(&mut recipe, spec, 0.5); + assert_eq!(recipe.get("light.exposure"), Some(&0.5)); + note_recipe_value(&mut recipe, spec, 1.25); + assert_eq!(recipe.get("light.exposure"), Some(&1.25), "a new value replaces the old"); + note_recipe_value(&mut recipe, spec, spec.default); + assert!(recipe.is_empty(), "{recipe:?}"); + } + + /// `start` hands `library.import` a `recipe` only when the dialog has one. + #[test] + fn start_passes_the_recipe_only_when_the_dialog_has_one() { + let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::new(), crate::Services { png: None, ..Default::default() }); + let mut d = dialog(); + start(&mut app, &d).unwrap(); + let params = app.import.take().map(|t| t.params).unwrap(); + assert!(params.get("recipe").is_none(), "{params}"); + d.recipe.insert("light.exposure".into(), 0.5); + d.recipe.insert("color.vibrance".into(), -20.0); + start(&mut app, &d).unwrap(); + let params = app.import.take().map(|t| t.params).unwrap(); + assert_eq!(params["recipe"], json!([{"id": "color.vibrance", "value": -20.0}, {"id": "light.exposure", "value": 0.5}]), "{params}"); + } } diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index d461d690ab..5228f7b95b 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -1,7 +1,7 @@ use serde_json::json; use super::tags::{tag_field_width, tag_help, tag_toggle, unknown_tags_warning}; -use super::{Color32, ImportDialog, LightcraftApp, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, Vec2, pos2, register, vec2}; +use super::{Color32, ImportDialog, LightcraftApp, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, Value, Vec2, pos2, register, vec2}; /// The review dialog's first size (points). It can be resized; the photo grid takes the height. pub(crate) const DIALOG_SIZE: [f32; 2] = [960.0, 720.0]; @@ -447,6 +447,96 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { let r = ui.add(egui::TextEdit::singleline(&mut d.keywords).hint_text(crate::i18n::tr("comma, separated")).desired_width(f32::INFINITY)); register(ui, "field:importKeywords", r.rect); }); + recipe_section(app, ui, d); +} + +/// The develop controls offered in the import review's optional batch-edit recipe: the everyday +/// adjustments, not a second editor. Each must be one a recipe may name (`library.import` refuses +/// the others: no white balance, geometry or crop); a test holds the list to that. Anything else is +/// reached by choosing or saving a preset. +pub(super) const RECIPE_CONTROLS: &[&str] = &[ + "light.exposure", + "light.contrast", + "light.highlights", + "light.shadows", + "light.whites", + "light.blacks", + "color.vibrance", + "color.saturation", + "effects.clarity", + "effects.texture", + "effects.dehaze", + "detail.sharpenAmount", + "grain.amount", + "vignette.amount", +]; + +/// A recipe as the `recipe` param of `library.import` and `preset.saveRecipe`. +pub(super) fn recipe_items(recipe: &std::collections::BTreeMap) -> Value { + Value::Array(recipe.iter().map(|(id, v)| json!({"id": id, "value": v})).collect()) +} + +/// Record a slider's new value in the recipe: a control back at its default is no longer named. +pub(super) fn note_recipe_value(recipe: &mut std::collections::BTreeMap, spec: &lightcraft_develop::controls::ControlSpec, value: f64) { + if (value - spec.default).abs() < 1e-9 { + recipe.remove(spec.id); + } else { + recipe.insert(spec.id.to_string(), value); + } +} + +/// The optional "Batch edits" section of the import review: a small recipe of develop controls set +/// on every photo this import adds, on top of its XMP sidecar, camera default and the chosen preset. +/// The recipe lives only in the dialog until the import runs, so cancelling changes neither the +/// catalog nor the preset collections; "Save as Preset" is the explicit way to keep one for reuse. +fn recipe_section(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { + let t = Tokens::get(ui.ctx()); + let open_id = egui::Id::unique("import-recipe-open"); + let mut open = ui.ctx().data(|m| m.get_temp::(open_id)).unwrap_or(false); + field(ui, "Batch edits", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + if crate::widgets::text_button(ui, "importRecipeToggle", if open { "Hide adjustments" } else { "Adjust…" }, open).clicked() { + open = !open; + } + let n = d.recipe.len(); + let summary = if n == 0 { crate::i18n::tr("None").to_string() } else { crate::i18n::tr_format!("Adjustments: {n}", n = n) }; + ui.label(egui::RichText::new(summary).color(if n == 0 { t.text_dim } else { t.text_label })); + }); + ui.ctx().data_mut(|m| m.insert_temp(open_id, open)); + if !open { + return; + } + ui.label( + egui::RichText::new(crate::i18n::tr( + "Set on every photo this import adds, after its XMP sidecar and the preset above; photos the library already has are left alone. A slider left at its default changes nothing. Nothing is saved unless you save it as a preset.", + )) + .color(t.text_dim) + .small(), + ); + for &id in RECIPE_CONTROLS { + let Some(spec) = lightcraft_develop::controls::find(id) else { continue }; + let v = d.recipe.get(id).copied().unwrap_or(spec.default); + if let Some(nv) = crate::widgets::slider(ui, spec, v, true, None).value { + note_recipe_value(&mut d.recipe, spec, nv); + } + } + field(ui, "Recipe", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + crate::text_field::TextField::singleline("field:importRecipeName", &mut d.recipe_name) + .hint(crate::i18n::tr("name for a saved preset")) + .width(160.0) + .show(ui); + let can = !d.recipe.is_empty() && !d.recipe_name.trim().is_empty(); + let b = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("Save as Preset"))); + register(ui, "button:importRecipeSave", b.rect); + if b.clicked() { + let params = json!({"name": d.recipe_name.trim(), "recipe": recipe_items(&d.recipe)}); + match app.run("preset.saveRecipe", params) { + Ok(_) => app.toast(ui.ctx(), crate::i18n::tr("Saved as a preset")), + Err(e) => app.toast_error(ui.ctx(), e), + } + } + }); } /// Draw one import-dialog candidate cell: register `import:{i}`, request the cell's thumbnail, diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index 5c27983400..71ac358f9a 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -1,5 +1,5 @@ use super::scan::{busy_synchronizing, running}; -use super::{ImportDialog, ImportUprightMode, ImportWarning, ImportWarningCode, LightcraftApp, Ordering, Value, json}; +use super::{ImportDialog, ImportUprightMode, ImportWarning, ImportWarningCode, LightcraftApp, Ordering, Value, json, recipe_items}; /// Files per batch in the browser build (each batch joins the catalog as it is ready, so the /// progress window updates); the desktop's worker uses [`lightcraft_engine::import::batch_size`]. @@ -16,7 +16,7 @@ pub struct ImportTask { queue: Vec, pub total: usize, pub done: usize, - params: Value, + pub(super) params: Value, pub imported: usize, /// Brought back from Recently Deleted (`onDeleted: restore`). pub restored: usize, @@ -225,6 +225,9 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result (true, true) => "move", }; let mut params = json!({"mode": mode, "keywords": d.keywords()}); + if !d.recipe.is_empty() { + params["recipe"] = recipe_items(&d.recipe); + } if !d.on_deleted.is_empty() { params["onDeleted"] = json!(d.on_deleted); } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e71ef8164a..f801ee843f 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -40,6 +40,7 @@ mod grid; mod grid_drag; mod guided_guides; mod histogram_drag; +mod import_recipe; mod import_scan_note; mod import_thumbnails; mod info_dialogs; diff --git a/crates/ui-egui/src/tests/import_recipe.rs b/crates/ui-egui/src/tests/import_recipe.rs new file mode 100644 index 0000000000..7a46603dfe --- /dev/null +++ b/crates/ui-egui/src/tests/import_recipe.rs @@ -0,0 +1,182 @@ +//! The import review's "Batch edits" section: the recipe in the dialog is what the import sets on +//! the photos it adds, "Save as Preset" needs a name and a recipe, and cancelling the review +//! changes neither the catalog nor the presets. + +use std::path::PathBuf; +use std::time::Duration; + +use serde_json::json; + +use crate::dialogs::import::ImportDialog; +use crate::headless::Headless; +use crate::state::{Dialog, ViewMode}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +/// A folder of two small PNGs. +fn folder(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-ui-import-recipe-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for i in 0..2u8 { + let data: Vec<[u8; 4]> = (0..40 * 30).map(|k| [(k % 40 * 6) as u8, i * 90, 7, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: 40, height: 30, data }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(dir.join(format!("img{i}.png")), png).unwrap(); + } + dir +} + +/// The app with an empty library and the import review open on a folder of two photos. +fn review(tag: &str) -> (Headless, PathBuf) { + let dir = folder(tag); + let app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 1400.0], 1.0); + h.app.ui.view = ViewMode::PhotoGrid; + let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [dir.to_string_lossy()]}}), T); + assert_eq!(r["result"]["scanning"], true, "{r}"); + assert!(h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the review opens"); + h.settle(SETTLE); + (h, dir) +} + +fn dialog(h: &mut Headless) -> &mut ImportDialog { + match &mut h.app.ui.dialog { + Some(Dialog::Import { opts }) => opts, + other => panic!("no import review: {other:?}"), + } +} + +/// Where a widget is and where the review's window is: `[x, y, w, h]` each. +fn rects(h: &mut Headless, id: &str) -> ([f64; 4], [f64; 4]) { + let r = h.request("ui.widgets", json!({}), T); + let all = r["result"].as_array().expect("widgets"); + let find = |name: &str| -> [f64; 4] { + let w = all.iter().find(|w| w["id"] == name).unwrap_or_else(|| panic!("no widget {name}")); + [0usize, 1, 2, 3].map(|i| w["rect"][i].as_f64().unwrap()) + }; + (find(id), find("dialog:window")) +} + +/// Click a widget of the review, scrolling the review first when the widget is below its window +/// (the review's content scrolls; the Batch edits section is at the bottom of it). +fn click(h: &mut Headless, id: &str) { + for _ in 0..40 { + let (w, win) = rects(h, id); + if w[1] + w[3] <= win[1] + win[3] - 30.0 { + break; + } + h.request("ui.move", json!({"x": win[0] + win[2] / 2.0, "y": win[1] + win[3] / 2.0}), T); + h.request("ui.scroll", json!({"dy": -400.0}), T); + h.settle(SETTLE); + } + let (w, win) = rects(h, id); + assert!(w[1] >= win[1] && w[1] + w[3] <= win[1] + win[3], "{id} {w:?} is inside the window {win:?}"); + let r = h.request("ui.clickWidget", json!({"id": id}), T); + assert_eq!(r["ok"], true, "{id}: {r}"); + h.settle(SETTLE); +} + +fn toast(h: &Headless) -> String { + h.app.ui.toast.clone().map(|t| t.0).unwrap_or_default() +} + +/// Wait for the import the review started to finish. +fn finish_import(h: &mut Headless) { + let t0 = std::time::Instant::now(); + while h.app.import.is_some() && t0.elapsed() < Duration::from_secs(60) { + h.step(); + } + assert!(h.app.import.is_none(), "the import finished"); + h.settle(SETTLE); +} + +/// "Save as Preset" saves nothing without a name or without a recipe, and with both saves exactly +/// the recipe as a preset, leaving the review's own choices (its preset, the photos) as they were. +#[test] +fn save_as_preset_needs_a_name_and_a_recipe() { + let (mut h, dir) = review("save"); + let presets0 = h.app.session.presets.len(); + click(&mut h, "button:importRecipeToggle"); + assert!( + h.request("ui.widgets", json!({"filter": "importRecipeSave"}), T)["result"].as_array().is_some_and(|w| !w.is_empty()), + "the section is open" + ); + + dialog(&mut h).recipe_name = "Warm trip".into(); + click(&mut h, "button:importRecipeSave"); + assert_eq!(h.app.session.presets.len(), presets0, "a name alone saves nothing"); + assert_eq!(toast(&h), "", "the button is off: pressing it does not even ask the engine (which would refuse with a message)"); + + let d = dialog(&mut h); + d.recipe_name = " ".into(); + d.recipe.insert("light.exposure".into(), 0.5); + click(&mut h, "button:importRecipeSave"); + assert_eq!(h.app.session.presets.len(), presets0, "a recipe alone saves nothing"); + assert_eq!(toast(&h), "", "the button is off without a name too"); + + dialog(&mut h).recipe_name = " Warm trip ".into(); + click(&mut h, "button:importRecipeSave"); + assert_eq!(h.app.session.presets.len(), presets0 + 1, "{}", toast(&h)); + let saved = h.app.session.presets.iter().find(|p| p.name == "Warm trip").expect("the preset is named as typed, trimmed"); + assert_eq!(saved.settings, json!({"light": {"exposure": 0.5}}), "only what the recipe names"); + assert_eq!(toast(&h), "Saved as a preset"); + assert_eq!(dialog(&mut h).preset, "", "the review's own preset choice is not replaced"); + assert_eq!(h.app.session.catalog.len(), 0, "nothing was imported"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Cancelling the review with a recipe in it adds no photo and saves no preset. +#[test] +fn cancelling_the_review_discards_the_recipe() { + let (mut h, dir) = review("cancel"); + let presets0 = h.app.session.presets.len(); + let undo0 = h.app.session.undo.len(); + let d = dialog(&mut h); + d.recipe.insert("light.exposure".into(), 0.5); + d.recipe_name = "Never saved".into(); + h.settle(SETTLE); + let r = h.request("ui.dialog.cancel", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.dialog.is_none() && h.app.import.is_none()); + assert_eq!((h.app.session.catalog.len(), h.app.session.presets.len(), h.app.session.undo.len()), (0, presets0, undo0)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Confirming the review with a recipe imports the photos with it: each has the values and the +/// Import adjustments step, and the import is still one undo step. +#[test] +fn confirming_with_a_recipe_sets_it_on_the_new_photos() { + let (mut h, dir) = review("confirm"); + let undo0 = h.app.session.undo.len(); + let d = dialog(&mut h); + d.recipe.insert("light.exposure".into(), 0.5); + d.recipe.insert("color.vibrance".into(), 20.0); + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + finish_import(&mut h); + assert_eq!(h.app.session.catalog.len(), 2); + for p in h.app.session.catalog.photos() { + assert_eq!((p.develop.light.exposure, p.develop.color.vibrance), (0.5, 20.0), "{}", p.file_name); + assert!(p.history.iter().any(|s| s.label == "Import adjustments"), "{}", p.file_name); + } + assert_eq!(h.app.session.undo.len(), undo0 + 1, "one undo step"); + h.request("engine.execute", json!({"command": "edit.undo"}), T); + assert_eq!(h.app.session.catalog.len(), 0); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Confirming without a recipe adds no Import adjustments step. +#[test] +fn confirming_without_a_recipe_adds_no_adjustment_step() { + let (mut h, dir) = review("plain"); + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + finish_import(&mut h); + assert_eq!(h.app.session.catalog.len(), 2); + assert!(h.app.session.catalog.photos().all(|p| !p.history.iter().any(|s| s.label == "Import adjustments"))); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/gaps.md b/docs/gaps.md index 5d01ebf9a2..08cebce09d 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -153,6 +153,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-12 | minor | Gap 20 shrinks: Mamiya MEF decodes (`vendor/mef.rs`) and is imported; gap 10 count 240 → 241 | | 2026-10-12 | minor | Gap 20 shrinks: Epson ERF decodes (`vendor/erf.rs`), 3 bodies verified; gap 10 count 237 → 240 | | 2026-10-13 | minor | Gap 28: F6 (filmstrip) and F7 (left panel) are bound, so the entry no longer lists them as missing; hours unchanged | +| 2026-10-13 | minor | Import gains an optional batch-edit recipe (LR-IMP-RECIPE); it is additive and no ranked gap lists it, so no gap closes and the numbers do not move | | 2026-10-20 | patch | Gap 24: extreme brush segments skip the intermediate dabs; the gap stays open | | 2026-10-11 | minor | Gap 10 shrinks: Leica Q3 verified by a recorded check of 38 private DNGs (236 models verified; Leica 14); gap not closed | | 2026-10-12 | minor | Camera-look deep shadows follow the JPEG toe (#1307); camera calibration remains partial | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index bcdaada1cf..99381ec5f5 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -26,7 +26,7 @@ cited here still exists. Formerly docs/parity.md. | Section | ✅ | 🟡 | ⬜ | 🚫 | P0 done | P1 done | |---|---:|---:|---:|---:|---:|---:| -| A. Import (IMP) | 12 | 3 | 1 | 1 | 4/6 (67%) | 5/5 (100%) | +| A. Import (IMP) | 13 | 3 | 1 | 1 | 4/6 (67%) | 5/5 (100%) | | B. Library management (LIB) | 22 | 2 | 1 | 2 | 9/9 (100%) | 9/9 (100%) | | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | @@ -75,6 +75,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/dialogs/import.rs`) | | LR-IMP-AUTO | Watched-folder auto import | P2 | ✅ | `cmd:library.autoImport`, `cmd:library.autoImportScan`, `crates/ui-egui/src/dialogs/settings.rs` | Settings ▸ Import ▸ Auto Import: a watched folder whose new photos are added (in place or copied) once complete, into an optional album; scanned every 3 s | | LR-IMP-PRESET | Preset on import | P2 | ✅ | `cmd:library.import` (`preset`) | chosen in the import review; one History entry | +| LR-IMP-RECIPE | Batch edits during import | P2 | ✅ | `cmd:library.import` (`recipe`), `cmd:preset.saveRecipe` (registered; `crates/engine/src/tests/import.rs` asserts it), `crates/ui-egui/src/dialogs/import.rs` | an optional Batch edits section in the import review: sliders for everyday adjustments (Light, Vibrance and Saturation, Clarity, Texture and Dehaze, Sharpening, Grain, Vignette) whose values are set on every photo the import adds, after its XMP sidecar, camera default and the chosen preset, as one extra History step (`Import adjustments`) after the preset's own; a photo the library already has (a duplicate, one restored from Recently Deleted, one joined from a browsed folder) is not changed; a summary beside the section counts the adjustments, it does not list them; Save as Preset stores only the settings the recipe names (`cmd:preset.saveRecipe`) so it can be reused from the Preset list; the recipe lives only in the dialog until the import runs, so Cancel changes neither the catalog nor the preset collections. The command takes any plain develop control, not only the ones the dialog offers, and refuses white balance, geometry and crop controls, per-photo controls and unknown ids before anything is imported. Not a second editor: white balance is not offered (a temperature means something else on a raw than on a rendered photo, so the command refuses it too), and neither are crop, masks, curve or point colour; a slider left at its default names nothing, so setting a control to its default for the whole batch is only possible through the command | | LR-IMP-RAWDEFAULT | Raw defaults | P1 | ✅ | `cmd:library.preferences`, `crates/engine/src/import.rs`, `crates/ui-egui/src/dialogs/settings.rs` | LightCraft default / a preset / per camera (make + model); non-raw default too; the preset look counts as unedited and Reset returns to it | | LR-IMP-MIGRATE | Migrate other catalogs | OOS | 🚫 | | | | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) | @@ -924,6 +925,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-13 | minor | KEY-SLIDER-RESET: hovering a slider's name or thumb says a double-click resets it; a double-click on the thumb is one undo step, not two; a disabled slider's name doesn't reset it (issue #1436); status unchanged (✅) | | 2026-10-20 | patch | LR-MASK-BRUSH: extreme segments skip intermediate dabs; ordinary spacing and endpoints preserved; status unchanged (🟡) | | 2026-10-12 | minor | LR-META-XMP: bounded complete-APP1 manual JPEG reread, fail-closed sidecar precedence and scoped regression coverage; LR-META-EXIF-FULL: reuse loaded bytes; statuses unchanged | +| 2026-10-13 | minor | LR-IMP-RECIPE added (✅): an optional batch-edit recipe for newly imported photos (`library.import` `recipe`, `preset.saveRecipe`, the Batch edits section of the import review); no existing row changes | | 2026-10-13 | minor | LR-IMP-ADD-DIALOG: the import review (and `library.importPreview`) says when its folder scan stopped at the walk limit, could not read folders or skipped files that are not a supported photo type; no walk behaviour changes; status unchanged (✅) | | 2026-10-13 | minor | LR-IMP-ADD-DIALOG: the import review (and `library.importPreview`) says when its folder scan stopped at the walk limit, could not read folders or skipped files that are not a supported photo type (XMP sidecars are not counted); no walk behaviour changes; status unchanged (✅) | | 2026-10-11 | minor | LR-MERGE-HDR: HDR and panorama merges of raws without colour matrices (CR2, NEF, ARW…) write the colour they open with as DNG tags (issue #965); status unchanged | From 472560b30936259fe50f8df67b9ad57ea8ef7a6d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 02:36:08 +0100 Subject: [PATCH 24/24] Tests: clipping warnings crush the shadows with Blacks (#3839) Main fails this test: Exposure -5 alone no longer leaves a channel at 0 in the demo photo. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/tests/alt_preview.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/ui-egui/src/tests/alt_preview.rs b/crates/ui-egui/src/tests/alt_preview.rs index 5997b41b43..96a9d60e6d 100644 --- a/crates/ui-egui/src/tests/alt_preview.rs +++ b/crates/ui-egui/src/tests/alt_preview.rs @@ -97,6 +97,10 @@ fn j_paints_clipped_highlights_red_and_clipped_shadows_blue() { assert!(h.app.ui.show_clipping); assert!(share_of(&h, red) > 0.5, "blown highlights shown in red: {}", share_of(&h, red)); set(&mut h, -5.0); + // the demo photo's shadows don't reach black on Exposure alone: Blacks crushes them + let r = h.request("engine.execute", json!({"command": "develop.set", "params": {"control": "light.blacks", "value": -100.0}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); assert!(share_of(&h, blue) > 0.01, "crushed shadows shown in blue: {}", share_of(&h, blue)); assert!(share_of(&h, red) < 0.01, "nothing blown at -5 EV: {}", share_of(&h, red)); }