From c571c4b436e2cfe4bec9b9bada4f1218dbe1eeb8 Mon Sep 17 00:00:00 2001 From: AlphaZentaurii <342205933+AlphaZentaurii@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:02:05 +0100 Subject: [PATCH 001/112] C1-DEVELOP: Levels as stored, Brightness and Levels as effective values The Levels import reads the columns in a different order and with a different midtone than Capture One writes them. This reads them as the catalog stores them, and reads Brightness and the Levels as the value that applies to a photo. Levels: each column is four numbers, red;green;blue;master (a master edit is 0.000;0.000;0.000;0.078), the points and output levels in 0..1 of the 0..255 scale, and ZMIDTONE is the tool's own signed value (-1..1, 0 neutral), not the place of a marker. The values are stored to three decimals and Capture One renders a reopened catalog from them, so they are read as stored, not rounded to whole levels. A black point above the white point is kept (an inverted channel), as are output levels that are inverted. Output levels count only while ZLEVELSTARGETENABLE isn't 0. A column that isn't four numbers in range is reported on its own line instead of guessed. Brightness and the Levels are the variant's effective value: the adjustment layer's, else a style's, else the camera default layer's, since Capture One can save them as camera defaults. A photo that keeps such a default gets it, an adjustment that resets a value over a non-neutral default writes nothing, and values within float noise of neutral (under 0.001 for Brightness, 0.0001 for each Levels value) count as neutral. Brightness keeps its factor of 2 (checked against Capture One's own exports, to 0.2 of an 8-bit level) and is no longer rounded. The other sliders and the curves are read as before. Reported in the import result: - "Capture One Levels (local adjustments): used on N photo(s), not imported yet": a local adjustment layer has Levels set to something other than neutral (local layers are still not imported). - "Capture One Levels: values could not be read on N photo(s); Levels skipped for these photos". - "Capture One Levels: black and white points closer than 2 levels on N photo(s); they were moved apart": the Levels tool keeps its points at least 2 levels apart. Tests: the Levels tests use the stored slot order and the signed midtone, and new tests cover effective values, tolerances, defaults, inverted points and the unreadable cases, with synthetic values. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/capture_one_catalog.rs | 117 ++++++- crates/engine/src/capture_one_develop.rs | 193 ++++++---- .../engine/src/capture_one_develop_tests.rs | 329 +++++++++++++++++- docs/lightroom-catalog-import.md | 16 +- 4 files changed, 576 insertions(+), 79 deletions(-) diff --git a/crates/engine/src/capture_one_catalog.rs b/crates/engine/src/capture_one_catalog.rs index 1dd566e450..5313c8352b 100644 --- a/crates/engine/src/capture_one_catalog.rs +++ b/crates/engine/src/capture_one_catalog.rs @@ -310,6 +310,8 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, let layers = crate::capture_one_develop::read_layers(&reader, &entities, cancel).map_err(|e| e.replace("Lightroom", "Capture One"))?; done.fetch_add(1, Ordering::Relaxed); let mut not_imported: BTreeMap = BTreeMap::new(); + let mut levels_too_close = 0usize; + let mut levels_unreadable = 0usize; let mut keyword_names: HashMap> = HashMap::new(); for (pk, k) in &keyword_tree { keyword_names.entry(text(k, "ZNAME").trim().to_lowercase()).or_default().push(*pk); @@ -421,11 +423,17 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, let develop = layers .get(&variant_pk) .map(|l| crate::capture_one_develop::develop_of(l, [width as f64, height as f64], (camera_make, camera_model))) - .filter(|d| !d.is_empty() || !d.not_imported.is_empty()); + .filter(|d| !d.is_empty() || !d.not_imported.is_empty() || d.levels_unreadable); for tool in develop.iter().flat_map(|d| &d.not_imported) { let count = not_imported.entry(tool.clone()).or_default(); *count = count.saturating_add(1); } + if develop.as_ref().is_some_and(|d| d.levels_too_close) { + levels_too_close = levels_too_close.saturating_add(1); + } + if develop.as_ref().is_some_and(|d| d.levels_unreadable) { + levels_unreadable = levels_unreadable.saturating_add(1); + } photos.push(CatalogPhoto { source_id: variant_pk, uuid: if uuid.is_empty() { String::new() } else { format!("c1:{uuid}") }, @@ -464,6 +472,15 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, for (tool, count) in not_imported { warnings.push(format!("Capture One {tool}: used on {count} photo(s), not imported yet (the photos keep the rest of their settings)")); } + if levels_unreadable > 0 { + warnings.push(format!("Capture One Levels: values could not be read on {levels_unreadable} photo(s); Levels skipped for these photos")); + } + if levels_too_close > 0 { + warnings.push(format!( + "Capture One Levels: black and white points closer than {} levels on {levels_too_close} photo(s); they were moved apart", + lcc_develop::LEVELS_MIN_GAP + )); + } // ---- albums, with the projects and groups that hold them let kinds: HashMap = collections @@ -813,15 +830,17 @@ mod tests { let read = read_with_progress(&db, &cancel, &AtomicUsize::new(0), &AtomicUsize::new(0)).unwrap(); let c1 = read.photos[0].capture_one.as_deref().expect("variant 7 has settings"); assert_eq!(c1.not_imported, vec!["LCC", "Local adjustment layers"], "Brightness is imported"); + assert_eq!(c1.sliders.get("light.brightness"), Some(&25.0), "Capture One's 12.5 doubled"); assert!(read.photos[1].capture_one.is_none(), "an untouched variant has nothing to import"); let warnings = read.warnings.join("\n"); assert!(warnings.contains("Capture One LCC: used on 1 photo(s), not imported yet"), "{warnings}"); + assert!(!warnings.contains("Capture One Brightness"), "Brightness is imported now: {warnings}"); let mut s = crate::Session::new(); let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); let photo = |name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().clone(); let a = photo("a.NEF"); assert_eq!(a.develop.light.exposure, 0.75); - assert_eq!(a.develop.light.brightness, 25.0, "Capture One's Brightness doubled onto the app's scale"); + assert_eq!(a.develop.light.brightness, 25.0, "Capture One's Brightness doubled onto the app's scale, unrounded"); assert_eq!(a.develop.orientation, lcc_geom::Orientation::from_parts(false, 1)); let g = a.develop.crop.geometry.rect; // the centre (3000, 2000) of the 6000 × 4000 stored image is the centre shown; 2000 × 3000 of 4000 × 6000 @@ -842,6 +861,98 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Brightness and the global Levels land in the photo's settings; Levels on a local adjustment layer are named + /// next to the generic local-layers line, and points the Levels tool would have to move apart are said so. + #[test] + fn brightness_and_global_levels_import_and_local_levels_are_named() { + let dir = std::env::temp_dir().join(format!("c1-levels-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("Test.cocatalogdb"); + let defaults = json!({"ZBRIGHTNESS": 0, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.000", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000", + "ZMIDTONE": "0.000;0.000;0.000;0.000", "ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.000", + "ZLEVELSTARGETHIGHLIGHT": "1.000;1.000;1.000;1.000", "ZLEVELSTARGETENABLE": 1}); + std::fs::write( + &db, + develop_catalog(vec![ + layer(1, 18, 7, defaults.clone()), + layer( + 2, + 17, + 7, + json!({"ZBRIGHTNESS": 20.5, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.750", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.250", + "ZMIDTONE": "0.000;0.000;0.000;0.500", "ZLEVELSTARGETENABLE": 1}), + ), + // a local layer with Levels of its own, and one without + layer(3, 23, 7, json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.600", "ZLEVELSTARGETENABLE": 1})), + layer(4, 23, 7, json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000", "ZLEVELSTARGETENABLE": 1})), + layer(5, 18, 8, defaults), + layer(6, 17, 8, json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.500", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.502"})), + ]), + ) + .unwrap(); + let mut s = crate::Session::new(); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let photo = |name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().clone(); + let a = photo("a.NEF"); + assert_eq!(a.develop.light.brightness, 41.0); + let m = a.develop.levels.master; + assert_eq!((m.black, m.white, m.midtone), (191.25, 63.75, 0.5), "inverted, as stored"); + assert!(a.develop.levels.red.is_default() && a.develop.levels.green.is_default() && a.develop.levels.blue.is_default()); + // black 127.5 and white 128.01: the tool keeps them at least 2 levels apart + let b = photo("b.NEF").develop.levels.master; + assert!((b.white - b.black).abs() >= lcc_develop::LEVELS_MIN_GAP, "{b:?}"); + let warnings: Vec<&str> = report["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + for line in [ + "Capture One Levels (local adjustments): used on 1 photo(s), not imported yet (the photos keep the rest of their settings)", + "Capture One Local adjustment layers: used on 1 photo(s), not imported yet (the photos keep the rest of their settings)", + "Capture One Levels: black and white points closer than 2 levels on 1 photo(s); they were moved apart", + ] { + assert!(warnings.contains(&line), "{line}: {warnings:?}"); + } + assert!(!warnings.iter().any(|w| w.starts_with("Capture One Brightness")), "{warnings:?}"); + let unmapped = + |id: &str| report["unmapped"].get(id).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect::>()); + assert_eq!(unmapped("7"), Some(vec!["Levels (local adjustments)", "Local adjustment layers"])); + assert_eq!(unmapped("8"), None, "the second variant's Levels are all imported"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Capture One can save Brightness and Levels as the camera's defaults: a variant that keeps them has + /// them imported, even with no adjustment layer of its own; a neutral default alone imports nothing. + #[test] + fn a_default_layer_with_brightness_and_levels_is_imported_without_edits() { + let dir = std::env::temp_dir().join(format!("c1-defaults-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("Test.cocatalogdb"); + let neutral = json!({"ZBRIGHTNESS": 0, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.000", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000"}); + let saved = json!({"ZBRIGHTNESS": 10, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.100", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.800"}); + std::fs::write( + &db, + develop_catalog(vec![ + // variant 7: a saved default and no layer of the user's; variant 8: a neutral default, nothing else + layer(1, 18, 7, saved), + layer(2, 18, 8, neutral), + ]), + ) + .unwrap(); + let read = read_with_progress(&db, &AtomicBool::new(false), &AtomicUsize::new(0), &AtomicUsize::new(0)).unwrap(); + assert!(read.photos[0].capture_one.is_some(), "the saved default is imported"); + assert!(read.photos[1].capture_one.is_none(), "a neutral default has nothing to import"); + let mut s = crate::Session::new(); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let photo = |name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().clone(); + let a = photo("a.NEF"); + assert_eq!(a.develop.light.brightness, 20.0); + assert_eq!((a.develop.levels.master.black, a.develop.levels.master.white), (25.5, 204.0)); + let b = photo("b.NEF"); + assert_eq!(b.develop.light.brightness, 0.0); + assert!(b.develop.levels.master.is_default()); + assert!(report["unmapped"].get("7").is_none() && report["unmapped"].get("8").is_none()); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn a_format_named_in_place_of_a_camera_is_no_camera() { let row = |make: &str, model: &str, format: &str| -> Row { @@ -1258,5 +1369,7 @@ mod tests { ] { assert!(warnings.iter().any(|w| w.starts_with(line)), "{line}: {warnings:?}"); } + // Brightness and Levels are imported now: the shot's list of what is not imported lost two lines + assert!(!warnings.iter().any(|w| w.starts_with("Capture One Brightness") || w.starts_with("Capture One Levels")), "{warnings:?}"); } } diff --git a/crates/engine/src/capture_one_develop.rs b/crates/engine/src/capture_one_develop.rs index 240a9cce83..baf700da0a 100644 --- a/crates/engine/src/capture_one_develop.rs +++ b/crates/engine/src/capture_one_develop.rs @@ -3,14 +3,18 @@ //! Capture One keeps a variant's develop settings in `ZVARIANTLAYER`, one row per layer, told apart by the //! Core Data entity in `Z_ENT` (named in `ZENTITIES`): the *adjustment* layer holds what the user set (a column //! the user never touched is NULL), *style* layers what applied styles set, and the *default* layer the camera's -//! defaults (every column filled). A setting counts as the variant's when the adjustment layer (else a style) -//! sets it to something other than the default. +//! defaults (every column filled). Brightness and the Levels are the variant's *effective* value: the adjustment +//! layer's, else a style's, else the default layer's (Capture One can save them as the camera's defaults), imported +//! when it differs from neutral by more than a tolerance (float noise left by a reset isn't an edit). The other +//! settings count as the variant's when the adjustment layer (else a style) sets them to something other than the +//! default. //! //! Imported so far: exposure, contrast, brightness, saturation, High Dynamic Range (highlight, shadow, white and -//! black recovery), clarity and structure, levels (per channel, input and target), the curves (RGB, red, green, -//! blue), the orientation and straighten angle, the crop and its aspect, flips and white balance. Every other setting -//! a variant uses, and any of those whose stored value can't be read, is named in the import report as not imported. The ICC profile -//! choice is left out on purpose: photos get the app's standard camera colour. +//! black recovery), clarity and structure, levels (per channel, input and output), the curves (RGB, red, green, +//! blue), the orientation and straighten angle, the crop and its aspect, flips and white balance. Every other +//! setting a variant uses, and any of those whose stored value can't be read, is named in the import report as not +//! imported. Local adjustment layers are not imported. The ICC profile choice is left out on purpose: photos get +//! the app's standard camera colour. //! //! How Capture One writes the values (observed in catalogs written by Capture One 16.x, own design; no Capture One //! code or documentation was used): @@ -21,18 +25,21 @@ //! - `ZFLIP` 0 none, 1 horizontal, 2 vertical. //! - `ZWHITEBALANCE` `r;g;b`: the gains on the camera's raw channels (green 1). //! - `ZEXPOSURE` EV. -//! - `ZCONTRAST`, `ZBRIGHTNESS`, `ZSATURATION` −50..50 (the app's sliders run −100..100: doubled). +//! - `ZCONTRAST`, `ZBRIGHTNESS`, `ZSATURATION` −50..50 (the app's sliders run −100..100: doubled; fractions are +//! common in Brightness). //! - `ZHIGHLIGHTRECOVERY`, `ZSHADOWRECOVERY`, `ZWHITERECOVERY`, `ZBLACKRECOVERY`: recovery amounts (positive pulls //! highlights and whites down, lifts shadows and blacks), on the app's −100..100 scale. //! - `ZCLARITY`, `ZCLARITYSTRUCTURE` −100..100 (structure is the app's Texture); `ZCLARITYMETHOD` has no equivalent. //! - `ZGRADATIONCURVE[RED|GREEN|BLUE]` `x,y;x,y;…`: curve points, 0..1 (0..255 accepted); `…Y` (the luma curve) has //! no equivalent. -//! - `ZLEVELSSHADOW`, `ZLEVELSHIGHLIGHT`, `ZLEVELSTARGETSHADOW`, `ZLEVELSTARGETHIGHLIGHT`, `ZMIDTONE`: one value for -//! all channels or four (`rgb;r;g;b`), 0..1 (0..255 accepted); the midtone is where its marker sits between the -//! black and white points (0.5 neutral). +//! - Levels, one text per column with four slots `red;green;blue;master`: `ZLEVELSSHADOW` and `ZLEVELSHIGHLIGHT` +//! (the input black and white points) and `ZLEVELSTARGETSHADOW` and `ZLEVELSTARGETHIGHLIGHT` (the output levels), +//! all 0..1 of the 0..255 scale, and `ZMIDTONE`, the signed midtone (−1..1, 0 neutral, as the tool shows it). The +//! values are stored to three decimals, and Capture One itself renders a reopened catalog from them, so they are +//! read exactly, not snapped to whole levels. A black point above the white point is stored as it is (the channel +//! is inverted); nothing is swapped. Output levels count only while `ZLEVELSTARGETENABLE` isn't 0. //! -//! The tool formats below the exposure line follow Capture One's own sidecar (`.cos`) keys of the same names; values -//! that don't read as described are reported, never guessed. +//! Values that don't read as described are reported, never guessed. use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::atomic::AtomicBool; @@ -83,6 +90,13 @@ pub struct CaptureOneDevelop { /// Levels by the app's channel name: black, midtone (−1..1), white, output black, output white (0..255). #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub levels: BTreeMap, + /// Whether an imported channel has its black and white points closer together than the Levels tool allows + /// (it moves them apart on import). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub levels_too_close: bool, + /// Whether a Levels column holds something other than four numbers: the variant's Levels are skipped. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub levels_unreadable: bool, /// The settings the variant uses that this import doesn't bring across (names as Capture One shows them). #[serde(skip_serializing_if = "Vec::is_empty")] pub not_imported: Vec, @@ -160,7 +174,7 @@ const TOOLS: &[(&str, &[&str])] = &[ ]; /// Columns this import reads for itself. -const IMPORTED: &[&str] = &["ZEXPOSURE", "ZROTATION", "ZFLIP", "ZCROP", "ZCROPASPECTRATIONAME", "ZWHITEBALANCE"]; +const IMPORTED: &[&str] = &["ZEXPOSURE", "ZROTATION", "ZFLIP", "ZCROP", "ZCROPASPECTRATIONAME", "ZWHITEBALANCE", "ZLEVELSTARGETENABLE"]; /// Sliders read one to one: column, the app's group and name, factor onto the app's scale. const SLIDERS: &[(&str, &str, &str, f64)] = &[ @@ -175,13 +189,35 @@ const SLIDERS: &[(&str, &str, &str, f64)] = &[ ("ZCLARITYSTRUCTURE", "effects", "texture", 1.0), ]; +/// The sliders of [`SLIDERS`] read as the variant's effective value (the adjustment layer's, else a style's, else the +/// camera default's), with float noise counting as neutral. Brightness is the one whose scale was measured against +/// Capture One's own exports (the app's slider has the same effect on twice the range, to 0.2 of an 8-bit level). +const EFFECTIVE_SLIDERS: &[&str] = &["ZBRIGHTNESS"]; + +/// A slider this close to 0 (in Capture One's units, where the sliders' step is 1) is none, for the same reason. +const SLIDER_NEUTRAL: f64 = 1e-3; + +/// A Levels value within this of neutral (in Capture One's 0..1 units, finer than the three decimals it stores) is +/// neutral. +const LEVELS_NEUTRAL: f64 = 1e-4; + +/// The columns of the default layer that are always kept: Brightness and Levels apply from the camera's defaults too. +const TONE_DEFAULTS: &[&str] = + &["ZBRIGHTNESS", "ZLEVELSSHADOW", "ZLEVELSHIGHLIGHT", "ZMIDTONE", "ZLEVELSTARGETSHADOW", "ZLEVELSTARGETHIGHLIGHT", "ZLEVELSTARGETENABLE"]; + /// Curve columns and the app's channel they become. const CURVES: &[(&str, &str)] = &[("ZGRADATIONCURVE", "master"), ("ZGRADATIONCURVERED", "red"), ("ZGRADATIONCURVEGREEN", "green"), ("ZGRADATIONCURVEBLUE", "blue")]; -/// Levels columns, in the order [`levels_of`] reads them. +/// Levels columns, in the order [`levels_of`] reads them: black, midtone, white, output black, output white. const LEVELS: [&str; 5] = ["ZLEVELSSHADOW", "ZMIDTONE", "ZLEVELSHIGHLIGHT", "ZLEVELSTARGETSHADOW", "ZLEVELSTARGETHIGHLIGHT"]; +/// The value of each [`LEVELS`] column that changes nothing, in Capture One's units (0..1; the midtone signed). +const LEVELS_AT_REST: [f64; 5] = [0.0, 0.0, 1.0, 0.0, 1.0]; + +/// The app's channel of each slot of a Levels value, in the order Capture One stores them. +const LEVELS_SLOTS: [&str; 4] = ["red", "green", "blue", "master"]; + /// A column's tool in the report, or `None` for a column that is never reported. A longer prefix wins /// (`ZLENSLCC…` is LCC, other `ZLENS…` columns lens correction). fn tool_of(column: &str) -> Option<&'static str> { @@ -234,6 +270,8 @@ pub(crate) struct Layers { styles: Vec<(i64, Row)>, default: Row, local: usize, + /// How many of the local adjustment layers have Levels set to something other than neutral. + local_levels: usize, } impl Layers { @@ -254,6 +292,12 @@ impl Layers { fn number(&self, column: &str) -> Option { self.changed(column).and_then(Value::as_f64).filter(|v| v.is_finite()) } + + /// What applies to the variant: the adjustment layer's value, else a style's, else the default layer's (Capture + /// One can save settings as the camera's defaults, so this isn't necessarily neutral). + fn effective(&self, column: &str) -> Option<&Value> { + self.own(column).or_else(|| self.default(column)) + } } /// The layers of every variant in `ZVARIANTLAYER`, by variant key. The table is streamed twice so only what is @@ -282,27 +326,54 @@ pub(crate) fn read_layers(reader: &Reader, entities: &HashMap, canc } else if local.contains(&ent) && row.get("ZENABLED").and_then(Value::as_i64) != Some(0) { let layers = out.entry(variant).or_default(); layers.local = layers.local.saturating_add(1); + if uses_levels(&row) { + layers.local_levels = layers.local_levels.saturating_add(1); + } } Ok(()) })?; for layers in out.values_mut() { layers.styles.sort_by_key(|(index, _)| *index); } - // the default layer: its rotation always (the camera's orientation), the rest where the variant sets something + // the default layer: its rotation always (the camera's orientation), the tone columns that apply from the camera's + // defaults (see [`TONE_DEFAULTS`]), the rest where the variant sets something reader.each_row("ZVARIANTLAYER", false, false, cancel, |row, _| { let (Some(ent), Some(variant)) = (key(&row, "Z_ENT"), key(&row, "ZVARIANT")) else { return Ok(()) }; if !default.contains(&ent) { return Ok(()); } - // (a variant with no adjustment or style layer has nothing to import) - let Some(layers) = out.get_mut(&variant) else { return Ok(()) }; + // (a variant with no adjustment or style layer has nothing to import, unless its camera default sets + // Brightness or Levels: Capture One can save those as defaults) + if !out.contains_key(&variant) && !(variant > 0 && default_applies(&row)) { + return Ok(()); + } + let layers = out.entry(variant).or_default(); let used: HashSet = layers.adjustment.keys().chain(layers.styles.iter().flat_map(|(_, s)| s.keys())).cloned().collect(); - layers.default = row.into_iter().filter(|(k, v)| !v.is_null() && (k == "ZROTATION" || used.contains(k))).collect(); + layers.default = + row.into_iter().filter(|(k, v)| !v.is_null() && (k == "ZROTATION" || used.contains(k) || TONE_DEFAULTS.contains(&k.as_str()))).collect(); Ok(()) })?; Ok(out) } +/// Whether a slider value is a setting: finite and not under [`SLIDER_NEUTRAL`] from 0. +fn slider_is_set(v: f64) -> bool { + v.is_finite() && v.abs() >= SLIDER_NEUTRAL +} + +/// Whether a camera default layer sets a slider or Levels that apply to every photo that keeps them. +fn default_applies(row: &Row) -> bool { + let number = |column: &str| row.get(column).and_then(number_of); + EFFECTIVE_SLIDERS.iter().any(|column| number(column).is_some_and(slider_is_set)) || uses_levels(row) +} + +/// Whether a layer row has any Levels column set to something other than neutral (read as [`slots_of`] reads it). +fn uses_levels(row: &Row) -> bool { + LEVELS.iter().zip(LEVELS_AT_REST).any(|(column, rest)| { + row.get(*column).and_then(Value::as_str).and_then(numbers).is_some_and(|n| n.iter().any(|v| (v - rest).abs() > LEVELS_NEUTRAL)) + }) +} + /// A crop rectangle that is a crop: finite, positive size. fn crop_of(v: &Value) -> Option<[f64; 4]> { let n = numbers(v.as_str()?)?; @@ -367,50 +438,36 @@ fn curve_of(v: &Value) -> Option> { Some(if points.iter().all(|p| (p[0] - p[1]).abs() < 1e-9) { Vec::new() } else { points }) } -/// One levels value: the same for every channel, or four (`rgb;r;g;b`). -fn channels_of(v: &Value) -> Option<[f64; 4]> { - let n = match v { - Value::String(s) => numbers(s)?, - _ => vec![number_of(v)?], - }; - match n.as_slice() { - [a] => Some([*a; 4]), - [a, b, c, d] => Some([*a, *b, *c, *d]), - _ => None, - } +/// A Levels column's four slots (`red;green;blue;master`), each within `lo..=hi`; `None` when the value isn't four such +/// numbers (a single number, another count, text, NaN, out of range). +fn slots_of(v: &Value, lo: f64, hi: f64) -> Option<[f64; 4]> { + let n = <[f64; 4]>::try_from(numbers(v.as_str()?)?).ok()?; + n.iter().all(|x| (lo..=hi).contains(x)).then_some(n) } -/// The variant's levels by the app's channel; `None` when a set value can't be read. Points given as fractions -/// (all within 0..1) are scaled to 0..255. +/// The variant's Levels by the app's channel, from the effective value of each column ([`Layers::effective`]; a +/// column no layer sets is neutral): `red`, `green`, `blue` and `master`, each as black, midtone, white, output black +/// and output white on the app's scale (0..255, the midtone signed), for the channels that aren't neutral. Output +/// levels count only while `ZLEVELSTARGETENABLE` isn't 0. `None` when a Levels column holds something that isn't four +/// numbers in range (0..1, the midtone −1..1): reported, never guessed. fn levels_of(layers: &Layers) -> Option> { - let mut out = BTreeMap::new(); - if LEVELS.iter().all(|c| layers.changed(c).is_none()) { - return Some(out); - } - // (a column the variant leaves alone is the default layer's, else neutral) - let neutral = [0.0, 0.5, 1.0, 0.0, 1.0]; - let mut v = [[0.0; 4]; 5]; + let outputs = layers.effective("ZLEVELSTARGETENABLE").and_then(Value::as_f64) != Some(0.0); + let mut columns = [[0.0; 4]; 5]; for (i, column) in LEVELS.iter().enumerate() { - let raw = match layers.own(column).or_else(|| layers.default(column)) { - Some(value) => channels_of(value)?, - None => [neutral[i]; 4], - }; - v[i] = if i == 1 { - // the midtone marker: strictly between the points - raw.iter().all(|m| *m > 0.0 && *m < 1.0).then_some(raw)? - } else if raw.iter().all(|x| (0.0..=1.0).contains(x)) { - raw.map(|x| x * 255.0) - } else if raw.iter().all(|x| (0.0..=255.0).contains(x)) { - raw - } else { - return None; + columns[i] = match layers.effective(column) { + Some(v) => slots_of(v, if i == 1 { -1.0 } else { 0.0 }, 1.0)?, + None => [LEVELS_AT_REST[i]; 4], }; } - for (c, name) in ["master", "red", "green", "blue"].iter().enumerate() { - let mut l = lcc_develop::ChannelLevels { black: v[0][c], midtone: 0.0, white: v[2][c], out_black: v[3][c], out_white: v[4][c] }.sanitized(); - l.set_midtone_position(l.black + (l.white - l.black) * v[1][c]); - if !l.is_default() { - out.insert((*name).to_string(), [l.black, l.midtone, l.white, l.out_black, l.out_white]); + let mut out = BTreeMap::new(); + for (slot, name) in LEVELS_SLOTS.iter().enumerate() { + let mut v: [f64; 5] = std::array::from_fn(|i| columns[i][slot]); + if !outputs { + (v[3], v[4]) = (LEVELS_AT_REST[3], LEVELS_AT_REST[4]); + } + if v.iter().zip(LEVELS_AT_REST).any(|(x, rest)| (x - rest).abs() > LEVELS_NEUTRAL) { + // 0..1 of the 0..255 scale (the midtone is the tool's own signed value) + out.insert((*name).to_string(), [v[0] * 255.0, v[1], v[2] * 255.0, v[3] * 255.0, v[4] * 255.0]); } } Some(out) @@ -421,6 +478,8 @@ pub(crate) fn develop_of(layers: &Layers, size: [f64; 2], camera: (&str, &str)) let mut d = CaptureOneDevelop { size, ..Default::default() }; let mut not_imported: BTreeMap<&'static str, ()> = BTreeMap::new(); d.exposure = layers.number("ZEXPOSURE"); + // Brightness and the Levels are the effective values, not the change from the default layer: Capture One can save + // them as the camera's defaults d.camera_rotation = layers.default("ZROTATION").and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0); d.rotation = layers.own("ZROTATION").and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e6).unwrap_or(d.camera_rotation); d.flip = layers.changed("ZFLIP").and_then(Value::as_i64).filter(|f| *f != 0); @@ -449,7 +508,14 @@ pub(crate) fn develop_of(layers: &Layers, size: [f64; 2], camera: (&str, &str)) // the columns brought across: never reported let mut handled: HashSet<&str> = HashSet::new(); for (column, group, name, factor) in SLIDERS { - if let Some(v) = layers.changed(column).and_then(number_of) { + if EFFECTIVE_SLIDERS.contains(column) { + if let Some(v) = layers.effective(column).and_then(number_of) { + if slider_is_set(v) { + d.sliders.insert(format!("{group}.{name}"), (v * factor).clamp(-100.0, 100.0)); + } + handled.insert(column); + } + } else if let Some(v) = layers.changed(column).and_then(number_of) { d.sliders.insert(format!("{group}.{name}"), (v * factor).clamp(-100.0, 100.0)); handled.insert(column); } @@ -462,10 +528,14 @@ pub(crate) fn develop_of(layers: &Layers, size: [f64; 2], camera: (&str, &str)) handled.insert(column); } } - if let Some(levels) = levels_of(layers) { - d.levels = levels; - handled.extend(LEVELS); + // the Levels columns have lines of their own in the report (values that can't be read, points too close, local + // layers), never a tool's + match levels_of(layers) { + Some(levels) => d.levels = levels, + None => d.levels_unreadable = true, } + handled.extend(LEVELS); + d.levels_too_close = d.levels.values().any(|[black, _, white, ..]| (white - black).abs() < lcc_develop::LEVELS_MIN_GAP); let columns: HashSet<&String> = layers.adjustment.keys().chain(layers.styles.iter().flat_map(|(_, s)| s.keys())).collect(); for column in columns { if let Some(tool) = tool_of(column) @@ -478,6 +548,9 @@ pub(crate) fn develop_of(layers: &Layers, size: [f64; 2], camera: (&str, &str)) if layers.local > 0 { not_imported.insert("Local adjustment layers", ()); } + if layers.local_levels > 0 { + not_imported.insert("Levels (local adjustments)", ()); + } d.not_imported = not_imported.into_keys().map(str::to_string).collect(); d } diff --git a/crates/engine/src/capture_one_develop_tests.rs b/crates/engine/src/capture_one_develop_tests.rs index 1e776d2c34..06da0252d8 100644 --- a/crates/engine/src/capture_one_develop_tests.rs +++ b/crates/engine/src/capture_one_develop_tests.rs @@ -262,20 +262,22 @@ fn curves_become_point_curves() { assert!(lcc_develop::ToneCurve::point_curve_is_identity(&s.curve.blue), "a straight line changes nothing"); } +/// Capture One writes four slots, `red;green;blue;master` (the master edit of a catalog is `0.000;0.000;0.000;0.078`), +/// and the midtone as the tool's own signed value (0 neutral; the default layer holds `0.000;0.000;0.000;0.000`). #[test] -fn levels_per_channel() { +fn levels_per_channel_in_the_stored_slot_order() { let l = layers( - json!({"ZLEVELSSHADOW": "0.1;0;0.2;0", "ZLEVELSHIGHLIGHT": "0.9", "ZMIDTONE": "0.4;0.5;0.5;0.5", "ZLEVELSTARGETHIGHLIGHT": 250}), - json!({"ZLEVELSSHADOW": "0;0;0;0", "ZLEVELSHIGHLIGHT": "1;1;1;1", "ZMIDTONE": "0.5;0.5;0.5;0.5", "ZLEVELSTARGETSHADOW": "0", "ZLEVELSTARGETHIGHLIGHT": 255}), + json!({"ZLEVELSSHADOW": "0.1;0;0.2;0", "ZLEVELSHIGHLIGHT": "1;0.9;1;0.8", "ZMIDTONE": "0;0;0;0.4", "ZLEVELSTARGETHIGHLIGHT": "1;1;1;0.98"}), + levels_neutral(), ); let d = develop_of(&l, [6000.0, 4000.0], ("", "")); - assert!(d.not_imported.is_empty(), "{:?}", d.not_imported); + assert!(d.not_imported.is_empty() && !d.levels_unreadable && !d.levels_too_close, "{d:?}"); let (s, _) = applied(&d); + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + assert!(near(s.levels.red.black, 25.5) && near(s.levels.blue.black, 51.0) && s.levels.green.black == 0.0); + assert!(near(s.levels.green.white, 229.5) && s.levels.red.white == 255.0); let m = s.levels.master; - assert!((m.black - 25.5).abs() < 1e-6 && (m.white - 229.5).abs() < 1e-6 && (m.out_white - 250.0).abs() < 1e-6, "{m:?}"); - assert!(m.midtone > 0.0, "a marker nearer black brightens the midtones"); - assert!((s.levels.green.black - 51.0).abs() < 1e-6); - assert_eq!(s.levels.red.black, 0.0); + assert!(m.black == 0.0 && near(m.white, 204.0) && m.midtone == 0.4 && near(m.out_white, 249.9), "{m:?}"); assert_eq!(s.levels.red.midtone, 0.0); } @@ -290,13 +292,8 @@ fn unreadable_tool_values_are_reported() { ("ZGRADATIONCURVE", json!("nan,0;1,1"), "Curve"), ("ZGRADATIONCURVE", json!(format!("0,0;{}1,1", "0.5,0.5;".repeat(400))), "Curve"), ("ZGRADATIONCURVE", json!(12), "Curve"), - ("ZLEVELSSHADOW", json!("0.1;0.2"), "Levels"), - ("ZLEVELSSHADOW", json!("300"), "Levels"), - ("ZLEVELSSHADOW", json!("-0.5"), "Levels"), - ("ZMIDTONE", json!("1.5"), "Levels"), - ("ZMIDTONE", json!("0"), "Levels"), - ("ZLEVELSHIGHLIGHT", json!({"a": 1}), "Levels"), ("ZCONTRAST", json!("lots"), "Contrast"), + ("ZBRIGHTNESS", json!("lots"), "Brightness"), ("ZCLARITY", json!("1e999"), "Clarity"), ]; for (column, value, tool) in cases { @@ -306,6 +303,33 @@ fn unreadable_tool_values_are_reported() { assert!(d.curves.is_empty() && d.levels.is_empty() && d.sliders.is_empty(), "{column} = {value}"); let _ = applied(&d); } + // Levels: four numbers in range (0..1, the midtone -1..1), or the variant's Levels have a line of their own in the + // report ("values could not be read") and nothing is set + let levels: &[(&str, Value)] = &[ + ("ZLEVELSSHADOW", json!("0.1;0.2")), + ("ZLEVELSSHADOW", json!("0.1;0.2;0.3")), + ("ZLEVELSSHADOW", json!("0;0;0;0;0")), + ("ZLEVELSSHADOW", json!("300")), + ("ZLEVELSSHADOW", json!("-0.5")), + ("ZLEVELSSHADOW", json!("0;0;0;1.5")), + ("ZLEVELSSHADOW", json!("0;0;0;-0.1")), + ("ZMIDTONE", json!("1.5")), + ("ZMIDTONE", json!("0")), + ("ZMIDTONE", json!("0;0;0;1.5")), + ("ZMIDTONE", json!("0;0;0;-1.5")), + ("ZLEVELSHIGHLIGHT", json!({"a": 1})), + ("ZLEVELSHIGHLIGHT", json!("0;0;0;nan")), + ("ZLEVELSHIGHLIGHT", json!(0.5)), + ]; + for (column, value) in levels { + let d = develop_of(&layers(json!({ *column: value }), levels_neutral()), [6000.0, 4000.0], ("", "")); + assert!(d.levels_unreadable && d.levels.is_empty() && d.not_imported.is_empty(), "{column} = {value}: {d:?}"); + let _ = applied(&d); + } + // an unreadable camera default is the same + let mut bad = levels_neutral(); + bad["ZMIDTONE"] = json!("0;0;0"); + assert!(develop_of(&layers(json!({"ZEXPOSURE": 0.5}), bad), [6000.0, 4000.0], ("", "")).levels_unreadable); // an archive with values out of range still applies within range let d = CaptureOneDevelop { sliders: [("light.contrast".to_string(), 1e9), ("nogroup".to_string(), 1.0)].into_iter().collect(), @@ -317,3 +341,280 @@ fn unreadable_tool_values_are_reported() { assert_eq!(s.light.contrast, 100.0); assert!(s.levels.master.white <= 255.0 && s.levels.master.midtone <= 1.0); } + +/// What the camera's default layer holds for Exposure, Brightness and Levels when nothing is saved there: neutral. +fn levels_neutral() -> Value { + json!({"ZEXPOSURE": 0, "ZBRIGHTNESS": 0, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.000", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000", + "ZMIDTONE": "0.000;0.000;0.000;0.000", "ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.000", + "ZLEVELSTARGETHIGHLIGHT": "1.000;1.000;1.000;1.000", "ZLEVELSTARGETENABLE": 1}) +} + +fn develop(adjustment: Value) -> CaptureOneDevelop { + develop_of(&layers(adjustment, levels_neutral()), [6000.0, 4000.0], ("", "")) +} + +fn develop_over(adjustment: Value, default: Value) -> CaptureOneDevelop { + develop_of(&layers(adjustment, default), [6000.0, 4000.0], ("", "")) +} + +fn brightness_of(d: &CaptureOneDevelop) -> Option { + d.sliders.get("light.brightness").copied() +} + +fn channel(d: &CaptureOneDevelop, name: &str) -> Option<[f64; 5]> { + d.levels.get(name).copied() +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +/// A camera default that isn't neutral (Capture One can save Brightness and Levels as defaults). +fn saved_default() -> Value { + let mut d = levels_neutral(); + d["ZBRIGHTNESS"] = json!(10); + d["ZLEVELSHIGHLIGHT"] = json!("1.000;1.000;1.000;0.800"); + d["ZMIDTONE"] = json!("0.000;0.000;0.000;0.250"); + d +} + +#[test] +fn brightness_doubles_without_rounding() { + // fractions are common in the catalog: no rounding on the way + let b = |v: Value| brightness_of(&develop(json!({"ZBRIGHTNESS": v}))); + assert_eq!(b(json!(12.345)).map(|x| (x * 1e9).round() / 1e9), Some(24.69)); + assert_eq!(b(json!(23)), Some(46.0)); + assert_eq!(b(json!(-0.25)), Some(-0.5)); + // the ends of Capture One's range are the ends of the app's; beyond them (hostile or damaged) it is held there + assert_eq!((b(json!(50)), b(json!(-50))), (Some(100.0), Some(-100.0))); + assert_eq!((b(json!(75)), b(json!(-1.0e12))), (Some(100.0), Some(-100.0))); + // it lands in the settings + let (p, _) = partial(&develop(json!({"ZBRIGHTNESS": 10})), crate::crs::Target::RawAbsolute, None); + assert_eq!(p["light"], json!({"brightness": 20.0})); +} + +#[test] +fn brightness_at_its_default_or_within_noise_of_it_is_nothing() { + for own in [json!(0), json!(0.0), json!(null)] { + let d = develop(json!({"ZBRIGHTNESS": own})); + assert!(d.sliders.is_empty() && d.is_empty() && d.not_imported.is_empty()); + } + // float noise left by a reset, as the photo's own value and as a camera default; from a thousandth on it is a setting + for tiny in [9.0e-9, -2.0e-8, 0.0005, -0.00099] { + let d = develop(json!({"ZBRIGHTNESS": tiny})); + assert!(d.sliders.is_empty() && d.is_empty(), "{tiny}"); + let kept = develop_over(json!({}), json!({"ZBRIGHTNESS": tiny})); + assert!(kept.sliders.is_empty() && kept.is_empty(), "{tiny} as a default"); + } + assert_eq!(brightness_of(&develop(json!({"ZBRIGHTNESS": 0.001}))), Some(0.002)); + // a value that isn't a number is reported, not guessed + let bad = develop(json!({"ZBRIGHTNESS": "not a number"})); + assert!(bad.sliders.is_empty() && bad.not_imported == ["Brightness"]); +} + +#[test] +fn the_master_slot_scales_to_the_0_to_255_scale() { + let d = develop( + json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.200", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.800", "ZMIDTONE": "0.000;0.000;0.000;0.250"}), + ); + assert!(d.not_imported.is_empty() && !d.is_empty() && !d.levels_too_close && !d.levels_unreadable); + // the colour channels are untouched, and not written + assert_eq!(d.levels.keys().collect::>(), ["master"]); + let m = channel(&d, "master").unwrap(); + assert!(near(m[0], 51.0) && near(m[1], 0.25) && near(m[2], 204.0) && near(m[3], 0.0) && near(m[4], 255.0), "{m:?}"); + let (p, _) = partial(&d, crate::crs::Target::RawAbsolute, None); + assert_eq!(p["levels"].as_object().unwrap().keys().collect::>(), ["master"]); +} + +#[test] +fn output_levels_scale_like_the_input_points() { + let d = develop(json!({"ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.100", "ZLEVELSTARGETHIGHLIGHT": "1.000;1.000;1.000;0.900"})); + let m = channel(&d, "master").unwrap(); + assert!(near(m[0], 0.0) && near(m[2], 255.0) && near(m[3], 25.5) && near(m[4], 229.5), "{m:?}"); +} + +#[test] +fn inverted_points_and_output_levels_are_kept_as_they_are() { + // black above white, and output black above output white: nothing is swapped, clamped or refused + let d = develop(json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.750", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.250", + "ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.800", "ZLEVELSTARGETHIGHLIGHT": "1.000;1.000;1.000;0.200"})); + assert!(!d.levels_too_close); + let m = channel(&d, "master").unwrap(); + assert!(near(m[0], 191.25) && near(m[2], 63.75) && near(m[3], 204.0) && near(m[4], 51.0), "{m:?}"); + // through the app's own settings too + let (s, _) = applied(&d); + assert!(s.levels.master.black > s.levels.master.white && s.levels.master.out_black > s.levels.master.out_white); +} + +#[test] +fn the_midtone_goes_across_signed_and_unchanged() { + for m in [-1.0, -0.5, -0.125, 0.0625, 0.5, 1.0] { + let d = develop(json!({"ZMIDTONE": format!("0.000;0.000;0.000;{m:.4}")})); + assert_eq!(channel(&d, "master").unwrap()[1], m, "{m}"); + } +} + +/// Inverted points, a midtone and enabled output levels in one master edit, as the Levels tool stores them: nothing is +/// dropped, swapped or rounded, in the stored slot order. +#[test] +fn inverted_points_a_midtone_and_output_levels_are_all_kept_together() { + let d = develop(json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.843", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.157", + "ZMIDTONE": "0.000;0.000;0.000;0.300", "ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.118", + "ZLEVELSTARGETHIGHLIGHT": "1.000;1.000;1.000;0.863", "ZLEVELSTARGETENABLE": 1})); + assert_eq!(d.levels.keys().collect::>(), ["master"]); + let m = channel(&d, "master").unwrap(); + assert!(near(m[0], 214.965) && near(m[1], 0.3) && near(m[2], 40.035) && near(m[3], 30.09) && near(m[4], 220.065), "{m:?}"); + let (s, _) = applied(&d); + let l = s.levels.master; + assert!(l.black > l.white && l.out_black < l.out_white && (l.midtone - 0.3).abs() < 1e-9, "{l:?}"); +} +#[test] +fn a_column_the_variant_does_not_set_keeps_the_defaults() { + // only the white point is set: black, midtone and the outputs stay neutral + let m = channel(&develop(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.500"})), "master").unwrap(); + assert!(near(m[0], 0.0) && near(m[1], 0.0) && near(m[2], 127.5) && near(m[3], 0.0) && near(m[4], 255.0), "{m:?}"); + // a column set to its default value is no change + let none = develop(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000", "ZMIDTONE": "0.0;0.0;0.0;0.0", "ZLEVELSTARGETENABLE": 1})); + assert!(none.levels.is_empty() && none.is_empty()); +} + +#[test] +fn the_adjustment_layer_wins_over_a_style_and_a_style_counts_alone() { + let mut l = layers(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.800"}), levels_neutral()); + l.styles = vec![(1, row(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.900", "ZLEVELSSHADOW": "0.000;0.000;0.000;0.100"})))]; + let m = channel(&develop_of(&l, [6000.0, 4000.0], ("", "")), "master").unwrap(); + assert!(near(m[2], 204.0) && near(m[0], 25.5), "the white point is the adjustment layer's, the black point the style's: {m:?}"); + let style_only = Layers { styles: l.styles.clone(), default: row(levels_neutral()), ..Default::default() }; + assert!(near(channel(&develop_of(&style_only, [6000.0, 4000.0], ("", "")), "master").unwrap()[2], 229.5)); +} + +#[test] +fn output_levels_count_only_while_they_are_enabled() { + let own = json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.100", "ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.500", "ZLEVELSTARGETENABLE": 0}); + let m = channel(&develop(own), "master").unwrap(); + assert!(near(m[0], 25.5) && near(m[3], 0.0) && near(m[4], 255.0), "{m:?}"); + // disabled outputs alone are no change + assert!(develop(json!({"ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.500", "ZLEVELSTARGETENABLE": 0})).is_empty()); +} + +#[test] +fn points_closer_than_the_levels_tool_allows_are_flagged() { + let gap = |black: f64, white: f64| { + develop(json!({"ZLEVELSSHADOW": format!("0;0;0;{black}"), "ZLEVELSHIGHLIGHT": format!("1;1;1;{white}")})).levels_too_close + }; + assert!(gap(0.5, 0.5), "equal points"); + assert!(gap(0.5, 0.504), "1 level apart"); + assert!(gap(0.504, 0.5), "1 level apart, inverted"); + assert!(!gap(0.5, 0.51), "2.55 levels apart"); + assert!(!gap(0.75, 0.25), "inverted but wide"); + assert!(!gap(0.0, 1.0)); + // and the Levels settings keep the distance they need + let (s, _) = applied(&develop(json!({"ZLEVELSSHADOW": "0;0;0;0.5", "ZLEVELSHIGHLIGHT": "1;1;1;0.5"}))); + assert!((s.levels.master.white - s.levels.master.black).abs() >= lcc_develop::LEVELS_MIN_GAP); +} + +#[test] +fn local_levels_are_found_by_comparing_with_neutral() { + assert!(!uses_levels(&row(json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.000", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000"})))); + assert!(!uses_levels(&row(json!({"ZLEVELSSHADOW": null, "ZMIDTONE": null}))), "NULL is not a setting"); + assert!(!uses_levels(&row(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.99995"}))), "within a ten-thousandth"); + assert!(!uses_levels(&row(json!({"ZEXPOSURE": 1.0, "ZBRIGHTNESS": 25}))), "other settings are not Levels"); + assert!(uses_levels(&row(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.9998"}))), "beyond a ten-thousandth"); + assert!(uses_levels(&row(json!({"ZLEVELSSHADOW": "0.1;0;0;0"}))), "a colour channel counts"); + assert!(uses_levels(&row(json!({"ZMIDTONE": "0;0;0;-0.25"})))); + assert!(uses_levels(&row(json!({"ZLEVELSTARGETHIGHLIGHT": "1;1;1;0.5"}))), "output levels count"); + // the variant is told: the specific line next to the generic one, and its global Levels still go across + let mut l = layers(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.800"}), levels_neutral()); + l.local = 2; + l.local_levels = 1; + let d = develop_of(&l, [6000.0, 4000.0], ("", "")); + assert_eq!(d.not_imported, vec!["Levels (local adjustments)", "Local adjustment layers"]); + assert!(near(channel(&d, "master").unwrap()[2], 204.0)); + // local layers without Levels: only the generic line + l.local_levels = 0; + assert_eq!(develop_of(&l, [6000.0, 4000.0], ("", "")).not_imported, vec!["Local adjustment layers"]); +} + +#[test] +fn levels_within_a_ten_thousandth_of_neutral_are_none() { + // every column a little off neutral by float noise: no channel is written, as own values and as defaults + let noise = |scale: f64| { + json!({"ZLEVELSSHADOW": format!("{0};{0};{0};{0}", 0.00005 * scale), "ZLEVELSHIGHLIGHT": format!("{0};{0};{0};{0}", 1.0 - 0.00005 * scale), + "ZMIDTONE": format!("{0};{0};{0};{0}", -0.00005 * scale), "ZLEVELSTARGETSHADOW": format!("{0};{0};{0};{0}", 0.00005 * scale), + "ZLEVELSTARGETHIGHLIGHT": format!("{0};{0};{0};{0}", 1.0 - 0.00005 * scale)}) + }; + let own = develop_over(noise(1.0), levels_neutral()); + assert!(own.levels.is_empty() && own.is_empty() && !own.levels_too_close); + assert!(develop_over(json!({"ZEXPOSURE": 0.5}), noise(1.0)).levels.is_empty()); + // beyond it (0.0002 on every value) each channel is written + assert_eq!(develop_over(noise(4.0), levels_neutral()).levels.len(), 4); + // one value beyond it is enough, and only its channel is written + let one = develop(json!({"ZMIDTONE": "0;0;0.0002;0"})); + assert_eq!(one.levels.keys().collect::>(), ["blue"]); + // the closeness check is unaffected: points 1 level apart are flagged however the other values look + assert!(develop(json!({"ZLEVELSSHADOW": "0;0;0;0.5", "ZLEVELSHIGHLIGHT": "1;1;1;0.504"})).levels_too_close); +} + +#[test] +fn a_default_that_is_not_neutral_applies_to_a_photo_that_keeps_it() { + // no adjustment layer values of its own: the default is what the photo has + let d = develop_over(json!({"ZEXPOSURE": 0.5}), saved_default()); + assert_eq!(brightness_of(&d), Some(20.0)); + let m = channel(&d, "master").unwrap(); + assert!(near(m[0], 0.0) && near(m[1], 0.25) && near(m[2], 204.0), "{m:?}"); + // a style that sets one column leaves the others to the default; so does an adjustment + let mut l = layers(json!({}), saved_default()); + l.styles = vec![(1, row(json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.100"})))]; + let m = channel(&develop_of(&l, [6000.0, 4000.0], ("", "")), "master").unwrap(); + assert!(near(m[0], 25.5) && near(m[1], 0.25) && near(m[2], 204.0), "{m:?}"); + let m = channel(&develop_over(json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.100"}), saved_default()), "master").unwrap(); + assert!(near(m[0], 25.5) && near(m[1], 0.25) && near(m[2], 204.0), "{m:?}"); +} + +#[test] +fn an_adjustment_that_resets_to_neutral_over_a_non_neutral_default_writes_nothing() { + let d = develop_over( + json!({"ZBRIGHTNESS": 0, "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000", "ZMIDTONE": "0.000;0.000;0.000;0.000"}), + saved_default(), + ); + assert!(d.sliders.is_empty() && d.levels.is_empty() && d.is_empty() && d.not_imported.is_empty()); + let (p, _) = partial(&d, crate::crs::Target::RawAbsolute, None); + assert!(p.get("light").is_none() && p.get("levels").is_none(), "{p}"); +} + +#[test] +fn the_closeness_check_runs_on_the_effective_points() { + // a default whose points are 1 level apart, kept by the photo + let mut close = levels_neutral(); + close["ZLEVELSSHADOW"] = json!("0;0;0;0.5"); + close["ZLEVELSHIGHLIGHT"] = json!("1;1;1;0.504"); + assert!(develop_over(json!({"ZEXPOSURE": 0.5}), close.clone()).levels_too_close); + // the photo moves them apart: the default's no longer counts + assert!(!develop_over(json!({"ZLEVELSHIGHLIGHT": "1;1;1;0.9"}), close.clone()).levels_too_close); + // or resets them to neutral + let reset = develop_over(json!({"ZLEVELSSHADOW": "0;0;0;0", "ZLEVELSHIGHLIGHT": "1;1;1;1"}), close); + assert!(!reset.levels_too_close && reset.levels.is_empty()); +} + +#[test] +fn a_camera_default_layer_applies_when_it_sets_something() { + assert!(default_applies(&row(json!({"ZBRIGHTNESS": "-3"})))); + assert!(default_applies(&row(json!({"ZLEVELSHIGHLIGHT": "1;1;1;0.9"})))); + assert!(!default_applies(&row(levels_neutral()))); + assert!(!default_applies(&row(json!({"ZEXPOSURE": 1e-8, "ZBRIGHTNESS": 0.0004, "ZLEVELSSHADOW": "0;0;0;0.00005"}))), "noise is not a setting"); +} + +#[test] +fn an_archive_from_before_the_levels_flags_still_reads() { + let old = json!({"exposure": 0.5, "rotation": 0.0, "camera_rotation": 0.0, "size": [6000.0, 4000.0]}); + let d: CaptureOneDevelop = serde_json::from_value(old).unwrap(); + assert!(!d.levels_too_close && !d.levels_unreadable && d.levels.is_empty()); + // and the new fields survive the archive + let new = develop(json!({"ZLEVELSHIGHLIGHT": "1;1;1;0.8", "ZLEVELSSHADOW": "0;0;0;0.5", "ZBRIGHTNESS": 5})); + let back: CaptureOneDevelop = serde_json::from_value(serde_json::to_value(&new).unwrap()).unwrap(); + assert_eq!(back, new); + let unreadable = develop(json!({"ZLEVELSSHADOW": "1;2"})); + assert!(unreadable.levels_unreadable); + let back: CaptureOneDevelop = serde_json::from_value(serde_json::to_value(&unreadable).unwrap()).unwrap(); + assert!(back.levels_unreadable); +} diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 1ad133f278..768024e704 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -359,13 +359,23 @@ Capture One 16.9.0 on Windows (catalog format 160906). only approximates Capture One's (the result window says so, with the photo count); a rendered file's white balance is not imported. - **Tone and clarity**: `ZCONTRAST`, `ZBRIGHTNESS`, `ZSATURATION` (Capture One's ±50, doubled onto the app's - sliders), High Dynamic Range (`ZHIGHLIGHTRECOVERY` / `ZWHITERECOVERY` pull Highlights / Whites down, + sliders; Brightness is often fractional and not rounded: its scale was checked against Capture One's exports to + 0.2 of an 8-bit level), High Dynamic Range (`ZHIGHLIGHTRECOVERY` / `ZWHITERECOVERY` pull Highlights / Whites down, `ZSHADOWRECOVERY` / `ZBLACKRECOVERY` lift Shadows / Blacks), `ZCLARITY` → Clarity, `ZCLARITYSTRUCTURE` → Texture (the clarity method has no equivalent and is reported). - **Curves** (`ZGRADATIONCURVE`, `…RED`, `…GREEN`, `…BLUE`, `x,y;x,y;…` in 0..1 or 0..255) → the Tone Curve's point curves; the luma curve (`…Y`) is reported. - - **Levels** (`ZLEVELSSHADOW`, `ZLEVELSHIGHLIGHT`, `ZLEVELSTARGETSHADOW`, `ZLEVELSTARGETHIGHLIGHT`, `ZMIDTONE`; one - value or `rgb;r;g;b`, 0..1 or 0..255, the midtone as the marker's place between the points) → Levels per channel. + - **Levels** (`ZLEVELSSHADOW` and `ZLEVELSHIGHLIGHT`: the black and white points; `ZLEVELSTARGETSHADOW` and + `ZLEVELSTARGETHIGHLIGHT`: the output levels; `ZMIDTONE`): each is four numbers, `red;green;blue;master`, the points + in 0..1 of the 0..255 scale and the midtone as the tool's own signed value (−1..1, 0 neutral). They become the + Levels of the red, green and blue channels and of the master. The values are stored to three decimals and + Capture One renders a reopened catalog from them, so they are read as stored, not rounded to whole levels; a + black point above the white point (an inverted channel) is kept. Output levels count while `ZLEVELSTARGETENABLE` + isn't 0. Brightness and Levels are the variant's *effective* value (the adjustment layer's, else a style's, else the + camera default layer's, since Capture One can save them as camera defaults) and are written when they differ from + neutral by more than float noise (under 0.001 for Brightness, 0.0001 for each Levels value). Levels on a local + adjustment layer are named in the result window ("Levels (local adjustments)"); the Levels tool keeps its black and + white points at least 2 levels apart, and the window says how many photos had them closer. - A value that doesn't read as described (wrong count, out of range, not a number) is reported, never guessed. - The ICC profile choice is left out on purpose: photos get the app's camera colour. From 2a9379ceb4b59a8868893fd075d249e0c01ff03e Mon Sep 17 00:00:00 2001 From: AlphaZentaurii <342205933+AlphaZentaurii@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:02:05 +0100 Subject: [PATCH 002/112] C1-DEVELOP: import exposure as the effective value Exposure now follows the rule Brightness and Levels have: what a photo has is the adjustment layer's value, else a style layer's, else the camera default layer's, and it is written when it differs from 0 by more than 0.001 EV (finer than the slider's 0.01 step, so float noise left by a reset doesn't count as an edit). Before, only a value that differed from the default layer was imported. Capture One can save an exposure as a camera default, so a photo that keeps one gets it even with no edits of its own, and an adjustment that resets the exposure to 0 over a non-zero default writes nothing. A variant with no adjustment or style layer is read when its camera default sets an exposure, as it already was for Brightness and Levels. White balance is unchanged: it stays Capture One's change from as shot. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/capture_one_catalog.rs | 14 ++--- crates/engine/src/capture_one_develop.rs | 52 +++++++++++------- .../engine/src/capture_one_develop_tests.rs | 53 +++++++++++++++++++ docs/lightroom-catalog-import.md | 4 +- 4 files changed, 98 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/capture_one_catalog.rs b/crates/engine/src/capture_one_catalog.rs index 5313c8352b..d4fd0e8bf0 100644 --- a/crates/engine/src/capture_one_catalog.rs +++ b/crates/engine/src/capture_one_catalog.rs @@ -918,16 +918,18 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } - /// Capture One can save Brightness and Levels as the camera's defaults: a variant that keeps them has + /// Capture One can save Exposure, Brightness and Levels as the camera's defaults: a variant that keeps them has /// them imported, even with no adjustment layer of its own; a neutral default alone imports nothing. #[test] - fn a_default_layer_with_brightness_and_levels_is_imported_without_edits() { + fn a_default_layer_with_exposure_brightness_and_levels_is_imported_without_edits() { let dir = std::env::temp_dir().join(format!("c1-defaults-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let db = dir.join("Test.cocatalogdb"); - let neutral = json!({"ZBRIGHTNESS": 0, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.000", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000"}); - let saved = json!({"ZBRIGHTNESS": 10, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.100", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.800"}); + let neutral = + json!({"ZEXPOSURE": 0, "ZBRIGHTNESS": 0, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.000", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000"}); + let saved = json!({"ZEXPOSURE": 0.5, "ZBRIGHTNESS": 10, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.100", + "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.800"}); std::fs::write( &db, develop_catalog(vec![ @@ -944,10 +946,10 @@ mod tests { let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); let photo = |name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().clone(); let a = photo("a.NEF"); - assert_eq!(a.develop.light.brightness, 20.0); + assert_eq!((a.develop.light.exposure, a.develop.light.brightness), (0.5, 20.0)); assert_eq!((a.develop.levels.master.black, a.develop.levels.master.white), (25.5, 204.0)); let b = photo("b.NEF"); - assert_eq!(b.develop.light.brightness, 0.0); + assert_eq!((b.develop.light.exposure, b.develop.light.brightness), (0.0, 0.0)); assert!(b.develop.levels.master.is_default()); assert!(report["unmapped"].get("7").is_none() && report["unmapped"].get("8").is_none()); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/engine/src/capture_one_develop.rs b/crates/engine/src/capture_one_develop.rs index baf700da0a..538457bd96 100644 --- a/crates/engine/src/capture_one_develop.rs +++ b/crates/engine/src/capture_one_develop.rs @@ -3,11 +3,11 @@ //! Capture One keeps a variant's develop settings in `ZVARIANTLAYER`, one row per layer, told apart by the //! Core Data entity in `Z_ENT` (named in `ZENTITIES`): the *adjustment* layer holds what the user set (a column //! the user never touched is NULL), *style* layers what applied styles set, and the *default* layer the camera's -//! defaults (every column filled). Brightness and the Levels are the variant's *effective* value: the adjustment -//! layer's, else a style's, else the default layer's (Capture One can save them as the camera's defaults), imported -//! when it differs from neutral by more than a tolerance (float noise left by a reset isn't an edit). The other -//! settings count as the variant's when the adjustment layer (else a style) sets them to something other than the -//! default. +//! defaults (every column filled). Exposure, Brightness and the Levels are the variant's *effective* value: the +//! adjustment layer's, else a style's, else the default layer's (Capture One can save them as the camera's defaults), +//! imported when it differs from neutral by more than a tolerance (float noise left by a reset isn't an edit). The +//! other settings count as the variant's when the adjustment layer (else a style) sets them to something other than +//! the default. //! //! Imported so far: exposure, contrast, brightness, saturation, High Dynamic Range (highlight, shadow, white and //! black recovery), clarity and structure, levels (per channel, input and output), the curves (RGB, red, green, @@ -194,6 +194,10 @@ const SLIDERS: &[(&str, &str, &str, f64)] = &[ /// Capture One's own exports (the app's slider has the same effect on twice the range, to 0.2 of an 8-bit level). const EFFECTIVE_SLIDERS: &[&str] = &["ZBRIGHTNESS"]; +/// An exposure this close to 0 EV (a thousandth, finer than the slider's 0.01 step) is none: Capture One's catalogs +/// hold float noise such as 1e-8 where an exposure was set back to 0. +const EXPOSURE_NEUTRAL: f64 = 1e-3; + /// A slider this close to 0 (in Capture One's units, where the sliders' step is 1) is none, for the same reason. const SLIDER_NEUTRAL: f64 = 1e-3; @@ -201,9 +205,18 @@ const SLIDER_NEUTRAL: f64 = 1e-3; /// neutral. const LEVELS_NEUTRAL: f64 = 1e-4; -/// The columns of the default layer that are always kept: Brightness and Levels apply from the camera's defaults too. -const TONE_DEFAULTS: &[&str] = - &["ZBRIGHTNESS", "ZLEVELSSHADOW", "ZLEVELSHIGHLIGHT", "ZMIDTONE", "ZLEVELSTARGETSHADOW", "ZLEVELSTARGETHIGHLIGHT", "ZLEVELSTARGETENABLE"]; +/// The columns of the default layer that are always kept: Exposure, Brightness and Levels apply from the camera's +/// defaults too. +const TONE_DEFAULTS: &[&str] = &[ + "ZEXPOSURE", + "ZBRIGHTNESS", + "ZLEVELSSHADOW", + "ZLEVELSHIGHLIGHT", + "ZMIDTONE", + "ZLEVELSTARGETSHADOW", + "ZLEVELSTARGETHIGHLIGHT", + "ZLEVELSTARGETENABLE", +]; /// Curve columns and the app's channel they become. const CURVES: &[(&str, &str)] = @@ -289,10 +302,6 @@ impl Layers { self.own(column).filter(|v| self.default(column).is_none_or(|d| !same(v, d))) } - fn number(&self, column: &str) -> Option { - self.changed(column).and_then(Value::as_f64).filter(|v| v.is_finite()) - } - /// What applies to the variant: the adjustment layer's value, else a style's, else the default layer's (Capture /// One can save settings as the camera's defaults, so this isn't necessarily neutral). fn effective(&self, column: &str) -> Option<&Value> { @@ -343,7 +352,7 @@ pub(crate) fn read_layers(reader: &Reader, entities: &HashMap, canc return Ok(()); } // (a variant with no adjustment or style layer has nothing to import, unless its camera default sets - // Brightness or Levels: Capture One can save those as defaults) + // Exposure, Brightness or Levels: Capture One can save those as defaults) if !out.contains_key(&variant) && !(variant > 0 && default_applies(&row)) { return Ok(()); } @@ -356,15 +365,22 @@ pub(crate) fn read_layers(reader: &Reader, entities: &HashMap, canc Ok(out) } +/// Whether an exposure is a setting: finite and more than [`EXPOSURE_NEUTRAL`] from 0. +fn exposure_is_set(e: f64) -> bool { + e.is_finite() && e.abs() > EXPOSURE_NEUTRAL +} + /// Whether a slider value is a setting: finite and not under [`SLIDER_NEUTRAL`] from 0. fn slider_is_set(v: f64) -> bool { v.is_finite() && v.abs() >= SLIDER_NEUTRAL } -/// Whether a camera default layer sets a slider or Levels that apply to every photo that keeps them. +/// Whether a camera default layer sets an exposure, a slider or Levels that apply to every photo that keeps them. fn default_applies(row: &Row) -> bool { let number = |column: &str| row.get(column).and_then(number_of); - EFFECTIVE_SLIDERS.iter().any(|column| number(column).is_some_and(slider_is_set)) || uses_levels(row) + number("ZEXPOSURE").is_some_and(exposure_is_set) + || EFFECTIVE_SLIDERS.iter().any(|column| number(column).is_some_and(slider_is_set)) + || uses_levels(row) } /// Whether a layer row has any Levels column set to something other than neutral (read as [`slots_of`] reads it). @@ -477,9 +493,9 @@ fn levels_of(layers: &Layers) -> Option> { pub(crate) fn develop_of(layers: &Layers, size: [f64; 2], camera: (&str, &str)) -> CaptureOneDevelop { let mut d = CaptureOneDevelop { size, ..Default::default() }; let mut not_imported: BTreeMap<&'static str, ()> = BTreeMap::new(); - d.exposure = layers.number("ZEXPOSURE"); - // Brightness and the Levels are the effective values, not the change from the default layer: Capture One can save - // them as the camera's defaults + // Exposure, the sliders and the Levels are the effective values, not the change from the default layer: Capture One + // can save them as the camera's defaults + d.exposure = layers.effective("ZEXPOSURE").and_then(number_of).filter(|e| exposure_is_set(*e)); d.camera_rotation = layers.default("ZROTATION").and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0); d.rotation = layers.own("ZROTATION").and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e6).unwrap_or(d.camera_rotation); d.flip = layers.changed("ZFLIP").and_then(Value::as_i64).filter(|f| *f != 0); diff --git a/crates/engine/src/capture_one_develop_tests.rs b/crates/engine/src/capture_one_develop_tests.rs index 06da0252d8..9e23f84e68 100644 --- a/crates/engine/src/capture_one_develop_tests.rs +++ b/crates/engine/src/capture_one_develop_tests.rs @@ -598,6 +598,7 @@ fn the_closeness_check_runs_on_the_effective_points() { #[test] fn a_camera_default_layer_applies_when_it_sets_something() { + assert!(default_applies(&row(json!({"ZEXPOSURE": 0.5})))); assert!(default_applies(&row(json!({"ZBRIGHTNESS": "-3"})))); assert!(default_applies(&row(json!({"ZLEVELSHIGHLIGHT": "1;1;1;0.9"})))); assert!(!default_applies(&row(levels_neutral()))); @@ -618,3 +619,55 @@ fn an_archive_from_before_the_levels_flags_still_reads() { let back: CaptureOneDevelop = serde_json::from_value(serde_json::to_value(&unreadable).unwrap()).unwrap(); assert!(back.levels_unreadable); } + +#[test] +fn a_default_exposure_applies_to_a_photo_that_keeps_it() { + // Capture One can save an exposure as the camera's default: a photo with no exposure of its own has it + let d = develop_over(json!({"ZBRIGHTNESS": 5}), json!({"ZEXPOSURE": 0.5, "ZBRIGHTNESS": 0})); + assert_eq!(d.exposure, Some(0.5)); + assert_eq!(partial(&d, crate::crs::Target::RawAbsolute, None).0["light"]["exposure"], json!(0.5)); + // a style supplies it where the adjustment layer doesn't + let mut l = layers(json!({}), json!({"ZEXPOSURE": 0.5})); + l.styles = vec![(1, row(json!({"ZEXPOSURE": -1.0})))]; + assert_eq!(develop_of(&l, [6000.0, 4000.0], ("", "")).exposure, Some(-1.0)); + // and the photo's own value wins over the default + assert_eq!(develop_over(json!({"ZEXPOSURE": 1.25}), json!({"ZEXPOSURE": 0.5})).exposure, Some(1.25)); + // a default alone is a variant with something to import + let alone = develop_over(json!({}), json!({"ZEXPOSURE": 0.75})); + assert!(!alone.is_empty() && alone.exposure == Some(0.75)); +} + +#[test] +fn an_exposure_reset_to_zero_over_a_non_zero_default_writes_nothing() { + let d = develop_over(json!({"ZEXPOSURE": 0}), json!({"ZEXPOSURE": 0.5})); + assert_eq!(d.exposure, None); + assert!(d.is_empty() && d.not_imported.is_empty()); + let (p, _) = partial(&d, crate::crs::Target::RawAbsolute, None); + assert!(p.get("light").is_none(), "{p}"); + assert_eq!(develop_over(json!({"ZEXPOSURE": 0.0}), json!({"ZEXPOSURE": 0})).exposure, None); +} + +#[test] +fn exposure_values_are_held_to_the_apps_range_and_unreadable_ones_are_nothing() { + let ev = |v: Value| { + partial(&develop_over(json!({"ZEXPOSURE": v}), json!({"ZEXPOSURE": 0})), crate::crs::Target::RawAbsolute, None).0["light"]["exposure"] + .as_f64() + }; + assert_eq!((ev(json!(0.125)), ev(json!(-5))), (Some(0.125), Some(-5.0))); + assert_eq!((ev(json!(1.0e9)), ev(json!(-1.0e9))), (Some(5.0), Some(-5.0))); + for bad in [json!("x"), json!("1;2"), json!(null)] { + assert_eq!(develop_over(json!({"ZEXPOSURE": bad.clone()}), json!({"ZEXPOSURE": 0})).exposure, None, "{bad}"); + } +} + +#[test] +fn an_exposure_within_a_thousandth_of_zero_is_none() { + // float noise where an exposure was set back to 0, as a default and as a value of the photo's own + for tiny in [9.0e-9, -2.0e-8, 0.0005, -0.001] { + let d = develop_over(json!({"ZEXPOSURE": tiny}), json!({"ZEXPOSURE": 0})); + assert!(d.exposure.is_none() && d.is_empty(), "{tiny}"); + assert_eq!(develop_over(json!({}), json!({"ZEXPOSURE": tiny})).exposure, None, "{tiny} as a default"); + } + assert_eq!(develop_over(json!({"ZEXPOSURE": 0.002}), json!({"ZEXPOSURE": 0})).exposure, Some(0.002)); + assert_eq!(develop_over(json!({"ZEXPOSURE": -0.01}), json!({"ZEXPOSURE": 0})).exposure, Some(-0.01)); +} diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 768024e704..cf4c6b7708 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -345,7 +345,9 @@ Capture One 16.9.0 on Windows (catalog format 160906). *style* layers what applied styles set, the *default* layer the camera's defaults. A setting is the variant's when the adjustment layer (else a style) sets it to something other than the default. Imported so far, on top of the photo's camera defaults: - - **Exposure** (`ZEXPOSURE`, EV). + - **Exposure** (`ZEXPOSURE`, EV): the variant's effective value (the adjustment layer's, else a style's, else the + camera default layer's), written when it differs from 0 by more than 0.001 EV (finer than the slider's step, so + float noise left by a reset doesn't count as an edit). - **Orientation and straighten** (`ZROTATION`): the whole turn in degrees, clockwise as shown, including the camera's own orientation (the default layer's value, which the file's orientation already shows). The quarter turns beyond the camera's become the photo's orientation, the rest (±45°) the straighten angle. From 4a84655d9c6909edb657ec22c8070a5d2e917606 Mon Sep 17 00:00:00 2001 From: AlphaZentaurii <342205933+AlphaZentaurii@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:02:05 +0100 Subject: [PATCH 003/112] C1-DEVELOP: report the unverified tone sliders as not imported yet Contrast, Saturation, Highlight, Shadow, White, Black, Clarity and Structure were imported with a factor and a sign taken from the first tone import. None of them has been checked against Capture One's own exports yet, so they are reported as "not imported yet" instead, and the photo keeps the rest of its settings. Per group: - Contrast, Shadow: the factors have not been measured. - Highlight: the factor has not been measured, and the sign it was given contradicts the distribution of the stored values. - Saturation: Capture One stores -100..+100, so the factor of 2 for a -50..+50 range does not fit; the factor has not been measured either. - White and Black: they act locally in Capture One, while the app's Whites and Blacks are per-pixel, so no factor can reproduce them. - Clarity and Structure: out of scope for this import. Brightness stays imported; its scale was measured. The sliders whose factors and signs are calibrated against exports return in a later commit. The tone-slider test now asserts Brightness and the reported sliders, the manual-shot fixture test expects the High Dynamic Range line, and the import notes name the sliders that are reported. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/capture_one_catalog.rs | 1 + crates/engine/src/capture_one_develop.rs | 49 ++++++------------- .../engine/src/capture_one_develop_tests.rs | 23 +++++---- docs/lightroom-catalog-import.md | 9 ++-- 4 files changed, 32 insertions(+), 50 deletions(-) diff --git a/crates/engine/src/capture_one_catalog.rs b/crates/engine/src/capture_one_catalog.rs index d4fd0e8bf0..f341baaf85 100644 --- a/crates/engine/src/capture_one_catalog.rs +++ b/crates/engine/src/capture_one_catalog.rs @@ -1365,6 +1365,7 @@ mod tests { // all of them fit the result window's eight warnings assert!(warnings.len() <= 8, "{warnings:?}"); for line in [ + "Capture One High Dynamic Range: used on 3 photo(s)", "Capture One LCC: used on 2 photo(s)", "Capture One Local adjustment layers: used on 1 photo(s)", "Capture One White Balance: approximate on 5 photo(s)", diff --git a/crates/engine/src/capture_one_develop.rs b/crates/engine/src/capture_one_develop.rs index 538457bd96..6d87ef28de 100644 --- a/crates/engine/src/capture_one_develop.rs +++ b/crates/engine/src/capture_one_develop.rs @@ -9,12 +9,12 @@ //! other settings count as the variant's when the adjustment layer (else a style) sets them to something other than //! the default. //! -//! Imported so far: exposure, contrast, brightness, saturation, High Dynamic Range (highlight, shadow, white and -//! black recovery), clarity and structure, levels (per channel, input and output), the curves (RGB, red, green, +//! Imported so far: exposure, brightness, levels (per channel, input and output), the curves (RGB, red, green, //! blue), the orientation and straighten angle, the crop and its aspect, flips and white balance. Every other //! setting a variant uses, and any of those whose stored value can't be read, is named in the import report as not -//! imported. Local adjustment layers are not imported. The ICC profile choice is left out on purpose: photos get -//! the app's standard camera colour. +//! imported (Contrast, Saturation, High Dynamic Range and Clarity come back once their scales are measured against +//! Capture One's own exports). Local adjustment layers are not imported. The ICC profile choice is left out on +//! purpose: photos get the app's standard camera colour. //! //! How Capture One writes the values (observed in catalogs written by Capture One 16.x, own design; no Capture One //! code or documentation was used): @@ -25,11 +25,7 @@ //! - `ZFLIP` 0 none, 1 horizontal, 2 vertical. //! - `ZWHITEBALANCE` `r;g;b`: the gains on the camera's raw channels (green 1). //! - `ZEXPOSURE` EV. -//! - `ZCONTRAST`, `ZBRIGHTNESS`, `ZSATURATION` −50..50 (the app's sliders run −100..100: doubled; fractions are -//! common in Brightness). -//! - `ZHIGHLIGHTRECOVERY`, `ZSHADOWRECOVERY`, `ZWHITERECOVERY`, `ZBLACKRECOVERY`: recovery amounts (positive pulls -//! highlights and whites down, lifts shadows and blacks), on the app's −100..100 scale. -//! - `ZCLARITY`, `ZCLARITYSTRUCTURE` −100..100 (structure is the app's Texture); `ZCLARITYMETHOD` has no equivalent. +//! - `ZBRIGHTNESS` −50..50 (fractions are common; the app's slider runs −100..100 with the same effect: doubled). //! - `ZGRADATIONCURVE[RED|GREEN|BLUE]` `x,y;x,y;…`: curve points, 0..1 (0..255 accepted); `…Y` (the luma curve) has //! no equivalent. //! - Levels, one text per column with four slots `red;green;blue;master`: `ZLEVELSSHADOW` and `ZLEVELSHIGHLIGHT` @@ -176,23 +172,11 @@ const TOOLS: &[(&str, &[&str])] = &[ /// Columns this import reads for itself. const IMPORTED: &[&str] = &["ZEXPOSURE", "ZROTATION", "ZFLIP", "ZCROP", "ZCROPASPECTRATIONAME", "ZWHITEBALANCE", "ZLEVELSTARGETENABLE"]; -/// Sliders read one to one: column, the app's group and name, factor onto the app's scale. -const SLIDERS: &[(&str, &str, &str, f64)] = &[ - ("ZCONTRAST", "light", "contrast", 2.0), - ("ZBRIGHTNESS", "light", "brightness", 2.0), - ("ZSATURATION", "color", "saturation", 2.0), - ("ZHIGHLIGHTRECOVERY", "light", "highlights", -1.0), - ("ZSHADOWRECOVERY", "light", "shadows", 1.0), - ("ZWHITERECOVERY", "light", "whites", -1.0), - ("ZBLACKRECOVERY", "light", "blacks", 1.0), - ("ZCLARITY", "effects", "clarity", 1.0), - ("ZCLARITYSTRUCTURE", "effects", "texture", 1.0), -]; - -/// The sliders of [`SLIDERS`] read as the variant's effective value (the adjustment layer's, else a style's, else the -/// camera default's), with float noise counting as neutral. Brightness is the one whose scale was measured against -/// Capture One's own exports (the app's slider has the same effect on twice the range, to 0.2 of an 8-bit level). -const EFFECTIVE_SLIDERS: &[&str] = &["ZBRIGHTNESS"]; +/// Sliders read one to one: column, the app's group and name, factor onto the app's scale. Only Brightness is here: +/// its scale was measured against Capture One's own exports (the app's slider has the same effect on twice the +/// range, to 0.2 of an 8-bit level). Contrast, Saturation, the High Dynamic Range sliders, Clarity and Structure +/// stay in the report until their scales (and signs) are measured the same way; no guessed factor is applied. +const SLIDERS: &[(&str, &str, &str, f64)] = &[("ZBRIGHTNESS", "light", "brightness", 2.0)]; /// An exposure this close to 0 EV (a thousandth, finer than the slider's 0.01 step) is none: Capture One's catalogs /// hold float noise such as 1e-8 where an exposure was set back to 0. @@ -379,7 +363,7 @@ fn slider_is_set(v: f64) -> bool { fn default_applies(row: &Row) -> bool { let number = |column: &str| row.get(column).and_then(number_of); number("ZEXPOSURE").is_some_and(exposure_is_set) - || EFFECTIVE_SLIDERS.iter().any(|column| number(column).is_some_and(slider_is_set)) + || SLIDERS.iter().any(|(column, ..)| number(column).is_some_and(slider_is_set)) || uses_levels(row) } @@ -524,15 +508,10 @@ pub(crate) fn develop_of(layers: &Layers, size: [f64; 2], camera: (&str, &str)) // the columns brought across: never reported let mut handled: HashSet<&str> = HashSet::new(); for (column, group, name, factor) in SLIDERS { - if EFFECTIVE_SLIDERS.contains(column) { - if let Some(v) = layers.effective(column).and_then(number_of) { - if slider_is_set(v) { - d.sliders.insert(format!("{group}.{name}"), (v * factor).clamp(-100.0, 100.0)); - } - handled.insert(column); + if let Some(v) = layers.effective(column).and_then(number_of) { + if slider_is_set(v) { + d.sliders.insert(format!("{group}.{name}"), (v * factor).clamp(-100.0, 100.0)); } - } else if let Some(v) = layers.changed(column).and_then(number_of) { - d.sliders.insert(format!("{group}.{name}"), (v * factor).clamp(-100.0, 100.0)); handled.insert(column); } } diff --git a/crates/engine/src/capture_one_develop_tests.rs b/crates/engine/src/capture_one_develop_tests.rs index 9e23f84e68..55faacf063 100644 --- a/crates/engine/src/capture_one_develop_tests.rs +++ b/crates/engine/src/capture_one_develop_tests.rs @@ -226,23 +226,26 @@ fn applied(d: &CaptureOneDevelop) -> (lcc_develop::DevelopSettings, Vec) (lcc_develop::apply_partial(&lcc_develop::DevelopSettings::default(), &p, 1.0), skipped) } +/// Only Brightness has a measured scale; the other tone sliders are reported until theirs is (no guessed factor). #[test] -fn tone_sliders_and_clarity_come_across_on_the_apps_scale() { +fn brightness_comes_across_on_the_apps_scale_and_the_unmeasured_sliders_are_reported() { let l = layers( - json!({"ZCONTRAST": 20, "ZBRIGHTNESS": "-10", "ZSATURATION": 15, "ZHIGHLIGHTRECOVERY": 60, "ZSHADOWRECOVERY": 40, - "ZCLARITY": 30, "ZCLARITYSTRUCTURE": -25, "ZCLARITYMETHOD": 2}), + json!({"ZCONTRAST": 20, "ZBRIGHTNESS": "-10", "ZSATURATION": 15, "ZHIGHLIGHTRECOVERY": -60, "ZSHADOWRECOVERY": 40, + "ZWHITERECOVERY": -10, "ZBLACKRECOVERY": 10, "ZCLARITY": 30, "ZCLARITYSTRUCTURE": -25, "ZCLARITYMETHOD": 2}), json!({"ZCONTRAST": 0, "ZBRIGHTNESS": 0, "ZSATURATION": 0, "ZHIGHLIGHTRECOVERY": 0, "ZSHADOWRECOVERY": 0, - "ZCLARITY": 0, "ZCLARITYSTRUCTURE": 0, "ZCLARITYMETHOD": 1}), + "ZWHITERECOVERY": 0, "ZBLACKRECOVERY": 0, "ZCLARITY": 0, "ZCLARITYSTRUCTURE": 0, "ZCLARITYMETHOD": 1}), ); let d = develop_of(&l, [6000.0, 4000.0], ("", "")); - assert_eq!(d.not_imported, vec!["Clarity method"], "only the method has no equivalent"); + assert_eq!(d.not_imported, vec!["Clarity", "Clarity method", "Contrast", "High Dynamic Range", "Saturation"]); + assert_eq!(d.sliders.keys().collect::>(), ["light.brightness"]); assert!(!d.is_empty()); let (s, skipped) = applied(&d); - assert_eq!(skipped, vec!["Clarity method"]); - assert_eq!((s.light.contrast, s.light.brightness), (40.0, -20.0), "Capture One's ±50 doubled"); - assert_eq!(s.color.saturation, 30.0); - assert!(s.light.highlights < 0.0 && s.light.shadows > 0.0, "recovery pulls highlights down and lifts shadows"); - assert_eq!((s.effects.clarity, s.effects.texture), (30.0, -25.0)); + assert_eq!(skipped, d.not_imported); + assert_eq!(s.light.brightness, -20.0, "Capture One's ±50 doubled; a number written as text is read"); + // nothing else moved: the unmeasured sliders have no factor yet + let others = (s.light.contrast, s.color.saturation, s.light.highlights, s.light.shadows, s.light.whites, s.light.blacks); + assert_eq!(others, (0.0, 0.0, 0.0, 0.0, 0.0, 0.0)); + assert_eq!((s.effects.clarity, s.effects.texture), (0.0, 0.0)); } #[test] diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index cf4c6b7708..700da3e524 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -360,11 +360,10 @@ Capture One 16.9.0 on Windows (catalog format 160906). relative scale (no matrices for its camera) gets the same change through that scale, which on those cameras only approximates Capture One's (the result window says so, with the photo count); a rendered file's white balance is not imported. - - **Tone and clarity**: `ZCONTRAST`, `ZBRIGHTNESS`, `ZSATURATION` (Capture One's ±50, doubled onto the app's - sliders; Brightness is often fractional and not rounded: its scale was checked against Capture One's exports to - 0.2 of an 8-bit level), High Dynamic Range (`ZHIGHLIGHTRECOVERY` / `ZWHITERECOVERY` pull Highlights / Whites down, - `ZSHADOWRECOVERY` / `ZBLACKRECOVERY` lift Shadows / Blacks), `ZCLARITY` → Clarity, `ZCLARITYSTRUCTURE` → Texture - (the clarity method has no equivalent and is reported). + - **Brightness** (`ZBRIGHTNESS`, −50..50, often fractional) → Brightness doubled, not rounded: the app's slider has + Capture One's effect on twice the range (checked against Capture One's exports to 0.2 of an 8-bit level). The + other tone sliders (Contrast, Saturation, the High Dynamic Range sliders, Clarity and Structure) are named in the + result window until their scales are measured the same way. - **Curves** (`ZGRADATIONCURVE`, `…RED`, `…GREEN`, `…BLUE`, `x,y;x,y;…` in 0..1 or 0..255) → the Tone Curve's point curves; the luma curve (`…Y`) is reported. - **Levels** (`ZLEVELSSHADOW` and `ZLEVELSHIGHLIGHT`: the black and white points; `ZLEVELSTARGETSHADOW` and From 2291eae7bf8de53a546559458d83d139c48c88cb Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:24:17 +1100 Subject: [PATCH 004/112] upstream #4497: MCP export's bitDepth carries no integer enum The Gemini API refuses a whole tool list with one non-string `enum`; the export tool's bitDepth now names its values in the description. Hand-ported from upstream #4497 (the files diverged), with its test that every enum in the helper tools is a list of strings. Checked: lcc-mcp test passes. Manual: none, no user-visible change Co-authored-by: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/mcp/src/tests.rs | 29 +++++++++++++++++++++++++++++ crates/mcp/src/tools.rs | 3 ++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 90a28370a4..8457992be5 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -843,3 +843,32 @@ fn a_relative_save_path_is_checked_as_the_absolute_path_that_is_written() { assert!(std::path::Path::new(path).is_absolute(), "{path}"); assert!(path.ends_with("x.png")); } + +/// Issue #4496: the Gemini API takes only string `enum`s in a tool's parameters and refuses the whole tool list +/// (400) for one integer enum, so no helper tool declares one. +#[test] +fn every_enum_in_the_helper_tools_is_a_list_of_strings() { + fn check(at: &str, v: &Value, bad: &mut Vec) { + match v { + Value::Object(m) => { + if let Some(e) = m.get("enum") + && !e.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(Value::is_string)) + { + bad.push(format!("{at}: {e}")); + } + for (k, x) in m { + check(&format!("{at}.{k}"), x, bad); + } + } + Value::Array(a) => a.iter().enumerate().for_each(|(i, x)| check(&format!("{at}[{i}]"), x, bad)), + _ => {} + } + } + let mut bad = Vec::new(); + for has_ui in [false, true] { + for t in crate::tools::helper_tools(has_ui) { + check(t["name"].as_str().unwrap_or("?"), &t["inputSchema"], &mut bad); + } + } + assert!(bad.is_empty(), "non-string enums: {bad:?}"); +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 54f36d1933..3211aaff0d 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -266,7 +266,8 @@ pub fn helper_tools(has_ui: bool) -> Vec { "metadata": {"type": "string", "enum": ["all", "allExceptCamera", "copyright", "copyrightContact", "none"]}, "removeLocation": {"type": "boolean"}, "colorSpace": {"type": "string", "enum": ["srgb", "displayP3", "adobeRgb", "proPhoto", "rec2020"], "description": "Output colour space (default sRGB; AVIF is always sRGB; lossy JPEG XL writes adobeRgb/proPhoto as rec2020). adobeRgb = Adobe RGB (1998) compatible; the embedded ICC profile is generated from the published primaries"}, - "bitDepth": {"type": "integer", "enum": [8, 10, 16, 32], "description": "Bits per channel: PNG 8|16 (default 8), TIFF 8|16|32 (default 16; 32 = linear float with a linear profile), PSD 8|16 (default 16), AVIF 8|10, JPEG XL 8|16; JPEG/WebP are 8-bit"}, + // the values in words, not an `enum`: the Gemini API refuses a tool list with a non-string enum (upstream #4496) + "bitDepth": {"type": "integer", "description": "Bits per channel (8, 10, 16 or 32): PNG 8|16 (default 8), TIFF 8|16|32 (default 16; 32 = linear float with a linear profile), PSD 8|16 (default 16), AVIF 8|10, JPEG XL 8|16; JPEG/WebP are 8-bit"}, "hdr": {"type": "boolean", "description": "HDR output for photos edited in HDR (develop.hdr): JPEG as an ISO 21496-1 gain map JPEG, AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ, 32-bit TIFF with highlights above 1; other formats and SDR edits export as usual"}, "hdrTransfer": {"type": "string", "enum": ["pq", "hlg"], "description": "Transfer curve of HDR AVIF output (default pq): pq = SMPTE ST 2084, hlg = ITU-R BT.2100 hybrid log-gamma"}, "pluginDestination": {"type": "object", "description": "Send the exported files on to a plug-in export destination: {plugin, destination, args?} (see plugin.exportDestinations)"}, From acc72a1a9a0d90c0c32ce57864b74e5068a15af1 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:26:16 +1100 Subject: [PATCH 005/112] upstream #4528: MCP export forwards its JPEG XL options jxlLossless, jxlEffort and jxlProgressive were advertised by the export tool but missing from the forwarded-key list, so they were silently dropped. Hand-ported from upstream #4528 with its test (selection and explicit-photo calls). Checked: lcc-mcp export_tool tests pass. Manual: none, no user-visible change (docs already describe the options) Co-authored-by: Mex <44814932+MMexicann@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/mcp/src/tests.rs | 23 +++++++++++++++++++++++ crates/mcp/src/tools.rs | 3 +++ 2 files changed, 26 insertions(+) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 8457992be5..e1f3ee24f0 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -213,6 +213,29 @@ fn export_tool_forwards_its_advertised_options() { let _ = std::fs::remove_dir_all(&base); } +/// JPEG XL options reach the export command in both selection and explicit-photo calls. +#[test] +fn export_tool_forwards_jpeg_xl_options() { + for (lossless, effort, progressive) in [(true, "fast", true), (false, "normal", false)] { + for id in [None, Some(17)] { + let params = json!({"path": "out.jxl", "format": "jxl", "jxlLossless": lossless, "jxlEffort": effort, "jxlProgressive": progressive}); + let mut args = params.clone(); + if let Some(id) = id { + args["id"] = json!(id); + } + let mut b = Recorder(vec![]); + let result = call_tool(&mut b, "export", &args); + assert!(!result.is_error, "{result:?}"); + let mut calls = vec![]; + if let Some(id) = id { + calls.push(("engine.execute".to_string(), json!({"command": "library.select", "params": {"ids": [id], "active": id}}))); + } + calls.push(("engine.execute".to_string(), json!({"command": "app.export", "params": params}))); + assert_eq!(b.0, calls, "{args}"); + } + } +} + /// Issue #236: `app.export {addToPhotos, photosAlbum}` through the headless backend (the MCP /// `export` tool, `lcc-cli run`): the files written go to Photos and the result says how /// it went; where Photos isn't (not macOS), it is refused before anything is written. A fake diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 3211aaff0d..bca77e87a0 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -853,6 +853,9 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult { "dontEnlarge", "ppi", "quality", + "jxlLossless", + "jxlEffort", + "jxlProgressive", "limitKb", "sharpen", "sharpenAmount", From 9f57e59e63c18082acd538fded5bbce52a05d6df Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:28:33 +1100 Subject: [PATCH 006/112] upstream #4737: headless batch exports continue past a missing original A headless batch (MCP export, cli run) stopped at the first failed photo; it now lists the failure as {photo, file, error} in `files` and keeps going. A single-photo export still fails as an error, and a per-file error is not promoted to the top-level result. Hand-ported from upstream #4737 with its test; docs/mcp.md and docs/control-protocol.md updated. Checked: lcc-mcp tests pass. Manual: docs/mcp.md, docs/control-protocol.md (developer reference) Co-authored-by: acebear17 <121527825+acebear17@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/mcp/src/headless.rs | 42 +++++++++++++++++-- docs/control-protocol.md | 2 +- docs/mcp.md | 4 +- ...1-29-mcp-batch-export-missing-originals.md | 3 ++ 4 files changed, 46 insertions(+), 5 deletions(-) create mode 100644 docs/whats-new/2026-11-29-mcp-batch-export-missing-originals.md diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 34f6bed2fb..77080416ba 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -133,6 +133,9 @@ impl Headless { lcc_engine::export::set_video_hooks(&mut items, &lcc_engine::export_video::VideoHooks { cancel, progress: Some(progress) }); row }); + // a batch goes on past a photo that fails (a missing original) and lists it in `files`; + // a single-photo export that fails is an error (upstream #4737) + let stop_on_error = total == 1; let mut hook = self.progress.take(); let mut cancelled = false; let files = run_batch( @@ -141,7 +144,7 @@ impl Headless { &Destination { dir: dir.to_string(), exact: exact.map(str::to_string) }, write, &|path| Path::new(path).exists(), - true, + stop_on_error, &mut |done, name| { cancelled = hook.as_mut().is_some_and(|h| !h(done, total, name)); !cancelled @@ -154,8 +157,9 @@ impl Headless { return Err("cancelled".into()); } lcc_engine::export::mark_exported(&mut self.session, &files); - // Single-photo exports also report path/width/height at the top level (back-compat). - let mut out = files.first().cloned().unwrap_or_else(|| json!({})); + // Single-photo exports also report path/width/height at the top level (back-compat); a + // per-file error is never promoted to the top level. + let mut out = files.first().filter(|file| file.get("error").is_none()).cloned().unwrap_or_else(|| json!({})); if let Some(photos) = after.run(&files, false) { out["applePhotos"] = photos; } @@ -396,6 +400,38 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Upstream #4737 (issue #4714): a missing original in a headless export is reported per file, and later photos still export. + #[test] + fn a_missing_original_does_not_stop_a_headless_batch_export() { + let base = std::env::temp_dir().join(format!("lc-mcp-missing-export-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (source, output) = (base.join("source"), base.join("output")); + std::fs::create_dir_all(&source).unwrap(); + + let mut h = Headless::demo(); + let mut ids = Vec::new(); + for (i, name) in ["missing.png", "before.png", "after.png"].into_iter().enumerate() { + let img = lcc_raster::Rgba8 { width: 8, height: 8, data: vec![[20 + i as u8, 3, 9, 255]; 64] }; + let png = lcc_codecs::encode_png(&lcc_codecs::EncodeImage::rgba8(&img), &lcc_codecs::EncodeMeta::default()).unwrap(); + let path = source.join(name); + std::fs::write(&path, &png).unwrap(); + let r = crate::call_tool(&mut h, "import", &json!({"paths": [path.to_string_lossy()]})); + assert!(!r.is_error, "{r:?}"); + ids.push(h.session.catalog.photos().find(|p| p.file_name == name).unwrap().id.0); + } + std::fs::remove_file(source.join("missing.png")).unwrap(); + + let r = h.call("app.export", json!({"ids": ids, "dir": output.to_string_lossy(), "longEdge": 32, "format": "png"})).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 3, "{r}"); + assert!(files[0]["error"].as_str().is_some_and(|e| e.contains("missing.png")), "{r}"); + assert!(r.get("error").is_none(), "{r}"); + assert!(output.join("before.png").is_file(), "{r}"); + assert!(output.join("after.png").is_file(), "{r}"); + + let _ = std::fs::remove_dir_all(&base); + } + /// The export file-name template takes the Rename Photos tokens. #[test] fn export_naming_tokens() { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 08dc8eb070..5fbafb8e12 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -136,7 +136,7 @@ filmstrip is visible. | `ui.dropFiles` | `{paths: [..], hover?}` | Files dragged from the file manager. `hover: true` makes every following frame report `paths` as hovered over the window (the drop card appears, `ui.widgets` lists `dropOverlay`) until another `ui.dropFiles` replaces them; `{paths: [], hover: true}` ends the hover. Without `hover` the files are dropped: the hover ends and the next frame receives them as dropped files, exactly as an OS drop arrives (photos and folders open the import review, or import at once with Settings ▸ Import ▸ Import dropped files without review). An empty path stands for a file whose path the platform doesn't tell | | `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) | | `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:`, `compare:renderFailed:`) | -| `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir`; `destinationMode: "chooseLater"` without `dir` opens the folder dialog and exports once a folder is chosen (nothing when it is cancelled; an error where there is no folder dialog) | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md` — and `quality`, the JPEG quality a `limitKb` file-size limit settled on, when a limit was set); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | +| `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir`; `destinationMode: "chooseLater"` without `dir` opens the folder dialog and exports once a folder is chosen (nothing when it is cancelled; an error where there is no folder dialog) | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md` — and `quality`, the JPEG quality a `limitKb` file-size limit settled on, when a limit was set). A headless batch continues after a failed photo and lists it as `{photo, file, error}` in `files`; a failed single-photo export is an error. With `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | | `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | | `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | | `ui.render` | `{id?, size?, path?, inline?}` | Render a photo (PNG to `path`), `{width, height}`; `inline: true` without `path` puts the PNG in the reply as base64 `png` (for a client on another machine) | diff --git a/docs/mcp.md b/docs/mcp.md index c34bd2ebf5..c8bd57eeec 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -378,7 +378,9 @@ until the export ends. EOF lets a pending export finish and preserves queued req photo, suppressing its response. Unknown/completed request ids are ignored. A photo already being processed finishes first: completed photos remain, each written with the existing atomic file writer, and there are no partial files to delete. Unrelated outputs and earlier exports -are untouched. A failed export is an `isError` tool result. Transport mutexes recover poisoning. +are untouched. In a headless batch export, a failed photo is listed as `{photo, file, error}` in +`files` and later photos continue exporting. A failed single-photo export is an `isError` tool +result. Transport mutexes recover poisoning. If a protocol write or flush fails, the CLI reports the output error and shuts down without waiting for stdin to close. Output failures are observable only when writing. An active direct diff --git a/docs/whats-new/2026-11-29-mcp-batch-export-missing-originals.md b/docs/whats-new/2026-11-29-mcp-batch-export-missing-originals.md new file mode 100644 index 0000000000..395a08351c --- /dev/null +++ b/docs/whats-new/2026-11-29-mcp-batch-export-missing-originals.md @@ -0,0 +1,3 @@ +### MCP batch exports go on past a missing original + +- A headless export of several photos (the MCP `export` tool, ` run`) no longer stops at a photo whose original is missing: it is listed with its error in `files` and the other photos are still written. A single-photo export that fails is still an error. From cb32ba309ce620369c2d2b814ffb26a2a4322920 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:32:44 +1100 Subject: [PATCH 007/112] upstream #4484: the contact sheet's Paper box shows A4 / Letter Hand-ported (the dialog lives in panels/dialogs.rs here): the combo's selected text is the label (A4, translated Letter), not the stored id "a4"/"letter". Test brought over into tests_print.rs. Manual: none, no user-visible change beyond the label's spelling. Co-authored-by: Hafer-Nil <26671928+Hafer-Nil@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/gpu/tests/shutdown.rs | 3 ++- crates/preview/src/tests.rs | 32 +++++++++++----------------- crates/ui-egui/src/panels/dialogs.rs | 3 ++- crates/ui-egui/src/tests_print.rs | 15 +++++++++++++ 4 files changed, 31 insertions(+), 22 deletions(-) diff --git a/crates/gpu/tests/shutdown.rs b/crates/gpu/tests/shutdown.rs index 1fc0ce7bb2..2b61139e49 100644 --- a/crates/gpu/tests/shutdown.rs +++ b/crates/gpu/tests/shutdown.rs @@ -40,7 +40,8 @@ fn nothing_renders_on_the_gpu_once_the_process_is_ending() { }) }; if has_gpu { - while rendered.load(Ordering::SeqCst) == 0 && !refused.load(Ordering::SeqCst) { + let end = std::time::Instant::now() + Duration::from_secs(120); + while rendered.load(Ordering::SeqCst) == 0 && !refused.load(Ordering::SeqCst) && std::time::Instant::now() < end { std::thread::yield_now(); } assert!(rendered.load(Ordering::SeqCst) > 0, "the GPU renders before the shutdown ({:?})", lcc_gpu::last_fallback()); diff --git a/crates/preview/src/tests.rs b/crates/preview/src/tests.rs index d6d6a42f98..2c4d59d131 100644 --- a/crates/preview/src/tests.rs +++ b/crates/preview/src/tests.rs @@ -218,17 +218,13 @@ fn pool_priorities_dedupe_and_drop() { 1000, Box::new(move || { let (m, cv) = &*g; - let mut open = m.lock().unwrap(); - while !*open { - open = cv.wait(open).unwrap(); - } + let (_open, waited) = cv.wait_timeout_while(m.lock().unwrap(), std::time::Duration::from_secs(60), |open| !*open).unwrap(); + assert!(!waited.timed_out(), "the test never opened the gate"); 999 }), ); // wait until the worker took the gate job - while p.queued() > 0 { - std::thread::yield_now(); - } + assert!(eventually(30, || p.queued() == 0), "the worker never took the gate job"); p.submit(1, 1, 5, Box::new(|| 1)); // off-screen thumb p.submit(2, 1, 10, Box::new(|| 2)); // visible thumb p.submit(3, 1, 100, Box::new(|| 3)); // loupe @@ -243,13 +239,11 @@ fn pool_priorities_dedupe_and_drop() { cv.notify_all(); } let mut order = Vec::new(); - while order.len() < 4 { - if let Some(d) = p.try_recv() { - order.push((d.slot, d.key, d.result)); - } else { - std::thread::yield_now(); - } - } + let all_done = eventually(30, || { + order.extend(std::iter::from_fn(|| p.try_recv()).map(|d| (d.slot, d.key, d.result))); + order.len() >= 4 + }); + assert!(all_done, "four jobs done: {order:?}"); assert_eq!(order, vec![(999, 0, 999), (3, 1, 3), (2, 2, 22), (1, 1, 1)]); } @@ -279,7 +273,7 @@ fn pool_with_a_running_job() -> (JobPool, std::sync::mpsc::Sender<()>) { let _ = released.recv_timeout(std::time::Duration::from_secs(60)); }), ); - has_started.recv().unwrap(); + has_started.recv_timeout(std::time::Duration::from_secs(30)).expect("the job starts"); (p, release) } @@ -301,7 +295,7 @@ fn pool_drop_waits_for_running_job() { f.store(true, Ordering::SeqCst); }), ); - has_started.recv().unwrap(); + has_started.recv_timeout(std::time::Duration::from_secs(30)).expect("the job starts"); let q = queued_ran.clone(); p.submit(2, 0, 1, Box::new(move || q.store(true, Ordering::SeqCst))); drop(p); @@ -347,9 +341,7 @@ fn pool_stops_after_a_job_panicked_and_when_dropped_by_its_own_job() { // a worker that unwound is not waited for let mut p: JobPool = JobPool::new(1); p.submit(1, 0, 1, Box::new(|| panic!("a job panics (expected in this test)"))); - while p.live_workers() > 0 { - std::thread::yield_now(); - } + assert!(eventually(30, || p.live_workers() == 0), "the worker that panicked is still counted"); assert!(p.shutdown(std::time::Duration::from_secs(30))); // the last owner of a pool is one of its jobs: the worker must not wait for (or join) itself @@ -785,7 +777,7 @@ fn a_slot_runs_one_job_at_a_time() { }) }; p.submit(1, 1, 9, job(1, Some(released))); - assert_eq!(has_started.recv().unwrap(), 1); + assert_eq!(has_started.recv_timeout(std::time::Duration::from_secs(30)).expect("slot 1's first job starts"), 1); // two newer requests for the busy slot: the second replaces the first, neither starts p.submit(1, 2, 9, job(2, None)); p.submit(1, 3, 9, job(3, None)); diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index ffd89e4ab8..50788ed5ea 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -1383,7 +1383,8 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { let n = app.session.selected().len(); ui.label(crate::i18n::tr_format!("{n} selected photos · {pages} pages", n = n, pages = n.div_ceil(options.columns * options.rows))); field(ui, "Paper", |ui| { - crate::widgets::combo_box("contactSheetPaper").selected_text(&options.paper).show_ui(ui, |ui| { + let shown = if options.paper == "letter" { crate::i18n::tr("Letter") } else { "A4" }; + crate::widgets::combo_box("contactSheetPaper").selected_text(shown).show_ui(ui, |ui| { ui.selectable_value(&mut options.paper, "a4".into(), "A4"); ui.selectable_value(&mut options.paper, "letter".into(), crate::i18n::tr("Letter")); }); diff --git a/crates/ui-egui/src/tests_print.rs b/crates/ui-egui/src/tests_print.rs index 4c8ac6ae80..5a2a761a41 100644 --- a/crates/ui-egui/src/tests_print.rs +++ b/crates/ui-egui/src/tests_print.rs @@ -569,3 +569,18 @@ fn print_module_follows_the_filmstrip_selection() { cmd(&mut h, "library.select", json!({"ids": []})); assert!(crate::print_ui::job_photos(&mut h.app, false).len() >= ids.len()); } + +// upstream #4484: the contact sheet's Paper box shows the label (A4 / Letter), not the stored id +#[test] +fn contact_sheet_paper_box_shows_the_label() { + let mut h = demo(Services::default()); + h.app.ui.language = crate::i18n::Locale::En; + for (paper, label) in [("a4", "A4"), ("letter", "Letter")] { + let options = lcc_engine::contact_sheet::Options { paper: paper.into(), ..Default::default() }; + h.app.ui.dialog = Some(Dialog::ContactSheet { options }); + h.settle(T); + let text = h.painted_text(); + assert!(text.iter().any(|t| t == label), "{paper} not shown as {label}"); + assert!(!text.iter().any(|t| t == paper), "{paper} shown raw"); + } +} From 4fc1441525da7e4d4f13638b7eef6c89b9310173 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:32:46 +1100 Subject: [PATCH 008/112] upstream #4444: LR-VIEW-ZOOM: dragging a mask keeps the photo sharp Adapted from upstream #4444: region::SHARP_DRAG names the "Edit Mask" interaction; DragScale keeps its drafts at full size on the CPU too and never gives up to CPU_DRAFT_SCALE mid-drag. The fork begins that interaction in three places in panels/detail.rs (gradient body, grip drag, mask keys); all use the constant. Test brought over. Manual: none, no user-visible change beyond sharper drafts. Co-authored-by: tecari0 <121329615+tecari0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/detail.rs | 6 +++--- crates/ui-egui/src/region.rs | 33 +++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 245d5a8242..101a58f38e 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -4974,7 +4974,7 @@ fn mask_overlay(app: &mut LccApp, ui: &mut egui::Ui, resp: &egui::Response, map: app.ui.tool.clear(); } if resp.drag_started() && d.masks.iter().find(|m| m.id == mid).and_then(|m| m.components.get(ci)).is_some() { - let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"})); + let _ = app.run("develop.beginInteraction", json!({"label": crate::region::SHARP_DRAG})); if let Some(original_shape) = current_shape(app, mid, ci) .or_else(|| d.masks.iter().find(|m| m.id == mid).and_then(|m| m.components.get(ci)).map(|c| c.shape.clone())) { @@ -5159,7 +5159,7 @@ fn mask_overlay(app: &mut LccApp, ui: &mut egui::Ui, resp: &egui::Response, map: let _ = app.run("mask.select", json!({"id": mask})); } app.ui.active_mask_component = Some(comp); - let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"})); + let _ = app.run("develop.beginInteraction", json!({"label": crate::region::SHARP_DRAG})); // (read after it begins: an old mask is on the photo from then on, in its coordinates) if let Some(original_shape) = current_shape(app, mask, comp) .or_else(|| d.masks.iter().find(|m| m.id == mask).and_then(|m| m.components.get(comp)).map(|c| c.shape.clone())) @@ -5418,7 +5418,7 @@ fn mask_keys(app: &mut LccApp, ui: &mut egui::Ui, map: &CanvasMap, d: &DevelopSe if app.session.active_mask != Some(mid) { let _ = app.run("mask.select", json!({"id": mid})); } - let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"})); + let _ = app.run("develop.beginInteraction", json!({"label": crate::region::SHARP_DRAG})); // (read after it begins: an old mask is on the photo from then on, in its coordinates) let (shape, map) = match (current_shape(app, mid, ci), current_on_photo(app, mid)) { (Some(s), Some(on)) => (s, map.for_mask(on)), diff --git a/crates/ui-egui/src/region.rs b/crates/ui-egui/src/region.rs index 1d25618e49..3b8e3b3711 100644 --- a/crates/ui-egui/src/region.rs +++ b/crates/ui-egui/src/region.rs @@ -100,6 +100,12 @@ pub struct LoupePlan { /// it, or full-size drafts of this drag went over [`DRAFT_BUDGET_MS`]), against the render at rest. pub const CPU_DRAFT_SCALE: f32 = 0.6; +/// The interaction label of a mask edit on the photo (moving, resizing or turning a gradient or +/// pin). Its drafts are always full size, on the CPU too, and never drop to [`CPU_DRAFT_SCALE`]: +/// the edit changes part of the photo, and a smaller draft blurred the whole photo for it +/// (adapted from upstream #4444). A slow machine shows fewer drafts instead. +pub const SHARP_DRAG: &str = "Edit Mask"; + /// The slider budget (ms): a drag whose full-size drafts take longer gets smaller drafts next time. /// A draft's time is its render plus the frame that shows it (the texture upload is part of it). pub const DRAFT_BUDGET_MS: f64 = 16.0; @@ -187,7 +193,7 @@ impl DragScale { } let key = (photo, control.to_string()); let small = matches!(self.verdict(&key), Some(Verdict::Slow { until, .. }) if now < until); - let s = if gpu && !small { 1.0 } else { CPU_DRAFT_SCALE }; + let s = if control == SHARP_DRAG || (gpu && !small) { 1.0 } else { CPU_DRAFT_SCALE }; self.current = Some((key, s)); self.seen = shown; Some(s) @@ -211,7 +217,8 @@ impl DragScale { } if self.samples.len() > GIVE_UP_AFTER && median_after_first(&self.samples).is_some_and(|m| m > DRAFT_BUDGET_MS * GIVE_UP_FACTOR) - && let Some((_, s)) = self.current.as_mut() + && let Some(((_, control), s)) = self.current.as_mut() + && control != SHARP_DRAG { *s = CPU_DRAFT_SCALE; return; @@ -1103,6 +1110,28 @@ mod tests { } /// One whole drag of `drag` at full size whose drafts all take `ms` to show, ending at `now`. + // Given a mask edit on the photo (a gradient's handle or pin dragged), its drafts are full size + // even on the CPU, after slow drags, and when they are far over budget: the photo stays sharp + // (upstream #4444) + #[test] + fn a_mask_edit_always_drafts_at_full_size() { + use lcc_catalog::PhotoId; + let mut d = DragScale::default(); + let mask = Some((PhotoId(1), SHARP_DRAG)); + assert_eq!(d.scale(mask, false, None, 0.0), Some(1.0), "on the CPU too"); + d.scale(None, false, None, 0.0); + for i in 0..3 { + assert_eq!(timed_drag(&mut d, mask, 400.0, f64::from(i)), Some(1.0), "drag {i}: slow drags don't shrink the next"); + } + assert_eq!(d.scale(mask, true, None, 10.0), Some(1.0)); + for key in 100..110 { + d.observe(key, 400.0, None); + } + assert_eq!(d.scale(mask, true, None, 10.0), Some(1.0)); + d.scale(None, true, None, 10.0); + assert_eq!(d.scale(Some((PhotoId(1), "Exposure")), false, None, 10.0), Some(CPU_DRAFT_SCALE)); + } + fn timed_drag(d: &mut DragScale, drag: Option<(lcc_catalog::PhotoId, &str)>, ms: f64, now: f64) -> Option { let scale = d.scale(drag, true, None, now); for key in 1..=6 { From 9468923d8bfcfbcadfd93496934d82d6f8172122 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:32:49 +1100 Subject: [PATCH 009/112] upstream #4482: unbounded test waits in ui-egui get a time limit The gated file_probe spins in headless.rs (two) and tests_sync.rs stop after 60 s. The preview and gpu halves of the upstream PR are already in the fork (eventually()/recv_timeout and the 120 s shutdown bound), so only the ui-egui part is ported. Test-only. Manual: none, no user-visible change. Co-authored-by: THEtheChad <880190+THEtheChad@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/headless.rs | 8 ++++++-- crates/ui-egui/src/tests_sync.rs | 4 +++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index c83223f83a..4e962d7a2d 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -4625,7 +4625,9 @@ mod tests { let (g, n) = (gate.clone(), started.clone()); h.app.session.media.file_probe = Some(std::sync::Arc::new(move |_: &str| { n.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - while !g.load(std::sync::atomic::Ordering::Relaxed) { + // bounded, so a test that fails before opening the gate doesn't leave the scan spinning + let end = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !g.load(std::sync::atomic::Ordering::Relaxed) && std::time::Instant::now() < end { std::thread::sleep(Duration::from_millis(5)); } Ok(lcc_engine::media::ProbeInfo { format: "PNG".into(), ..Default::default() }) @@ -4751,7 +4753,9 @@ mod tests { let gate = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let g = gate.clone(); h.app.session.media.file_probe = Some(std::sync::Arc::new(move |_: &str| { - while !g.load(std::sync::atomic::Ordering::Relaxed) { + // bounded, so a test that fails before opening the gate doesn't leave the scan spinning + let end = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !g.load(std::sync::atomic::Ordering::Relaxed) && std::time::Instant::now() < end { std::thread::sleep(Duration::from_millis(5)); } Ok(lcc_engine::media::ProbeInfo { format: "PNG".into(), ..Default::default() }) diff --git a/crates/ui-egui/src/tests_sync.rs b/crates/ui-egui/src/tests_sync.rs index 8182616388..4236dde8dc 100644 --- a/crates/ui-egui/src/tests_sync.rs +++ b/crates/ui-egui/src/tests_sync.rs @@ -492,7 +492,9 @@ fn the_folders_scan_shows_a_row_and_its_cross_closes_the_dialog() { let gate = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let g = gate.clone(); h.app.session.media.file_probe = Some(std::sync::Arc::new(move |_: &str| { - while !g.load(std::sync::atomic::Ordering::Relaxed) { + // bounded, so a test that fails before opening the gate doesn't leave the scan spinning + let end = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !g.load(std::sync::atomic::Ordering::Relaxed) && std::time::Instant::now() < end { std::thread::sleep(Duration::from_millis(5)); } Ok(lcc_engine::media::ProbeInfo { format: "PNG".into(), ..Default::default() }) From da85582c9643f1be3bb0a414792cc009622c7136 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:32:53 +1100 Subject: [PATCH 010/112] upstream #4663: _DISABLE_UPDATES turns update checks off Adapted from upstream #4663 (LIGHTCRAFT_DISABLE_UPDATES there): the variable is read through lcc_brand::env (brand prefix, legacy prefixes too). 1/on/true/yes (trimmed, any case) turn it on. Then update.check refuses with the reason, the start-up check never runs, and Help > Check for Updates... is greyed out with a hover text saying why (translated in every fork catalog). The Nix wrapper sets it. Manual: platforms/desktop.mdx (Updates), docs/manual/troubleshooting.md Co-authored-by: marcel <47798787+Supermarcel10@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- apps/app/src/main.rs | 5 +++-- crates/engine/src/cmd/update.rs | 4 ++++ crates/engine/src/update.rs | 16 ++++++++++++++++ crates/engine/src/update/tests.rs | 11 +++++++++++ crates/ui-egui/locales/fork/cs.json | 1 + crates/ui-egui/locales/fork/de.json | 1 + crates/ui-egui/locales/fork/es.json | 1 + crates/ui-egui/locales/fork/fi.json | 1 + crates/ui-egui/locales/fork/fr.json | 1 + crates/ui-egui/locales/fork/id.json | 1 + crates/ui-egui/locales/fork/it.json | 1 + crates/ui-egui/locales/fork/ja.json | 1 + crates/ui-egui/locales/fork/ka.json | 1 + crates/ui-egui/locales/fork/pl.json | 1 + crates/ui-egui/locales/fork/pt-br.json | 1 + crates/ui-egui/locales/fork/ru.json | 1 + crates/ui-egui/locales/fork/sv.json | 1 + crates/ui-egui/locales/fork/uk.json | 1 + crates/ui-egui/locales/fork/vi.json | 1 + crates/ui-egui/locales/fork/zh-hans.json | 1 + crates/ui-egui/locales/fork/zh-hant.json | 1 + crates/ui-egui/src/menubar.rs | 7 +++++++ crates/ui-egui/src/menus_fork.rs | 4 ++++ .../src/content/docs/platforms/desktop.mdx | 1 + docs/manual/troubleshooting.md | 4 +++- docs/whats-new/2026-11-29-disable-updates.md | 2 ++ nix/package.nix | 5 ++++- 27 files changed, 72 insertions(+), 4 deletions(-) create mode 100644 docs/whats-new/2026-11-29-disable-updates.md diff --git a/apps/app/src/main.rs b/apps/app/src/main.rs index 1e662e23fb..5438ab838c 100644 --- a/apps/app/src/main.rs +++ b/apps/app/src/main.rs @@ -1340,8 +1340,9 @@ fn panic_log_path(args: impl IntoIterator) -> Option< /// skipped, as the parser takes them. /// Whether the window looks for a newer release at start: only a session that keeps its settings, and not when /// `--no-update-check` was given (Settings > General still decides within that). +/// `_DISABLE_UPDATES` (a distro package) turns it off too (adapted from upstream #4663). fn startup_update_check(keeps_settings: bool, no_update_check: bool) -> bool { - keeps_settings && !no_update_check + keeps_settings && !no_update_check && !lcc_engine::update::disabled_by_env() } fn in_memory_session(args: impl IntoIterator) -> bool { @@ -2693,7 +2694,7 @@ mod config_path_tests { /// that keeps its settings looks. #[test] fn no_update_check_flag_disables_the_startup_check() { - assert!(startup_update_check(true, false)); + assert_eq!(startup_update_check(true, false), !lcc_engine::update::disabled_by_env()); assert!(!startup_update_check(true, true)); assert!(!startup_update_check(false, false)); } diff --git a/crates/engine/src/cmd/update.rs b/crates/engine/src/cmd/update.rs index 18d005c049..2532ea2e65 100644 --- a/crates/engine/src/cmd/update.rs +++ b/crates/engine/src/cmd/update.rs @@ -23,6 +23,10 @@ fn check(s: &mut Session, p: &Value) -> Result { if p.get("feed").is_some() { return Err(bad(C, "`feed` is not a parameter: the app reads only its own release feed")); } + if crate::update::disabled_by_env() { + let var = lcc_brand::env_var(crate::update::DISABLE_ENV); + return Err(bad(C, format!("updates are disabled ({var} is set); your package manager handles updates"))); + } let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false); if wait && !s.updater.checking() { s.updater.check_now(); diff --git a/crates/engine/src/update.rs b/crates/engine/src/update.rs index c0a3bee6ff..91b766a098 100644 --- a/crates/engine/src/update.rs +++ b/crates/engine/src/update.rs @@ -26,6 +26,22 @@ pub const ACTIVITY_KIND: &str = "update"; /// The row's label (English; the frontend translates it). pub const ACTIVITY_LABEL: &str = "Downloading update"; +/// The variable (after the brand's env prefix) that turns every update check and prompt off. +pub const DISABLE_ENV: &str = "DISABLE_UPDATES"; + +/// Whether `_DISABLE_UPDATES` (or a legacy spelling) turns update checks off for this +/// process. Distro packages (NixOS, deb/rpm, …) set it: the package manager owns the update flow, +/// so the app's own start-up prompt and manual check would only nag. Adapted from upstream #4663. +pub fn disabled_by_env() -> bool { + disabled_by_value(lcc_brand::env(DISABLE_ENV).as_deref()) +} + +/// [`disabled_by_env`] for a known value, without reading the environment: `1`, `on`, `true` or +/// `yes` (case-insensitive, trimmed) turn updates off; anything else, or no variable, leaves them on. +pub fn disabled_by_value(value: Option<&str>) -> bool { + value.is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "on" | "true" | "yes")) +} + /// Settings file in the app's settings folder. const SETTINGS_FILE: &str = "updates.json"; /// Schema version of that file; a file from a newer build is left alone. diff --git a/crates/engine/src/update/tests.rs b/crates/engine/src/update/tests.rs index 2be11af217..f2da7c7774 100644 --- a/crates/engine/src/update/tests.rs +++ b/crates/engine/src/update/tests.rs @@ -911,3 +911,14 @@ fn a_package_install_is_sent_to_its_package_manager() { assert!(activity.list().is_empty(), "nothing started"); let _ = std::fs::remove_dir_all(&dir); } + +// upstream #4663: `_DISABLE_UPDATES` values that turn updates off, and those that don't +#[test] +fn disable_updates_values() { + for on in ["1", "on", "true", "yes", " yes ", "TRUE"] { + assert!(disabled_by_value(Some(on)), "{on:?}"); + } + for off in [None, Some(""), Some(" "), Some("0"), Some("false"), Some("off"), Some("no"), Some("2")] { + assert!(!disabled_by_value(off), "{off:?}"); + } +} diff --git a/crates/ui-egui/locales/fork/cs.json b/crates/ui-egui/locales/fork/cs.json index 9cfbfdefc1..0026edb267 100644 --- a/crates/ui-egui/locales/fork/cs.json +++ b/crates/ui-egui/locales/fork/cs.json @@ -3552,6 +3552,7 @@ "Update this one automatically": "Aktualizovat tento modul automaticky", "Update to Current Process Version": "Aktualizovat na aktuální verzi procesu", "Update with Current Settings…": "Aktualizovat podle aktuálního nastavení…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Aktualizace jsou vypnuté (je nastaveno {env}_DISABLE_UPDATES); aktualizace obstarává správce balíčků.", "Updates the installed version": "Aktualizuje nainstalovanou verzi", "Updates…": "Aktualizace…", "Updating the DNG previews stopped unexpectedly": "Aktualizace náhledů DNG se neočekávaně zastavila", diff --git a/crates/ui-egui/locales/fork/de.json b/crates/ui-egui/locales/fork/de.json index 35552443ba..13f4f5b208 100644 --- a/crates/ui-egui/locales/fork/de.json +++ b/crates/ui-egui/locales/fork/de.json @@ -3421,6 +3421,7 @@ "Update this one automatically": "Dieses automatisch aktualisieren", "Update to Current Process Version": "Auf aktuelle Prozessversion aktualisieren", "Update with Current Settings…": "Mit aktuellen Einstellungen aktualisieren…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Updates sind ausgeschaltet ({env}_DISABLE_UPDATES ist gesetzt); Ihre Paketverwaltung kümmert sich um Updates.", "Updates the installed version": "Aktualisiert die installierte Version", "Updates…": "Aktualisierungen…", "Updating the DNG previews stopped unexpectedly": "Das Aktualisieren der DNG-Vorschauen wurde unerwartet angehalten", diff --git a/crates/ui-egui/locales/fork/es.json b/crates/ui-egui/locales/fork/es.json index 7ca47cd7dd..45b21ffd1a 100644 --- a/crates/ui-egui/locales/fork/es.json +++ b/crates/ui-egui/locales/fork/es.json @@ -3684,6 +3684,7 @@ "Update to Current Process": "Actualizar al proceso actual", "Update to Current Process Version": "Actualizar a la versión de proceso actual", "Update with Current Settings…": "Actualizar con la configuración actual…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Las actualizaciones están desactivadas ({env}_DISABLE_UPDATES está definida); su gestor de paquetes se encarga de ellas.", "Updates the installed version": "Actualiza la versión instalada", "Updates…": "Actualizaciones…", "Updating the DNG previews stopped unexpectedly": "La actualización de las vistas previas DNG se detuvo inesperadamente", diff --git a/crates/ui-egui/locales/fork/fi.json b/crates/ui-egui/locales/fork/fi.json index f0b5e58bad..19c9c5f2dd 100644 --- a/crates/ui-egui/locales/fork/fi.json +++ b/crates/ui-egui/locales/fork/fi.json @@ -3751,6 +3751,7 @@ "Update this one automatically": "Päivitä tämä automaattisesti", "Update to Current Process Version": "Päivitä nykyiseen prosessiversioon", "Update with Current Settings…": "Päivitä nykyisillä asetuksilla…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Päivitykset ovat pois päältä ({env}_DISABLE_UPDATES on asetettu); paketinhallinta hoitaa päivitykset.", "Updates the installed version": "Päivittää asennetun version", "Updates…": "Päivitykset…", "Updating the DNG previews stopped unexpectedly": "DNG-esikatselujen päivitys pysähtyi odottamatta", diff --git a/crates/ui-egui/locales/fork/fr.json b/crates/ui-egui/locales/fork/fr.json index 4e20aebef1..1125b09d58 100644 --- a/crates/ui-egui/locales/fork/fr.json +++ b/crates/ui-egui/locales/fork/fr.json @@ -3365,6 +3365,7 @@ "Update this one automatically": "Mettre à jour celui-ci automatiquement", "Update to Current Process Version": "Mettre à jour vers la version de traitement actuelle", "Update with Current Settings…": "Mettre à jour avec les réglages actuels…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Les mises à jour sont désactivées ({env}_DISABLE_UPDATES est défini) ; votre gestionnaire de paquets s’en charge.", "Updates the installed version": "Met à jour la version installée", "Updates…": "Mises à jour…", "Updating the DNG previews stopped unexpectedly": "La mise à jour des aperçus DNG s'est arrêtée de façon inattendue", diff --git a/crates/ui-egui/locales/fork/id.json b/crates/ui-egui/locales/fork/id.json index 89a8a184c5..9d87434767 100644 --- a/crates/ui-egui/locales/fork/id.json +++ b/crates/ui-egui/locales/fork/id.json @@ -3764,6 +3764,7 @@ "Update this one automatically": "Perbarui yang ini secara otomatis", "Update to Current Process Version": "Perbarui ke versi proses terbaru", "Update with Current Settings…": "Perbarui dengan pengaturan saat ini…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Pembaruan dimatikan ({env}_DISABLE_UPDATES disetel); pengelola paket Anda yang menangani pembaruan.", "Updates the installed version": "Memperbarui versi yang terinstal", "Updates…": "Pembaruan…", "Updating the DNG previews stopped unexpectedly": "Pembaruan pratinjau DNG berhenti tanpa diduga", diff --git a/crates/ui-egui/locales/fork/it.json b/crates/ui-egui/locales/fork/it.json index 4f5a9f5569..fc5579d857 100644 --- a/crates/ui-egui/locales/fork/it.json +++ b/crates/ui-egui/locales/fork/it.json @@ -3557,6 +3557,7 @@ "Update this one automatically": "Aggiorna questo automaticamente", "Update to Current Process Version": "Aggiorna alla versione processo corrente", "Update with Current Settings…": "Aggiorna con le impostazioni attuali…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Gli aggiornamenti sono disattivati ({env}_DISABLE_UPDATES è impostata); se ne occupa il gestore di pacchetti.", "Updates the installed version": "Aggiorna la versione installata", "Updates…": "Aggiornamenti…", "Updating the DNG previews stopped unexpectedly": "L'aggiornamento delle anteprime DNG si è interrotto inaspettatamente", diff --git a/crates/ui-egui/locales/fork/ja.json b/crates/ui-egui/locales/fork/ja.json index 2d2ddeb3e2..97a9870123 100644 --- a/crates/ui-egui/locales/fork/ja.json +++ b/crates/ui-egui/locales/fork/ja.json @@ -3686,6 +3686,7 @@ "Update to Current Process": "現在のプロセスに更新", "Update to Current Process Version": "現在のプロセスバージョンに更新", "Update with Current Settings…": "現在の設定で更新…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "アップデートはオフです({env}_DISABLE_UPDATES が設定されています)。アップデートはパッケージマネージャーが行います。", "Updates the installed version": "インストール済みのバージョンを更新します", "Updates…": "アップデート…", "Updating the DNG previews stopped unexpectedly": "DNG プレビューの更新が予期せず停止しました", diff --git a/crates/ui-egui/locales/fork/ka.json b/crates/ui-egui/locales/fork/ka.json index 4dbca81f17..cef78f4fa1 100644 --- a/crates/ui-egui/locales/fork/ka.json +++ b/crates/ui-egui/locales/fork/ka.json @@ -3965,6 +3965,7 @@ "Update this one automatically": "ამის ავტომატურად განახლება", "Update to Current Process Version": "მიმდინარე დამუშავების ვერსიამდე განახლება", "Update with Current Settings…": "განახლება მიმდინარე პარამეტრებით…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "განახლებები გამორთულია ({env}_DISABLE_UPDATES დაყენებულია); განახლებებს პაკეტების მმართველი უზრუნველყოფს.", "Updates the installed version": "აახლებს დაინსტალირებულ ვერსიას", "Updates…": "განახლებები…", "Updating the DNG previews stopped unexpectedly": "DNG გადახედვების განახლება მოულოდნელად შეჩერდა", diff --git a/crates/ui-egui/locales/fork/pl.json b/crates/ui-egui/locales/fork/pl.json index 1bcecc577b..59f52fac95 100644 --- a/crates/ui-egui/locales/fork/pl.json +++ b/crates/ui-egui/locales/fork/pl.json @@ -3801,6 +3801,7 @@ "Update this one automatically": "Aktualizuj tę automatycznie", "Update to Current Process Version": "Zaktualizuj do bieżącej wersji procesu", "Update with Current Settings…": "Aktualizuj bieżącymi ustawieniami…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Aktualizacje są wyłączone (ustawiono {env}_DISABLE_UPDATES); aktualizacjami zajmuje się menedżer pakietów.", "Updates the installed version": "Aktualizuje zainstalowaną wersję", "Updates…": "Aktualizacje…", "Updating the DNG previews stopped unexpectedly": "Aktualizacja podglądów DNG nieoczekiwanie się zatrzymała", diff --git a/crates/ui-egui/locales/fork/pt-br.json b/crates/ui-egui/locales/fork/pt-br.json index 1fed958212..43c6653c7e 100644 --- a/crates/ui-egui/locales/fork/pt-br.json +++ b/crates/ui-egui/locales/fork/pt-br.json @@ -3683,6 +3683,7 @@ "Update to Current Process": "Atualizar para o processo atual", "Update to Current Process Version": "Atualizar para a versão do processo atual", "Update with Current Settings…": "Atualizar com as configurações atuais…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "As atualizações estão desativadas ({env}_DISABLE_UPDATES está definida); seu gerenciador de pacotes cuida delas.", "Updates the installed version": "Atualiza a versão instalada", "Updates…": "Atualizações…", "Updating the DNG previews stopped unexpectedly": "A atualização das pré-visualizações DNG parou inesperadamente", diff --git a/crates/ui-egui/locales/fork/ru.json b/crates/ui-egui/locales/fork/ru.json index ffba3a436d..b53c7552dc 100644 --- a/crates/ui-egui/locales/fork/ru.json +++ b/crates/ui-egui/locales/fork/ru.json @@ -3662,6 +3662,7 @@ "Update to Current Process Version": "Обновить до текущей версии обработки", "Update with Current Settings…": "Обновить текущими настройками…", "Updated the edits saved in the external editor": "Обновлены правки, сохранённые во внешнем редакторе", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Обновления отключены (задана переменная {env}_DISABLE_UPDATES); обновлениями занимается менеджер пакетов.", "Updates the installed version": "Обновляет установленную версию", "Updates…": "Обновления…", "Updating the DNG previews stopped unexpectedly": "Обновление превью DNG неожиданно остановилось", diff --git a/crates/ui-egui/locales/fork/sv.json b/crates/ui-egui/locales/fork/sv.json index 1e8d467a64..c0cec16b82 100644 --- a/crates/ui-egui/locales/fork/sv.json +++ b/crates/ui-egui/locales/fork/sv.json @@ -3828,6 +3828,7 @@ "Update this one automatically": "Uppdatera det här automatiskt", "Update to Current Process Version": "Uppdatera till aktuell processversion", "Update with Current Settings…": "Uppdatera med aktuella inställningar…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Uppdateringar är avstängda ({env}_DISABLE_UPDATES är satt); din pakethanterare sköter uppdateringar.", "Updates the installed version": "Uppdaterar den installerade versionen", "Updates…": "Uppdateringar…", "Updating the DNG previews stopped unexpectedly": "Uppdateringen av DNG-förhandsvisningarna avbröts oväntat", diff --git a/crates/ui-egui/locales/fork/uk.json b/crates/ui-egui/locales/fork/uk.json index ad311c5b1a..eb409f40bc 100644 --- a/crates/ui-egui/locales/fork/uk.json +++ b/crates/ui-egui/locales/fork/uk.json @@ -3535,6 +3535,7 @@ "Update to Current Process": "Оновити до поточного процесу", "Update to Current Process Version": "Оновити до поточної версії обробки", "Update with Current Settings…": "Оновити поточними налаштуваннями…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Оновлення вимкнено (задано змінну {env}_DISABLE_UPDATES); оновленнями опікується менеджер пакетів.", "Updates the installed version": "Оновлює встановлену версію", "Updates…": "Оновлення…", "Updating the DNG previews stopped unexpectedly": "Оновлення попередніх переглядів DNG несподівано зупинилося", diff --git a/crates/ui-egui/locales/fork/vi.json b/crates/ui-egui/locales/fork/vi.json index 3e20b4349c..b8696b7eed 100644 --- a/crates/ui-egui/locales/fork/vi.json +++ b/crates/ui-egui/locales/fork/vi.json @@ -4005,6 +4005,7 @@ "Update this one automatically": "Tự động cập nhật plugin này", "Update to Current Process Version": "Cập nhật lên phiên bản quy trình hiện tại", "Update with Current Settings…": "Cập nhật với cài đặt hiện tại…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Cập nhật đã bị tắt ({env}_DISABLE_UPDATES được đặt); trình quản lý gói của bạn sẽ lo việc cập nhật.", "Updates the installed version": "Cập nhật phiên bản đã cài", "Updates…": "Cập nhật…", "Updating the DNG previews stopped unexpectedly": "Việc cập nhật bản xem trước DNG đã dừng đột ngột", diff --git a/crates/ui-egui/locales/fork/zh-hans.json b/crates/ui-egui/locales/fork/zh-hans.json index 4ade44b277..c2ec72088d 100644 --- a/crates/ui-egui/locales/fork/zh-hans.json +++ b/crates/ui-egui/locales/fork/zh-hans.json @@ -3623,6 +3623,7 @@ "Update to Current Process": "更新到当前处理版本", "Update to Current Process Version": "更新到当前处理版本", "Update with Current Settings…": "用当前设置更新…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "更新已关闭(已设置 {env}_DISABLE_UPDATES);更新由软件包管理器负责。", "Updates the installed version": "更新已安装的版本", "Updates…": "更新…", "Updating the DNG previews stopped unexpectedly": "更新 DNG 预览意外停止", diff --git a/crates/ui-egui/locales/fork/zh-hant.json b/crates/ui-egui/locales/fork/zh-hant.json index d3f179f053..439d5ebd46 100644 --- a/crates/ui-egui/locales/fork/zh-hant.json +++ b/crates/ui-egui/locales/fork/zh-hant.json @@ -3683,6 +3683,7 @@ "Update to Current Process": "更新至目前處理版本", "Update to Current Process Version": "更新至目前處理版本", "Update with Current Settings…": "以目前設定更新…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "更新已關閉(已設定 {env}_DISABLE_UPDATES);更新由套件管理員負責。", "Updates the installed version": "更新已安裝的版本", "Updates…": "更新…", "Updating the DNG previews stopped unexpectedly": "更新 DNG 預覽意外停止", diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rs index 4c6837b3e6..a652aa3ecb 100644 --- a/crates/ui-egui/src/menubar.rs +++ b/crates/ui-egui/src/menubar.rs @@ -132,6 +132,9 @@ pub fn native_menu_structure(bar: &[(String, Vec)], keymap: &crate::sh /// The Library module's menus in order (the macOS app menu is added by the host); [`menus`] gives /// the module on screen's. +/// Hover text of Help ▸ Check for Updates… when `_DISABLE_UPDATES` turned it off. +const UPDATES_DISABLED_HINT: &str = "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates."; + pub const MENUS: &[&str] = &["File", "Edit", "Library", "Photo", "Metadata", "View", "Window", "Help"]; /// Order inside submenus whose items come from the registry: (menu, submenu, ids and `---`). @@ -1601,6 +1604,10 @@ pub(crate) fn nodes_ui( if crate::lrc_menus::is_coming_soon(id) { r = r.on_disabled_hover_text(crate::i18n::tr(crate::lrc_menus::COMING_SOON_HINT)); } + // Check for Updates turned off by the environment says why (upstream #4663) + if id == "app.checkForUpdates" && lcc_engine::update::disabled_by_env() { + r = r.on_disabled_hover_text(crate::i18n::tr(UPDATES_DISABLED_HINT)); + } crate::widgets::register(ui.ctx(), format!("menuitem:{id}"), r.rect); if *checked == Some(true) { let t = crate::theme::Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/menus_fork.rs b/crates/ui-egui/src/menus_fork.rs index 88e8d139b2..b19afc8d4f 100644 --- a/crates/ui-egui/src/menus_fork.rs +++ b/crates/ui-egui/src/menus_fork.rs @@ -337,6 +337,10 @@ pub(super) fn enabled(app: &LccApp, id: &str) -> Option { if crate::lrc_menus::is_coming_soon(id) { return Some(false); } + // a distro package turned updates off (`_DISABLE_UPDATES`, upstream #4663) + if id == "app.checkForUpdates" && lcc_engine::update::disabled_by_env() { + return Some(false); + } crate::module::enabled(app, id) .or_else(|| crate::catalog_ui::enabled(app, id)) .or_else(|| crate::timelapse_ui::enabled(app, id)) diff --git a/docs/manual-site/src/content/docs/platforms/desktop.mdx b/docs/manual-site/src/content/docs/platforms/desktop.mdx index d2ef35ae8c..b0842780aa 100644 --- a/docs/manual-site/src/content/docs/platforms/desktop.mdx +++ b/docs/manual-site/src/content/docs/platforms/desktop.mdx @@ -26,6 +26,7 @@ import { Aside } from '@astrojs/starlight/components'; ## Updates - **Help ▸ Check for Updates…** reads the release feed, shows the notes and how long ago it last checked ("Last checked 5 minutes ago"), then **Download** fetches the file for your platform, verifies that it was signed by the Chromaforge authors, and offers to install it over this version (where the app can't install itself, it opens the file's folder instead). When the download is ready, **Install and Relaunch** is highlighted and has the keyboard focus, so Return presses it. The notes show `code`, **bold** and links as such; a link opens in your browser. +- Installed from a distro package (the Nix package, for example), the package manager handles updates: when the environment variable `_DISABLE_UPDATES` is `1`, `on`, `true` or `yes`, the start-up check never runs and **Help ▸ Check for Updates…** is greyed out; hovering it says why. - **Help ▸ What's New** lists the changes under a heading for each date, newest first. The newest date is open; click a date's arrow, or focus it and press Space or Enter, to open or close it. Older dates are added as you scroll to them. Its text is formatted like the update notes. - A download is installed only when the release's checksum list carries a valid signature; it is checked again before install. - Installing an update restarts the app. On Windows the app quits, the installer runs, and the app starts again when it is done (after a restart the installer asked for, if it needs one). If the installer fails or its permission prompt is declined, the old version stays and the next start logs why (the installer's own log is `update-install.log` beside the download); Start-menu shortcuts, and taskbar entries pinned from them, keep working across updates. macOS, AppImage and portable-zip copies swap the new version in and start it once the app has quit. diff --git a/docs/manual/troubleshooting.md b/docs/manual/troubleshooting.md index 9c0bd3d618..4efbf9a8a2 100644 --- a/docs/manual/troubleshooting.md +++ b/docs/manual/troubleshooting.md @@ -82,7 +82,9 @@ Library → Validate DNG Files checks the selected DNGs' raw data against their Help → Check for Updates… reads the project's release feed and, when something newer exists, offers to download it for this system and install it; the app restarts afterwards. The dialog says how long ago it last checked ("Last checked 5 minutes ago"). When the download is ready, "Install and Relaunch" is highlighted and has -the keyboard focus, so Return presses it. Things that can go wrong: +the keyboard focus, so Return presses it. When `_DISABLE_UPDATES` is `1`, `on`, `true` or `yes` (distro packages +such as the Nix package set it), Check for Updates… is greyed out and the start-up check never runs: the package +manager handles updates. Things that can go wrong: - "Could not reach the release server" or "the release server answered 403": no internet, a proxy, or GitHub's rate limit. The check uses the release's `latest.json` first, which usually still works; try again later. diff --git a/docs/whats-new/2026-11-29-disable-updates.md b/docs/whats-new/2026-11-29-disable-updates.md new file mode 100644 index 0000000000..67961a123d --- /dev/null +++ b/docs/whats-new/2026-11-29-disable-updates.md @@ -0,0 +1,2 @@ +### Distro packages can turn the updater off +- Setting `_DISABLE_UPDATES=1` turns off the start-up update check and greys out **Help ▸ Check for Updates…**, which says why when you hover it. Package managers (the Nix package sets it) own updates there. diff --git a/nix/package.nix b/nix/package.nix index 3d796e7401..d777e60f98 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -209,7 +209,10 @@ rustPlatform.buildRustPackage { $out/share/metainfo/${appId}.metainfo.xml # makeWrapper keeps the program working when the libs above are only dlopen'd. - wrapProgram $out/bin/${brand.binary} --prefix LD_LIBRARY_PATH : "${lib.makeLibraryPath runtimeLibs}" + # NixOS owns the update flow (the system state updates the software), so the app's own + # start-up prompt and manual check are turned off (upstream #4663). + wrapProgram $out/bin/${brand.binary} --prefix LD_LIBRARY_PATH : "${lib.makeLibraryPath runtimeLibs}" \ + --set ${brand.env_prefix}_DISABLE_UPDATES 1 '' # The CLI: a link to the program (its wrapper on Linux, which starts it under the name it was # started by), so it runs as the CLI. From 79f41fbdf31a41b8a0b721684b35496b39b0c9af Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:34:34 +1100 Subject: [PATCH 011/112] upstream #4653: Linux reveal selects the files via FileManager1.ShowItems Adapted from upstream #4653: apps/app/src/reveal.rs calls org.freedesktop.FileManager1.ShowItems over D-Bus (zbus, already a Linux-only dependency, 2 s timeout) so the file manager selects the file, or every selected photo in one window (new Services::reveal_many). Without the service it opens the folder with xdg-open, spawned and reaped on a thread instead of waited on (the freeze). macOS/Windows unchanged; show_in_finder now takes ids/selection. Tests: file_uri encoding, empty reveal error, menu test for selection vs single reveal. Manual: platforms/desktop.mdx Co-authored-by: marcel <47798787+Supermarcel10@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- apps/app/src/main.rs | 10 ++ apps/app/src/reveal.rs | 100 ++++++++++++++++++ apps/web/src/web.rs | 1 + crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/menubar.rs | 44 ++++++++ crates/ui-egui/src/menus.rs | 42 ++++++-- .../src/content/docs/platforms/desktop.mdx | 1 + .../2026-11-29-linux-reveal-selects.md | 2 + 8 files changed, 194 insertions(+), 11 deletions(-) create mode 100644 apps/app/src/reveal.rs create mode 100644 docs/whats-new/2026-11-29-linux-reveal-selects.md diff --git a/apps/app/src/main.rs b/apps/app/src/main.rs index 5438ab838c..643d0c1cbd 100644 --- a/apps/app/src/main.rs +++ b/apps/app/src/main.rs @@ -42,6 +42,7 @@ mod midi; mod native_dialog; #[cfg(target_os = "macos")] mod native_menu; +mod reveal; #[cfg(any(target_os = "linux", windows))] mod screen_icc; #[cfg(target_os = "macos")] @@ -807,6 +808,10 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path> launch(open_url_command(url)) })), reveal: Some(Box::new(|path: &str| { + // Linux/BSD: select the file in the file manager, never waiting for it (upstream #4653) + if cfg!(any(target_os = "linux", target_os = "freebsd")) { + return reveal::reveal_one(path); + } let status = if cfg!(target_os = "macos") { std::process::Command::new("open").args(["-R", path]).status() } else if cfg!(target_os = "windows") { @@ -819,6 +824,11 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path> .map_err(|e| e.to_string()) .and_then(|s| if s.success() || cfg!(target_os = "windows") { Ok(()) } else { Err(format!("reveal failed: {s}")) }) })), + reveal_many: if cfg!(any(target_os = "linux", target_os = "freebsd")) { + Some(Box::new(|paths: &[String]| reveal::reveal_files(paths))) + } else { + None + }, pick_files: picker!(|| { file_dialog() .add_filter_nocase(lcc_ui_egui::i18n::tr("Photos"), lcc_engine::import::EXTENSIONS) diff --git a/apps/app/src/reveal.rs b/apps/app/src/reveal.rs new file mode 100644 index 0000000000..b9246f14b2 --- /dev/null +++ b/apps/app/src/reveal.rs @@ -0,0 +1,100 @@ +//! Revealing photos in the Linux/BSD file manager. Adapted from upstream #4653 (issues #4652, +//! #4658 there): a file is selected through `org.freedesktop.FileManager1.ShowItems` over D-Bus +//! (several files in one window), and only where that service is missing does the parent folder +//! open with `xdg-open`, which is spawned without waiting so the app never freezes until the file +//! manager window closes. + +/// `file://` URI for `ShowItems`: every byte outside the unreserved set (and `/`) is +/// percent-encoded, so spaces and non-ASCII names survive the D-Bus call. +pub(crate) fn file_uri(path: &str) -> String { + const HEX: &[u8; 16] = b"0123456789ABCDEF"; + let mut out = String::with_capacity(path.len().saturating_add(7)); + out.push_str("file://"); + for &byte in path.as_bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => out.push(char::from(byte)), + _ => { + out.push('%'); + out.push(HEX.get(usize::from(byte >> 4)).map_or('0', |&c| char::from(c))); + out.push(HEX.get(usize::from(byte & 0xF)).map_or('0', |&c| char::from(c))); + } + } + } + out +} + +/// `ShowItems` on the running file manager (Linux: `zbus` is a Linux dependency). Managers +/// without `FileManager1` answer with an error and the caller falls back to `xdg-open`. +#[cfg(target_os = "linux")] +fn show_items(uris: &[String]) -> Result<(), String> { + let connection = zbus::blocking::connection::Builder::session() + .map_err(|e| e.to_string())? + .method_timeout(std::time::Duration::from_secs(2)) + .build() + .map_err(|e| e.to_string())?; + let proxy = + zbus::blocking::Proxy::new(&connection, "org.freedesktop.FileManager1", "/org/freedesktop/FileManager1", "org.freedesktop.FileManager1") + .map_err(|e| e.to_string())?; + let startup_id = ""; + proxy.call::<_, _, ()>("ShowItems", &(uris, startup_id)).map_err(|e| e.to_string()) +} + +#[cfg(not(target_os = "linux"))] +fn show_items(_: &[String]) -> Result<(), String> { + Err("no FileManager1 on this system".into()) +} + +/// Opens `dir` with `xdg-open` without waiting for it; the child is reaped on a thread so no +/// zombie is left behind. +fn xdg_open_dir(dir: &str) -> Result<(), String> { + let mut child = std::process::Command::new("xdg-open").arg(dir).spawn().map_err(|e| format!("xdg-open: {e}"))?; + std::thread::spawn(move || { + let _ = child.wait(); + }); + Ok(()) +} + +/// Reveals one path: a folder opens, a file is selected in its folder, falling back to opening +/// the folder. +pub(crate) fn reveal_one(path: &str) -> Result<(), String> { + let p = std::path::Path::new(path); + if p.is_dir() { + return xdg_open_dir(path); + } + if show_items(std::slice::from_ref(&file_uri(path))).is_ok() { + return Ok(()); + } + let dir = p.parent().map(|d| d.to_string_lossy().to_string()).filter(|d| !d.is_empty()).unwrap_or_else(|| ".".into()); + xdg_open_dir(&dir) +} + +/// Reveals several files: one `ShowItems` call selects them all in one window; without the +/// service, the first file's folder opens, as a single reveal does. +pub(crate) fn reveal_files(paths: &[String]) -> Result<(), String> { + let Some(first) = paths.first() else { return Err("no photo selected".into()) }; + if paths.len() > 1 { + let uris: Vec = paths.iter().map(|path| file_uri(path)).collect(); + if show_items(&uris).is_ok() { + return Ok(()); + } + } + reveal_one(first) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn file_uris_encode_for_show_items() { + assert_eq!(file_uri("/photos/IMG_0001.CR3"), "file:///photos/IMG_0001.CR3"); + assert_eq!(file_uri("/home/Me/My Photos/IMG 1.jpg"), "file:///home/Me/My%20Photos/IMG%201.jpg"); + assert_eq!(file_uri("/photos/café-étude.jpg"), "file:///photos/caf%C3%A9-%C3%A9tude.jpg"); + assert_eq!(file_uri("/photos/a#b%c.jpg"), "file:///photos/a%23b%25c.jpg"); + } + + #[test] + fn revealing_nothing_is_an_error() { + assert!(reveal_files(&[]).is_err()); + } +} diff --git a/apps/web/src/web.rs b/apps/web/src/web.rs index 369a483c44..566bd46a62 100644 --- a/apps/web/src/web.rs +++ b/apps/web/src/web.rs @@ -241,6 +241,7 @@ fn services(originals: Originals, backend: Option, files: Files, frozen lcc_codecs::encode_png(&lcc_codecs::EncodeImage::rgba8(img), &lcc_codecs::EncodeMeta::default()).unwrap_or_default() })), reveal: None, + reveal_many: None, log_file: None, open_with: None, open_all_with: None, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b15c090a25..07b6f03343 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -569,6 +569,8 @@ pub type PngEncode = Box Vec>; pub type PickFolder = Box Option>; /// Reveal a file in the system file manager (Finder / Explorer / the folder on Linux). pub type RevealFn = Box Result<(), String>>; +/// Shows several files at once in the system file manager, selected in one window. +pub type RevealManyFn = Box Result<(), String>>; /// Open a URL in the user's browser. /// Starts listing (or copying) the device's camera roll; the channel answers with the photos' /// paths, or why there are none (permission denied, …). `Err` when it could not start (Android). @@ -725,6 +727,9 @@ pub struct Services { pub png: Option, /// Show a file in the system file manager (desktop only). pub reveal: Option, + /// Show several files selected in one file-manager window (Linux `FileManager1.ShowItems`); + /// None where the host reveals only one (macOS `open -R`, Windows `explorer /select`). + pub reveal_many: Option, /// The host's current log file (`/logs/.log`), which Help ▸ Open Log /// Folder reveals (#260). None where no log is kept: the web, `--memory`, `_NO_PREFS`. pub log_file: Option, diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rs index a652aa3ecb..a1b51cd1b1 100644 --- a/crates/ui-egui/src/menubar.rs +++ b/crates/ui-egui/src/menubar.rs @@ -2225,6 +2225,50 @@ mod tests { assert_eq!(run_item(&mut app, "app.openLogFolder", Value::Null).unwrap_err(), "no file manager"); } + /// Upstream #4653: Show in Finder reveals the whole selection where the host selects several + /// files at once (`reveal_many`), and the active photo where it reveals one. + #[test] + fn show_in_finder_reveals_the_selection() { + let dir = lcc_testkit::TempDir::new("lc-ui-reveal"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let o = lcc_engine::export::ExportOptions { format: lcc_engine::export::ExportFormat::Png, ..Default::default() }; + for (name, base) in [("one.png", 0usize), ("two.png", 40)] { + let img = lcc_raster::Rgba8::from_fn(16, 12, |x, y| [(x * 7 + base) as u8, (y * 11) as u8, 50, 255]); + std::fs::write(dir.join(name), lcc_engine::export::encode_image(&img, &o).unwrap()).unwrap(); + } + let mut photos = LccApp::new(lcc_engine::Session::new().with_fs(), Default::default()); + photos.session.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let ids: Vec = photos.session.catalog.photos().map(|p| p.id.0).collect(); + assert_eq!(ids.len(), 2); + photos.session.execute("library.select", &json!({"ids": ids})).unwrap(); + // a demo scene has no file to reveal + let mut demo = app(); + assert!(run_item(&mut demo, "app.showInFinder", Value::Null).is_err()); + assert!(!crate::menus::ui_enabled(&demo, "app.showInFinder")); + // several files at once where the host supports it + let shown = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let captured = shown.clone(); + photos.services.reveal_many = Some(Box::new(move |paths: &[String]| { + captured.lock().unwrap().extend(paths.iter().cloned()); + Ok(()) + })); + assert!(crate::menus::ui_enabled(&photos, "app.showInFinder")); + let r = run_item(&mut photos, "app.showInFinder", Value::Null).unwrap(); + assert_eq!(shown.lock().unwrap().len(), 2, "{r}"); + assert_eq!(r["paths"].as_array().map(Vec::len), Some(2)); + // without it, one photo is revealed, as before + let single = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let one = single.clone(); + photos.services.reveal_many = None; + photos.services.reveal = Some(Box::new(move |p: &str| { + one.lock().unwrap().push(p.to_string()); + Ok(()) + })); + run_item(&mut photos, "app.showInFinder", Value::Null).unwrap(); + assert_eq!(single.lock().unwrap().len(), 1); + } + #[test] fn find_missing_and_locate() { let dir = lcc_testkit::TempDir::new("lc-ui-missing"); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index dcfd082090..3ec137d132 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -3728,7 +3728,7 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option crate::control::export_active(app, p), "photo.renderToDng" => return crate::render_dng_task::start(app, p), "photo.updateDngPreview" => return crate::dng_update_task::start(app, p), - "app.showInFinder" => show_in_finder(app), + "app.showInFinder" => show_in_finder(app, p), "app.showInFolders" => show_in_folders(app, p.get("id").and_then(Value::as_u64).map(lcc_catalog::PhotoId)), "app.openLogFolder" => open_log_folder(app), "app.website" | "app.github" | "app.help" | "app.feedback" | "app.discord" => { @@ -3817,12 +3817,12 @@ pub fn ui_enabled(app: &LccApp, id: &str) -> bool { }) } "app.showInFinder" => { - app.services.reveal.is_some() + (app.services.reveal.is_some() || app.services.reveal_many.is_some()) && app .session - .active() - .and_then(|id| app.session.catalog.photo(id)) - .is_some_and(|p| matches!(p.source, lcc_engine::catalog::Source::File { .. })) + .selected() + .iter() + .any(|id| app.session.catalog.photo(*id).is_some_and(|p| matches!(p.source, lcc_engine::catalog::Source::File { .. }))) } "app.showInFolders" => show_in_folders_enabled(app, None), "app.openSamModelFolder" => app.session.segmenter.dir.is_some() && app.services.open_with.is_some(), @@ -4005,13 +4005,33 @@ fn open_log_folder(app: &mut LccApp) -> Result { Ok(json!({"path": path})) } -/// Reveal the active photo's original in the system file manager. -fn show_in_finder(app: &mut LccApp) -> Result { - let id = app.session.active().ok_or("no photo selected")?; - let path = match app.session.catalog.photo(id).map(|p| p.source.clone()) { - Some(lcc_engine::catalog::Source::File { path }) => path, - _ => return Err("this photo has no file (demo scene)".into()), +/// Reveal the selected photos' originals (`ids`/`id`, or the selection) in the system file +/// manager. Where the host selects several files in one window (`reveal_many`, Linux) every file +/// is shown; otherwise the active photo, or the first with a file (adapted from upstream #4653). +fn show_in_finder(app: &mut LccApp, p: &Value) -> Result { + let ids = app.session.targets(p).map_err(|e| e.to_string())?; + if ids.is_empty() { + return Err("no photo selected".into()); + } + let file_of = |app: &LccApp, id: lcc_catalog::PhotoId| match app.session.catalog.photo(id).map(|photo| &photo.source) { + Some(lcc_engine::catalog::Source::File { path }) => Some(path.clone()), + _ => None, }; + let paths: Vec = ids.iter().filter_map(|id| file_of(app, *id)).collect(); + if paths.is_empty() { + return Err("this photo has no file (demo scene)".into()); + } + if let Some(reveal_many) = app.services.reveal_many.as_mut() { + reveal_many(&paths)?; + return Ok(json!({"path": paths.first(), "paths": paths})); + } + let path = app + .session + .active() + .and_then(|id| file_of(app, id)) + .filter(|active| paths.contains(active)) + .or_else(|| paths.into_iter().next()) + .ok_or("no photo selected")?; let reveal = app.services.reveal.as_mut().ok_or("not available here")?; reveal(&path)?; Ok(json!({"path": path})) diff --git a/docs/manual-site/src/content/docs/platforms/desktop.mdx b/docs/manual-site/src/content/docs/platforms/desktop.mdx index b0842780aa..4a978270cb 100644 --- a/docs/manual-site/src/content/docs/platforms/desktop.mdx +++ b/docs/manual-site/src/content/docs/platforms/desktop.mdx @@ -16,6 +16,7 @@ import { Aside } from '@astrojs/starlight/components'; | FreeBSD | `.tar.gz`; the release job is currently disabled | | RISC-V | not shipped | +- **Photo ▸ File ▸ Show in Finder** (`Ctrl+R`) shows the original in the file manager. On Linux it selects the file in the window (every selected photo at once) through the desktop's file-manager service, and where there is none it opens the folder; the app keeps working while that window is open. - Linux packages install a desktop entry, file types and a camera (PTP) udev rule. AppImage and Flatpak users add the rule by hand for tethering. - Flatpak can reach the network and the Pictures folder only; widen with a Flatpak override if you keep photos elsewhere. diff --git a/docs/whats-new/2026-11-29-linux-reveal-selects.md b/docs/whats-new/2026-11-29-linux-reveal-selects.md new file mode 100644 index 0000000000..557e6f95ac --- /dev/null +++ b/docs/whats-new/2026-11-29-linux-reveal-selects.md @@ -0,0 +1,2 @@ +### Show in Finder selects the files on Linux +- On Linux, **Show in Finder** now selects the photo in the file manager, and every selected photo at once, instead of only opening its folder. Where the file manager can't do that, the folder opens as before, and the app no longer freezes until that window is closed. From fd173060727ae201dfe874414e0b0871e65d2ce4 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:43:01 +1100 Subject: [PATCH 012/112] upstream #1704: Original and DNG exports follow the metadata setting Adapted from upstream #1704 (9495ad303, 711a90e6f; hand-ported, export.rs has diverged). The Original sidecar and a raw-data DNG's XMP packet only honoured "Remove location info"; under metadata none/copyright/ allExceptCamera they still carried title, caption, creator, keywords, capture time, location and rating. New MetadataPolicy::restrict / includes_location / name (extended for the fork's CopyrightContact policy and extra IPTC fields); sidecar_packet_with takes the policy. An Original whose file embeds metadata the policy leaves out is refused (read with lcc_meta::try_extract, which already walks PSD/HEIF/JXL in the fork and fails closed on malformed PSDs, replacing upstream's codec detour). Checked: upstream tests metadata_policy_holds_for_original_and_dng_exports and original_psd_export_refuses_embedded_metadata_excluded_by_policy pass, with the existing remove_location tests. Manual: output/export-metadata-watermark.mdx Sources: storytold/lightcraft #1704 Co-authored-by: Gert Pellin Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/export.rs | 69 ++++++++++- crates/engine/src/sidecar.rs | 18 ++- crates/engine/src/tests_export.rs | 111 ++++++++++++++++++ .../docs/output/export-metadata-watermark.mdx | 1 + ...6-11-29-export-original-metadata-policy.md | 4 + 5 files changed, 195 insertions(+), 8 deletions(-) create mode 100644 docs/whats-new/2026-11-29-export-original-metadata-policy.md diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 5b1c94f274..e584248530 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -761,6 +761,55 @@ impl MetadataPolicy { _ => None, } } + + /// `m` with only what this policy embeds (adapted from upstream #1704). Technical fields (dimensions, + /// orientation, software) are always kept: they describe the file, not the photo or the photographer. + pub fn restrict(self, m: &Metadata) -> Metadata { + let mut out = m.clone(); + if self == Self::All { + return out; + } + // camera, lens and capture settings + (out.make, out.model, out.serial_number) = (None, None, None); + (out.lens_make, out.lens_model, out.lens_serial_number, out.lens_spec) = (None, None, None, None); + (out.exposure_time, out.f_number, out.iso, out.focal_length, out.focal_length_35mm) = (None, None, None, None, None); + (out.flash, out.exposure_bias, out.exposure_program, out.metering_mode, out.white_balance) = (None, None, None, None, None); + (out.stabilization, out.focus, out.fuji_recipe) = (None, None, None); + if self == Self::AllExceptCamera { + return out; + } + // everything but the copyright info (and, under "copyright and contact", the creator's contact) + (out.capture_time, out.gps, out.title, out.headline, out.caption) = (None, None, None, None, None); + (out.description_writer, out.category, out.alt_text, out.extended_description) = (None, None, None, None); + (out.sublocation, out.city, out.state, out.country, out.country_code) = (None, None, None, None, None); + (out.keywords, out.hierarchical_keywords, out.regions) = (Vec::new(), Vec::new(), Vec::new()); + (out.supplemental_categories, out.subject_code) = (Vec::new(), Vec::new()); + (out.rating, out.label) = (None, None); + if self != Self::CopyrightContact { + out.contact = Default::default(); + } + if matches!(self, Self::Copyright | Self::CopyrightContact) { + return out; + } + (out.artist, out.copyright, out.copyright_marked, out.usage_terms, out.copyright_url) = (None, None, None, None, None); + out + } + + /// Whether this policy embeds where the photo was taken. + pub fn includes_location(self) -> bool { + matches!(self, Self::All | Self::AllExceptCamera) + } + + /// The setting's name as options and presets spell it. + pub fn name(self) -> &'static str { + match self { + Self::All => "all", + Self::AllExceptCamera => "allExceptCamera", + Self::Copyright => "copyright", + Self::CopyrightContact => "copyrightContact", + Self::None => "none", + } + } } /// Transfer curve of an HDR AVIF export (`hdrTransfer`): PQ (absolute, SDR white at 203 cd/m²) or @@ -2452,6 +2501,8 @@ enum Work { lossy_edge: Option, /// The original must not carry a location ([`removes_location`]). remove_location: bool, + /// The original must not carry metadata this policy leaves out. + policy: MetadataPolicy, label: String, size: (usize, usize), /// The photo's camera-profile choice (`profile.camera`): a DNG carries the colour the photo renders with. @@ -2564,7 +2615,8 @@ pub(crate) fn prepare_guarded( camera: p.develop.profile.camera.clone(), path: path.clone(), read: session.media.file_bytes.clone(), - packet: crate::sidecar::sidecar_packet_with(p, &session.catalog, removes_location(p, &session.catalog, o)), + packet: crate::sidecar::sidecar_packet_with(p, &session.catalog, removes_location(p, &session.catalog, o), o.metadata), + policy: o.metadata, dng, quality: o.quality, lossy_edge: o.resize.is_some().then(|| { @@ -2949,7 +3001,7 @@ impl PreparedExport { }) } - Work::File { path, read, packet, dng, quality, lossy_edge, label, size, remove_location, camera } => { + Work::File { path, read, packet, dng, quality, lossy_edge, label, size, remove_location, policy, camera } => { let bytes = match &read { Some(r) => r(&path)?, None => std::fs::read(&path).map_err(|e| format!("{path}: {e}"))?, @@ -2974,6 +3026,19 @@ impl PreparedExport { )); } } + // copied byte for byte, so its own metadata can't be filtered: refuse one that embeds what the + // metadata setting leaves out (fail closed when it can't be read) + if policy != MetadataPolicy::All { + let embedded = lcc_meta::try_extract(&bytes).map_err(|e| { + format!("{label}: can't read the metadata of the original file ({e}), so it can't be copied unchanged; export as JPEG or TIFF instead") + })?; + if policy.restrict(&embedded) != embedded { + return Err(format!( + "{label}: an original file is copied unchanged, and this one embeds metadata that the \"{}\" metadata setting leaves out; export as JPEG or TIFF instead", + policy.name() + )); + } + } return Ok(Exported { file_name, bytes, diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 6125d39e29..b7475c492a 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -801,17 +801,22 @@ const ORIENTATION_SPAN: u64 = 1 << 20; /// The sidecar packet for a photo; the colour label is written by its name in `cat` (custom /// label names included, as other editors do). pub fn sidecar_packet(p: &Photo, cat: &lcc_catalog::Catalog) -> String { - sidecar_packet_with(p, cat, false) + sidecar_packet_with(p, cat, false, crate::export::MetadataPolicy::All) } -/// [`sidecar_packet`], without any location (GPS, sublocation, city, state, country) when -/// `remove_location` is set (an export with "Remove location info"). -pub fn sidecar_packet_with(p: &Photo, cat: &lcc_catalog::Catalog, remove_location: bool) -> String { - packet(p, cat, remove_location, true) +/// [`sidecar_packet`] for an export: only the metadata `policy` includes, and without any location +/// (GPS, sublocation, city, state, country) when `remove_location` is set ("Remove location info"). +/// The edits and the flag are always written: they are what the packet is for. (Adapted from upstream #1704.) +pub fn sidecar_packet_with(p: &Photo, cat: &lcc_catalog::Catalog, remove_location: bool, policy: crate::export::MetadataPolicy) -> String { + packet_for(p, cat, remove_location, true, policy) } /// [`sidecar_packet_with`]; the GPS position is left out unless `gps` is set. fn packet(p: &Photo, cat: &lcc_catalog::Catalog, remove_location: bool, gps: bool) -> String { + packet_for(p, cat, remove_location, gps, crate::export::MetadataPolicy::All) +} + +fn packet_for(p: &Photo, cat: &lcc_catalog::Catalog, remove_location: bool, gps: bool, policy: crate::export::MetadataPolicy) -> String { let nz = |s: &str| (!s.trim().is_empty()).then(|| s.to_string()); // Names in `dc:subject`, paths in `lr:hierarchicalSubject` (`keywords::to_file`). let keywords = lcc_catalog::keywords::to_file(&p.meta.keywords); @@ -846,7 +851,8 @@ fn packet(p: &Photo, cat: &lcc_catalog::Catalog, remove_location: bool, gps: boo gps: p.meta.gps.filter(|_| gps).map(|(latitude, longitude)| lcc_meta::Gps { latitude, longitude, altitude: None }), ..Default::default() }; - let mut meta = meta; + let mut meta = policy.restrict(&meta); + let remove_location = remove_location || !policy.includes_location(); if remove_location { (meta.sublocation, meta.city, meta.state, meta.country, meta.country_code, meta.gps) = (None, None, None, None, None, None); } diff --git a/crates/engine/src/tests_export.rs b/crates/engine/src/tests_export.rs index 2d3797c5bc..77c14326ae 100644 --- a/crates/engine/src/tests_export.rs +++ b/crates/engine/src/tests_export.rs @@ -2053,3 +2053,114 @@ fn jpeg_with_extended_gps() -> Vec { out.extend(&jpeg[2..]); out } + +/// The metadata setting holds for the file-copying formats too (#1505): the original's sidecar +/// and the DNG's packet carry only what it includes, and an original that embeds metadata it +/// leaves out is refused rather than copied. +#[test] +fn metadata_policy_holds_for_original_and_dng_exports() { + let dir = temp_dir("export-policy"); + let raw = dir.join("Raw.dng"); + std::fs::write(&raw, synthetic_dng_with(None, Default::default())).unwrap(); + // a scan without any metadata of its own, and a JPEG whose EXIF names the camera + let img = lcc_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 8) as u8, (y * 10) as u8, 90, 255]); + let scan = dir.join("Scan.jpg"); + std::fs::write(&scan, lcc_codecs::encode_jpeg(&lcc_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &Default::default()).unwrap()) + .unwrap(); + let jpg = dir.join("Cam.jpg"); + let cam = lcc_meta::Metadata { make: Some("Maker".into()), model: Some("Body".into()), ..Default::default() }; + let exif = lcc_meta::write_exif(&cam); + let meta = lcc_codecs::EncodeMeta { exif: Some(&exif), ..Default::default() }; + std::fs::write(&jpg, lcc_codecs::encode_jpeg(&lcc_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap()).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [raw.to_string_lossy(), scan.to_string_lossy(), jpg.to_string_lossy()]})).unwrap(); + let id = |s: &Session, n: &str| s.catalog.photos().find(|p| p.file_name == n).unwrap().id; + let (rid, sid, jid) = (id(&s, "Raw.dng"), id(&s, "Scan.jpg"), id(&s, "Cam.jpg")); + s.execute( + "photo.setMeta", + &json!({"ids": [rid.0, sid.0], "title": "Dune", "caption": "Evening", "creator": "Sam", "copyright": "© Sam", "keywords": ["sand"], "city": "Paris", "gps": [48.85, 2.35]}), + ) + .unwrap(); + let opts = |f: &str, policy: &str| ExportOptions::from_json(&json!({"format": f, "metadata": policy})); + let side = |e: &crate::export::Exported| lcc_meta::parse_xmp(std::str::from_utf8(&e.sidecars[0].1).unwrap()).unwrap().metadata; + + // the scan's original with its sidecar, the raw as a DNG with the packet inside + for (format, pid) in [("original", sid), ("dng", rid)] { + let get = |s: &mut Session, policy: &str| { + let e = export_photo(s, pid, &opts(format, policy), 1).unwrap(); + if format == "original" { side(&e) } else { lcc_meta::extract(&e.bytes) } + }; + for policy in ["all", "allExceptCamera"] { + let m = get(&mut s, policy); + assert_eq!(m.title.as_deref(), Some("Dune"), "{format} {policy}"); + assert!(m.city.is_some() && m.gps.is_some() && m.keywords == ["sand"], "{format} {policy}: {m:?}"); + assert_eq!(m.copyright.as_deref(), Some("© Sam")); + } + let m = get(&mut s, "copyright"); + assert_eq!((m.copyright.as_deref(), m.artist.as_deref()), (Some("© Sam"), Some("Sam")), "{format}"); + assert!(m.title.is_none() && m.caption.is_none() && m.keywords.is_empty(), "{format}: {m:?}"); + assert!(m.city.is_none() && m.gps.is_none() && m.rating.is_none(), "{format}: {m:?}"); + let m = get(&mut s, "none"); + assert!(m.copyright.is_none() && m.artist.is_none() && m.title.is_none() && m.gps.is_none(), "{format}: {m:?}"); + assert!(m.keywords.is_empty() && m.city.is_none(), "{format}: {m:?}"); + } + // the sidecar keeps the edits whatever the policy + let e = export_photo(&mut s, sid, &opts("original", "none"), 1).unwrap(); + assert!(lcc_meta::parse_xmp(std::str::from_utf8(&e.sidecars[0].1).unwrap()).unwrap().lc_settings.is_some()); + + // an original naming its camera (a JPEG's EXIF, a raw's own tags): copied under "all", + // refused when the camera must go + for pid in [jid, rid] { + assert!(export_photo(&mut s, pid, &opts("original", "all"), 1).is_ok()); + for policy in ["allExceptCamera", "copyright", "none"] { + let err = export_photo(&mut s, pid, &opts("original", policy), 1).err().unwrap(); + assert!(err.contains("copied unchanged") && err.contains(policy) && err.contains("export as JPEG"), "{err}"); + } + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// A PSD's EXIF and XMP live in its image resources, which the generic metadata reader doesn't +/// walk: the Original guards read them through the codec, so a PSD that embeds what the metadata +/// setting leaves out (or a location to remove) is refused, not copied (#1505 review). +#[test] +fn original_psd_export_refuses_embedded_metadata_excluded_by_policy() { + let dir = temp_dir("export-psd-policy"); + let src = dir.join("Private.psd"); + let img = lcc_raster::Rgba8::from_fn(8, 6, |x, y| [(x * 20) as u8, (y * 30) as u8, 90, 255]); + let m = lcc_meta::Metadata { + make: Some("Procedural Camera".into()), + model: Some("Test Body".into()), + artist: Some("Private Creator".into()), + title: Some("Private Title".into()), + gps: Some(lcc_meta::Gps { latitude: 48.85, longitude: 2.35, altitude: None }), + ..Default::default() + }; + let exif = lcc_meta::write_exif(&m); + let xmp = lcc_meta::write_xmp(&m, None); + let meta = lcc_codecs::EncodeMeta { exif: Some(&exif), xmp: Some(&xmp), ..Default::default() }; + let bytes = lcc_codecs::encode_psd(&lcc_codecs::EncodeImage::rgba8(&img), &meta).unwrap(); + std::fs::write(&src, &bytes).unwrap(); + // a PSD without any metadata of its own + let plain = dir.join("Plain.psd"); + std::fs::write(&plain, lcc_codecs::encode_psd(&lcc_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap()).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy(), plain.to_string_lossy()]})).unwrap(); + let id = |s: &Session, n: &str| s.catalog.photos().find(|p| p.file_name == n).unwrap().id; + let (pid, plain_id) = (id(&s, "Private.psd"), id(&s, "Plain.psd")); + let opts = |policy: &str, remove: bool| ExportOptions::from_json(&json!({"format": "original", "metadata": policy, "removeLocation": remove})); + + let e = export_photo(&mut s, pid, &opts("all", false), 1).unwrap(); + assert_eq!(e.bytes, bytes, "copied unchanged"); + for policy in ["none", "copyright", "allExceptCamera"] { + let err = export_photo(&mut s, pid, &opts(policy, false), 1).err().unwrap_or_else(|| panic!("{policy}: the PSD was copied")); + assert!(err.contains("copied unchanged") && err.contains(policy) && err.contains("export as JPEG"), "{err}"); + } + let err = export_photo(&mut s, pid, &opts("all", true), 1).err().unwrap(); + assert!(err.contains("can't remove the location"), "{err}"); + // nothing embedded: nothing to refuse + for policy in ["none", "copyright", "allExceptCamera"] { + assert!(export_photo(&mut s, plain_id, &opts(policy, true), 1).is_ok(), "{policy}"); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/manual-site/src/content/docs/output/export-metadata-watermark.mdx b/docs/manual-site/src/content/docs/output/export-metadata-watermark.mdx index aab0dfd245..c4fa1db4d6 100644 --- a/docs/manual-site/src/content/docs/output/export-metadata-watermark.mdx +++ b/docs/manual-site/src/content/docs/output/export-metadata-watermark.mdx @@ -12,6 +12,7 @@ import { Aside } from '@astrojs/starlight/components'; ## Metadata - **All**, **No camera**, **Copyright**, **Copyright & Contact**, **None**. - **Remove location info** strips GPS. An original copied byte for byte is refused when it embeds GPS or place names, or when its metadata cannot be fully checked (a cut-short PNG or WebP, an over-limit XMP packet), with JPEG or TIFF offered instead. +- The **Metadata** choice holds for **Original** and **DNG** too: the sidecar of an original and the XMP inside a DNG carry only what it includes (the edits always go along). An original whose own file embeds metadata the choice leaves out (its camera, for anything but **All**) is refused rather than copied, with JPEG or TIFF offered instead. ## Watermarking - **Watermark** checkbox with a live preview on the photo. diff --git a/docs/whats-new/2026-11-29-export-original-metadata-policy.md b/docs/whats-new/2026-11-29-export-original-metadata-policy.md new file mode 100644 index 0000000000..afeb8bd042 --- /dev/null +++ b/docs/whats-new/2026-11-29-export-original-metadata-policy.md @@ -0,0 +1,4 @@ +### Original and DNG exports follow the metadata setting + +- An Original export's sidecar and a DNG's embedded XMP now carry only the metadata the **Metadata** choice includes; under **None** they no longer leak the title, creator, keywords or location. +- An original whose own file embeds metadata the choice leaves out is refused, with JPEG or TIFF offered instead. From 027178033c511e258a5661b0a5c9a81090b20aaa Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:45:31 +1100 Subject: [PATCH 013/112] upstream #1261: positive Paint vignette blends toward white Adapted from upstream #1261 (fixes upstream #905): Paint Overlay is now a flat overlay in both directions (toward 0 for negative Amount, toward 1 for positive). Color and Highlight Priority are unchanged. Render change, positive Paint only: before it was the Color lift, c + (1-c)*a*t*0.85, so the style tabs rendered identically; now c*(1-w) + w with w = a*t. Mid grey 0.18 at amount 100, full falloff: 0.877 -> 1.0 linear. Every other style/sign is bit-identical (same code). New test paint_overlay_vignette_lifts_a_corner_toward_white (corner >8 codes brighter than Color). cargo xtask sil: 9 passed. clippy -D warnings and lcc-pipeline lib tests green (tests_local_curve::a_global_drag... is flaky under parallel load, passes alone with and without this change). Fork's separate PaintOverlay==Color issue (upstream #980) not touched. Manual: develop/effects.mdx Co-authored-by: Vikram Bhaskaran Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/finish.rs | 15 +++++++++------ crates/pipeline/src/tests.rs | 17 +++++++++++++++++ .../src/content/docs/develop/effects.mdx | 2 +- .../2026-11-29-paint-vignette-white.md | 2 ++ 4 files changed, 29 insertions(+), 7 deletions(-) create mode 100644 docs/whats-new/2026-11-29-paint-vignette-white.md diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 5ddc5ca43f..fc2bb8b302 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -1067,16 +1067,19 @@ pub(crate) fn finish_with( let t = smooth(v.start, v.start + v.width, dist); if t > 0.0 { let lum = luminance_2020(d).clamp(0.0, 1.0); - if v.amount < 0.0 { + if v.style == VignetteStyle::PaintOverlay { + // Paint is a flat overlay toward black (negative) or white (positive); Color and + // Highlight Priority stay a multiply or a lift, so the style tabs differ once Amount + // leaves 0. Adapted from upstream #1261. + let w = v.amount.abs() * t; + let toward = if v.amount < 0.0 { 0.0 } else { 1.0 }; + d = d.map(|c| c * (1.0 - w) + toward * w); + } else if v.amount < 0.0 { let mut f = 1.0 + v.amount * t; if v.style == VignetteStyle::HighlightPriority { f += (1.0 - f) * v.highlights * smooth(0.4, 1.0, lum); } - if v.style == VignetteStyle::PaintOverlay { - d = d.map(|c| c * (1.0 - (-v.amount) * t) + 0.0); - } else { - d = d.map(|c| c * f); - } + d = d.map(|c| c * f); } else if hdr { // lighten towards SDR white; never pull HDR highlights down to it d = d.map(|c| c + (1.0 - c).max(0.0) * v.amount * t * 0.85); diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index 822dbe88f4..f9bf7b47b3 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -135,6 +135,23 @@ fn resolution_independence_of_local_contrast() { assert!(err < 9.0, "mean abs error {err}"); } +#[test] +fn paint_overlay_vignette_lifts_a_corner_toward_white() { + use lcc_develop::VignetteStyle; + let src = Rgb32f::filled(48, 48, [0.18, 0.18, 0.18]); + let mut paint = DevelopSettings::default(); + paint.vignette.amount = 100.0; + paint.vignette.midpoint = 0.0; + paint.vignette.feather = 10.0; + paint.vignette.style = VignetteStyle::PaintOverlay; + let mut color = paint.clone(); + color.vignette.style = VignetteStyle::ColorPriority; + let paint_img = render(&src, &SourceInfo::default(), &paint, &RenderRequest::fit(48, 48)).image; + let color_img = render(&src, &SourceInfo::default(), &color, &RenderRequest::fit(48, 48)).image; + let corner = |img: &lcc_raster::Rgba8| img.data[0][0]; + assert!(corner(&paint_img) > corner(&color_img) + 8, "paint {} color {}", corner(&paint_img), corner(&color_img)); +} + #[test] fn crop_and_straighten_output_size() { let mut s = DevelopSettings::default(); diff --git a/docs/manual-site/src/content/docs/develop/effects.mdx b/docs/manual-site/src/content/docs/develop/effects.mdx index c935308a46..8b8cfa1dc2 100644 --- a/docs/manual-site/src/content/docs/develop/effects.mdx +++ b/docs/manual-site/src/content/docs/develop/effects.mdx @@ -12,7 +12,7 @@ import { Aside } from '@astrojs/starlight/components'; - **Texture**, **Clarity**, **Dehaze**: in Basic and in the Effects dock card. -- **Vignette**: **Vignette** amount, **Midpoint**, **Roundness**, **Feather**, **Highlights**; style **Highlight**, **Color**, **Paint**. Post-crop: it follows the crop. +- **Vignette**: **Vignette** amount, **Midpoint**, **Roundness**, **Feather**, **Highlights**; style **Highlight**, **Color**, **Paint** (Paint blends the corners toward flat black when negative, toward flat white when positive). Post-crop: it follows the crop. - **Glow**: the bright parts of the picture, spread as a halo over it (beyond Lightroom, after DaVinci Resolve's Glow effect). **Glow** is the strength; **Threshold** picks how bright a part must be to glow; **Radius** sets the halo's width (relative to the frame, so a preview matches an export); **H/V Ratio** stretches the halo one way (50 is even); **Gain** and **Gamma** shape the glow's brightness and falloff; the composite is **Screen** (gentler, the default) or **Add** (hotter); **Recovery** brings the bright regions' own detail back through the glow. - **Grain**: amount, **Size**, **Size Variation**, **Roughness**, **Clumping**, **Color**, **Response**, **Seed**. From process V7, irregular particles that do not change with the picture's size. See [Process versions](../process-versions/). - Dehaze from V3 keeps shadows from going black. diff --git a/docs/whats-new/2026-11-29-paint-vignette-white.md b/docs/whats-new/2026-11-29-paint-vignette-white.md new file mode 100644 index 0000000000..15e7efae48 --- /dev/null +++ b/docs/whats-new/2026-11-29-paint-vignette-white.md @@ -0,0 +1,2 @@ +### Paint vignette lightens toward white +- A positive **Paint** post-crop vignette now blends the corners toward flat white, as a negative one blends toward black. Before, it lifted the corners exactly like **Color**, so the two styles looked the same. From 0a4024ad05202dfc4962cb64f4361054937a3cab Mon Sep 17 00:00:00 2001 From: MarkusHammer Date: Tue, 24 Nov 2026 22:53:53 +0100 Subject: [PATCH 014/112] upstream #4729: an older process version's untouched defaults are not an edit Cherry-picked from upstream cae6cf087 (crs.rs applied cleanly; the test moved into the fork's inline crs::tests module, since the fork has no crs/tests.rs). crs:ToneCurve named "Medium Contrast" without a 2012 curve, and a raw's Sharpness 25 without ...2012 fields, are read as the old process version's defaults, not edits. Import-time interpretation only: photos already in a catalog render as before, no pipeline change. Checked: cargo test -p lcc-engine crs:: (29 passed, incl. new the_older_process_defaults_are_no_edit). Manual: none, no user-visible change in the manual's terms (docs/xmp-interop.md table updated) (cherry picked from commit cae6cf087fa20c4aa936b32eb52394cf0bbc021b) Co-authored-by: MarkusHammer Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/crs.rs | 54 ++++++++++++++++++- .../2026-11-29-older-process-defaults.md | 3 ++ docs/xmp-interop.md | 3 +- 3 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 docs/whats-new/2026-11-29-older-process-defaults.md diff --git a/crates/engine/src/crs.rs b/crates/engine/src/crs.rs index ff0613711e..dccedd5297 100644 --- a/crates/engine/src/crs.rs +++ b/crates/engine/src/crs.rs @@ -390,9 +390,14 @@ pub fn to_partial(props: &Props, target: Target) -> Value { n(o, "ParametricMidtoneSplit", "curve.split_mid"); n(o, "ParametricHighlightSplit", "curve.split_highlights"); n(o, "CurveRefineSaturation", "curve.refine_saturation"); + // Under the older process versions an untouched photo's curve is the one named "Medium + // Contrast", as Contrast 25, Blacks 5 and Brightness 50 are its sliders' defaults (read + // relative to them above): it is no edit, and our rendering has its own base contrast, so it + // is not applied. A changed curve is named otherwise ("Custom", "Strong Contrast"). + let old_default_curve = first(props, "crs:ToneCurveName").is_some_and(|n| n.eq_ignore_ascii_case("Medium Contrast")); if let Some(c) = curve(props, "crs:ToneCurve").filter(|c| c.as_array().is_some_and(|a| !a.is_empty())) { // the older single curve, used when no 2012 curve is present - if !props.contains_key("crs:ToneCurvePV2012") { + if !props.contains_key("crs:ToneCurvePV2012") && !old_default_curve { put(o, "curve.master", c); } } @@ -430,7 +435,13 @@ pub fn to_partial(props: &Props, target: Target) -> Value { n(o, "SplitToningBalance", "grading.balance"); // ---- Detail - n(o, "Sharpness", "detail.sharpen_amount"); + // An older process version's raw sharpening default (25) is an untouched photo's, like its + // tone sliders' defaults above: the photo keeps our own raw default. (Rendered files defaulted + // to 0 there, and 25 under the 2012 process is a choice: both are read as written.) + let raw = matches!(target, Target::RawAbsolute | Target::RawRelative); + if !(raw && !pv2012 && num(props, "crs:Sharpness") == Some(25.0)) { + n(o, "Sharpness", "detail.sharpen_amount"); + } n(o, "SharpenRadius", "detail.sharpen_radius"); n(o, "SharpenDetail", "detail.sharpen_detail"); n(o, "SharpenEdgeMasking", "detail.sharpen_masking"); @@ -1093,6 +1104,45 @@ mod tests { assert!(["/curve/master", "/curve/red", "/curve/green", "/curve/blue"].iter().all(|p| all.pointer(p).is_some()), "{all}"); } + /// An older-process packet (written for this test, as old DNGs, sidecars and catalogs carry it) of + /// a photo nobody edited: its sliders and raw sharpening at their old defaults and its curve named + /// as the old default one. `extra`: more attributes. + fn old_process_packet(curve_name: &str, sharpness: &str, extra: &str) -> String { + format!( + r#" + + 0, 070, 58180, 190255, 255 + "# + ) + } + + /// An untouched raw from an older process version keeps the look it is imported with (so it isn't + /// taken for an edited one, whose thumbnails need the whole raw decoded); what was changed there + /// still comes in, and so does a sharpening of 25 where it isn't that version's raw default. + #[test] + fn the_older_process_defaults_are_no_edit() { + let raw = DevelopSettings::for_raw(5000.0, 0.0); + let read = |base: &DevelopSettings, packet: String, target| apply_partial(base, &to_partial(&props(&packet), target), 1.0); + let untouched = old_process_packet("Medium Contrast", "25", ""); + assert_eq!(read(&raw, untouched.clone(), Target::RawAbsolute), raw, "an untouched older-process raw is unchanged"); + assert_eq!(read(&raw, untouched, Target::RawRelative), raw); + for changed in ["Custom", "Strong Contrast"] { + assert!(!read(&raw, old_process_packet(changed, "25", ""), Target::RawAbsolute).curve.master.is_empty(), "{changed}: the curve is read"); + } + let sharpening = |packet: String, base: &DevelopSettings, target| read(base, packet, target).detail.sharpen_amount; + assert_eq!(sharpening(old_process_packet("Medium Contrast", "50", ""), &raw, Target::RawAbsolute), 50.0, "a changed amount is read"); + let current = old_process_packet("Medium Contrast", "25", r#"crs:ProcessVersion="11.0" crs:Contrast2012="0""#); + assert_eq!(sharpening(current, &raw, Target::RawAbsolute), 25.0, "25 under the 2012 process is a choice"); + let rendered = DevelopSettings::default(); + assert_eq!( + sharpening(old_process_packet("Medium Contrast", "25", ""), &rendered, Target::Rendered), + 25.0, + "a rendered file's old default was 0" + ); + } + fn unmapped(x: &str) -> Vec { to_partial_report(&props(x), None, Target::Any, 1.5).1 } diff --git a/docs/whats-new/2026-11-29-older-process-defaults.md b/docs/whats-new/2026-11-29-older-process-defaults.md new file mode 100644 index 0000000000..8f729ab8b6 --- /dev/null +++ b/docs/whats-new/2026-11-29-older-process-defaults.md @@ -0,0 +1,3 @@ +### Untouched photos from older Lightroom process versions stay unedited + +- A photo saved under process version 2003/2010 and never edited there no longer comes in as edited: its "Medium Contrast" curve and a raw's default sharpening of 25 are read as that version's defaults, so it keeps the import look. diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 20d244a03c..d9240e9007 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -199,11 +199,12 @@ application's renderer and is ignored: the photo keeps the app's own process, th | `ParametricShadowSplit`, `ParametricMidtoneSplit`, `ParametricHighlightSplit` | `curve.split_shadows/split_mid/split_highlights` | | | `CurveRefineSaturation` | `curve.refine_saturation` | 0..100 (100 = curve saturation unchanged) | | `ToneCurvePV2012`, `ToneCurvePV2012Red/Green/Blue` | `curve.master/red/green/blue` | `"x, y"` points in 0..255 → 0..1; a straight 0→255 line = no curve; the red / green / blue curves are read only when `ToneCurvePV2012` and all three channel curves are present (Lightroom Classic ignores them otherwise: a master + red-only packet renders without the red curve) | +| `ToneCurve` (older process versions) | `curve.master` | as `ToneCurvePV2012`, read only when the packet has no `ToneCurvePV2012`; a curve named `Medium Contrast` (`ToneCurveName`) is the older process versions' untouched default, like their Contrast 25, Blacks 5 and Brightness 50, and comes in as no curve (see `Sharpness` for the other older default that isn't an edit), so an unedited photo keeps its import look | | `SplitToningShadowHue/Saturation`, `SplitToningHighlightHue/Saturation` | `grading.shadows/highlights.hue/sat` | | | `ColorGradeShadowLum`, `ColorGradeHighlightLum` | `grading.shadows/highlights.lum` | | | `ColorGradeMidtoneHue/Sat/Lum`, `ColorGradeGlobalHue/Sat/Lum` | `grading.midtones/global.*` | | | `ColorGradeBlending`, `SplitToningBalance` | `grading.blending`, `grading.balance` | | -| `Sharpness`, `SharpenRadius`, `SharpenDetail`, `SharpenEdgeMasking` | `detail.sharpen_*` | | +| `Sharpness`, `SharpenRadius`, `SharpenDetail`, `SharpenEdgeMasking` | `detail.sharpen_*` | a raw's `Sharpness` of 25 under an older process version (no `…2012` fields) is that version's untouched default and leaves our raw default in place; anywhere else 25 is read as written | | `LuminanceSmoothing`, `LuminanceNoiseReductionDetail`, `LuminanceNoiseReductionContrast` | `detail.nr_luminance/nr_detail/nr_contrast` | | | `ColorNoiseReduction`, `ColorNoiseReductionDetail`, `ColorNoiseReductionSmoothness` | `detail.nr_color/nr_color_detail/nr_color_smoothness` | | | `PostCropVignetteAmount/Midpoint/Roundness/Feather/HighlightContrast` | `vignette.amount/midpoint/roundness/feather/highlights` | | From 964f1282760336ab2c63b711249b06def6a10377 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:57:43 +1100 Subject: [PATCH 015/112] upstream #4747: skip warnings for inactive legacy XMP fields Adapted from upstream #4747 (11f91a524, 03d61a7f6; hand-applied, the fork's quiet list differs and its crs tests are inline). The unmapped report no longer warns about crs:AutoWhiteVersion, zero ChromaticAberrationR/B and Defringe, or identity ToneCurveRed/Green/Blue (ascending points with y == x from 0 to 255). Report only: sidecar detection is unchanged, so a packet with AutoWhiteVersion + HasCrop=False still resets a crop. The fork's lightroom_catalog coverage test drops AutoWhiteVersion from its expected unmapped list accordingly. Checked: cargo test -p lcc-engine crs lightroom_catalog sidecar (292 passed), incl. upstream tests legacy_optics_defaults_and_identity_channel_curves_do_not_warn and auto_white_version_preserves_an_explicit_crop_reset. Manual: none, no user-visible change Sources: storytold/lightcraft #4747 Co-authored-by: murdawkmedia <119478503+murdawkmedia@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/crs.rs | 58 ++++++++++++++++++++++++++ crates/engine/src/lightroom_catalog.rs | 4 +- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/crs.rs b/crates/engine/src/crs.rs index dccedd5297..016f43d8ca 100644 --- a/crates/engine/src/crs.rs +++ b/crates/engine/src/crs.rs @@ -628,12 +628,36 @@ pub fn to_partial_report(props: &Props, values: Option<&crate::crs_masks::Values // Point Color slots that are all empty (-1) let value_is = |k: &str, f: &dyn Fn(&[String]) -> bool| props.get(&format!("crs:{k}")).is_some_and(|v| f(v)); let empty_points = |v: &[String]| v.iter().all(|s| s.split(',').all(|n| n.trim().parse::().is_ok_and(|x| x == -1.0) || n.trim().is_empty())); + // a channel curve that is the identity: ascending points from x = 0 to 255, each with y == x (upstream #4747) + let identity_curve = |v: &[String]| { + let mut previous = None; + for point in v { + let Some((x, y)) = point.split_once(',') else { return false }; + let (Ok(x), Ok(y)) = (x.trim().parse::(), y.trim().parse::()) else { + return false; + }; + let ascending = match previous { + None => x == 0.0, + Some(prior) => x > prior, + }; + if !ascending || !(0.0..=255.0).contains(&x) || x != y { + return false; + } + previous = Some(x); + } + previous == Some(255.0) + }; let quiet = |k: &str| { k.starts_with("Enable") || k.starts_with("ToneCurveName") || k == "AutoTone" || k == "AutoGrayscaleMix" + || k == "AutoWhiteVersion" || (k == "PointColors" && value_is(k, &empty_points)) + // inactive legacy optics fields at zero, and identity channel curves (upstream #4747) + || (matches!(k, "ChromaticAberrationB" | "ChromaticAberrationR" | "Defringe") + && value_is(k, &|v| v.len() == 1 && v.iter().all(|s| s.trim().parse::().is_ok_and(|n| n == 0.0)))) + || (matches!(k, "ToneCurveRed" | "ToneCurveGreen" | "ToneCurveBlue") && value_is(k, &identity_curve)) // Point Color's variance means nothing without a used slot || (k == "ColorVariance" && (!props.contains_key("crs:PointColors") || value_is("PointColors", &empty_points))) // the lens profile's strength, written at its default (100 %) next to every profile @@ -1143,6 +1167,40 @@ mod tests { ); } + #[test] + fn legacy_optics_defaults_and_identity_channel_curves_do_not_warn() { + let attrs = r#"crs:AutoWhiteVersion="134348800" crs:ChromaticAberrationR="+0" crs:ChromaticAberrationB="0.0" crs:Defringe="0""#; + let curve = r#"0, 0255, 255"#; + assert!(unmapped(&preset_packet(attrs, curve)).is_empty()); + + let collinear = curve.replace("255, 255", "128, 128255, 255"); + assert!(unmapped(&preset_packet(attrs, &collinear)).is_empty()); + let unordered = collinear.replace("255, 255", "64, 64255, 255"); + assert_eq!(unmapped(&preset_packet(attrs, &unordered)), ["ToneCurveRed"]); + + let attrs = attrs.replace(r#"crs:Defringe="0""#, r#"crs:Defringe="1""#); + let curve = curve.replace("255, 255", "255, 220"); + assert_eq!(unmapped(&preset_packet(&attrs, &curve)), ["Defringe", "ToneCurveRed"]); + } + + #[test] + fn auto_white_version_preserves_an_explicit_crop_reset() { + let packet = r#" + + + "#; + let target = Target::RawAbsolute; + let defaults = DevelopSettings::default(); + let cropped = apply_partial(&defaults, &to_partial(&props(SIDECAR), target), 1.0); + assert_ne!(cropped.crop.geometry, defaults.crop.geometry); + + let sidecar = crate::sidecar::parse_sidecar(packet, target).unwrap(); + assert!(sidecar.warnings.is_empty()); + let Some(crate::sidecar::DevelopPatch::Partial(patch)) = sidecar.develop else { panic!("expected a crop reset") }; + assert_eq!(apply_partial(&cropped, &patch, 1.0).crop.geometry, defaults.crop.geometry); + } + fn unmapped(x: &str) -> Vec { to_partial_report(&props(x), None, Target::Any, 1.5).1 } diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 46775e432b..4879a9459c 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -2970,11 +2970,11 @@ pub(crate) mod tests { dropped.sort(); let mapped = PUBLIC_CRS_FIELDS.len() - dropped.len(); eprintln!("crs coverage: {mapped} of {} public fields map; dropped: {dropped:?}", PUBLIC_CRS_FIELDS.len()); - // No equivalent in the app: Lightroom's algorithm / tool bookkeeping (auto white version, + // No equivalent in the app: Lightroom's tool bookkeeping (auto white version is quiet since upstream #4747; // Upright's preview, centre mode and focal length: ours computes its own) and the pre-2012 // single Defringe switch. Reported as unmapped and kept in the archive. (Lens profile setup // is bookkeeping the import ignores, `crs::IGNORED`: not reported.) - let expected = ["AutoWhiteVersion", "Defringe", "UprightCenterMode", "UprightFocalLength35mm", "UprightPreview"]; + let expected = ["Defringe", "UprightCenterMode", "UprightFocalLength35mm", "UprightPreview"]; assert_eq!(dropped, expected, "{mapped} mapped"); } From d423abe829a912c583088f2b08f1a3460b8b4c8c Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:59:42 +1100 Subject: [PATCH 016/112] upstream #1736: control channel bounds the pending synthetic-event queue Chromaforge already bounds `count` (1..100) and `steps` (1..1000) per request (bounded_arg), so of upstream #1736 only the aggregate queue cap is ported, adapted: a request that would take app.synthetic past MAX_PENDING_EVENTS (4096, room for several of the largest drags) is refused before it queues anything; one lone release (ui.pointer up / ui.key up) may go one past, so a held button or key is never stuck down. Upstream's smaller per-request limits (10/50), its own parser and pointer_is_down tracking are not taken. Hostile-input test added; docs/control-protocol.md describes the limit. Checked: clippy -D warnings on lcc-ui-egui, control tests pass. Manual: docs/control-protocol.md (developer reference) Co-authored-by: Navid Zaman Khan Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control.rs | 77 +++++++++++++++++++++++++++++++++++ docs/control-protocol.md | 2 +- 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 4cf6802665..f83d85154f 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -300,6 +300,49 @@ pub(crate) fn check_gesture_numbers(method: &str, p: &Value) -> Result<(), Strin check(method, "", p) } +/// Most synthetic events that may wait in `app.synthetic` for the frames that drain them. +/// `count` and `steps` bound one request; this bounds a script that sends requests faster than +/// the app takes them, so the queue (and the time it takes to drain) can't grow without end. +/// Room for several of the largest drags (`steps` 1000 = 1003 events). Adapted from upstream #1736. +pub const MAX_PENDING_EVENTS: usize = 4096; + +/// How many synthetic events `method` with `p` queues, and whether it is a lone release (a +/// pointer `up`, a key `up`). Invalid arguments count 0: the method's own branch refuses them. +fn queued_events(method: &str, p: &Value) -> (usize, bool) { + let n = |key: &str, default: u64, range: (u64, u64)| usize::try_from(bounded_arg(p, key, default, range).unwrap_or(0)).unwrap_or(usize::MAX); + match method { + "ui.move" | "ui.hoverWidget" | "ui.text" | "ui.scroll" | "ui.zoom" | "ui.clipboard" => (1, false), + "ui.clickWidget" | "ui.click" => (n("count", 1, CLICK_COUNT).saturating_mul(2).saturating_add(1), false), + "ui.dragWidget" | "ui.drag" => (n("steps", 10, DRAG_STEPS).saturating_add(3), false), + "ui.pointer" => { + let events = p.get("events").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); + let kind = |e: &Value| e.get("kind").and_then(Value::as_str).unwrap_or("move").to_string(); + let total = events.iter().fold(0usize, |t, e| t.saturating_add(if kind(e) == "down" { 2 } else { 1 })); + (total, events.len() == 1 && events.iter().all(|e| kind(e) == "up")) + } + "ui.key" => match p.get("action").and_then(Value::as_str).unwrap_or("press") { + "press" => (2, false), + "up" => (1, true), + _ => (1, false), + }, + _ => (0, false), + } +} + +/// Refuses a request whose events would take the queue past [`MAX_PENDING_EVENTS`]. A lone +/// release may go one past it, so a held button or key is never left stuck down by a full queue. +fn event_budget(pending: usize, method: &str, p: &Value) -> Result<(), String> { + let (additional, release) = queued_events(method, p); + let cap = if release { MAX_PENDING_EVENTS.saturating_add(1) } else { MAX_PENDING_EVENTS }; + if additional == 0 || pending.saturating_add(additional) <= cap { + Ok(()) + } else { + Err(format!( + "{method}: {pending} synthetic events still pending, {additional} more would pass the limit of {MAX_PENDING_EVENTS}; wait for the app to catch up" + )) + } +} + pub fn handle(app: &mut LccApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { if let Some(o) = crate::surface::handle(app, req) { return o; @@ -312,6 +355,9 @@ pub fn handle(app: &mut LccApp, ctx: &egui::Context, req: &ControlRequest) -> Ou { return err(e); } + if let Err(e) = event_budget(app.synthetic.len(), &req.method, p) { + return err(e); + } let s = |k: &str| p.get(k).and_then(Value::as_str); let f = |k: &str| p.get(k).and_then(Value::as_f64); match req.method.as_str() { @@ -963,6 +1009,37 @@ mod hostile_gesture_tests { app } + /// Adapted from upstream #1736: requests sent faster than frames drain them can't grow the + /// queue past `MAX_PENDING_EVENTS`; a lone release still gets through, once. + #[test] + fn the_synthetic_queue_is_bounded_but_a_release_gets_through() { + let mut app = app(); + app.synthetic = vec![egui::Event::PointerMoved(egui::pos2(1.0, 1.0)); MAX_PENDING_EVENTS - 1]; + for (method, params) in [ + ("ui.click", json!({"x": 1, "y": 1})), + ("ui.drag", json!({"x": 1, "y": 1, "toX": 5, "toY": 5, "steps": 1000})), + ("ui.pointer", json!({"events": [{"kind": "down"}]})), + ("ui.key", json!({"key": "A"})), + ] { + let r = reply(&mut app, method, params); + assert_eq!(r["ok"], false, "{method}: {r}"); + assert_eq!(app.synthetic.len(), MAX_PENDING_EVENTS - 1, "{method} queued past the limit"); + } + let r = reply(&mut app, "ui.scroll", json!({"dy": 1})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.synthetic.len(), MAX_PENDING_EVENTS); + assert_eq!(reply(&mut app, "ui.move", json!({"x": 1, "y": 1}))["ok"], false); + let up = json!({"events": [{"kind": "up"}]}); + assert_eq!(reply(&mut app, "ui.pointer", up.clone())["ok"], true, "a lone release goes one past the limit"); + assert_eq!(app.synthetic.len(), MAX_PENDING_EVENTS + 1); + assert_eq!(reply(&mut app, "ui.pointer", up)["ok"], false, "but only one"); + assert_eq!(reply(&mut app, "ui.key", json!({"key": "A", "action": "up"}))["ok"], false); + assert_eq!(app.synthetic.len(), MAX_PENDING_EVENTS + 1); + // once the frames drain the queue, requests are taken again + app.synthetic.clear(); + assert_eq!(reply(&mut app, "ui.drag", json!({"x": 1, "y": 1, "toX": 5, "toY": 5, "steps": 1000}))["ok"], true); + } + #[test] fn invalid_pointer_events_reject_the_whole_batch() { let mut app = app(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 5fbafb8e12..d3c80222eb 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -120,7 +120,7 @@ filmstrip is visible. | `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `frameGaps: {hostFrameMs, gapMs, maxGapMs, maxGapHostMs}` = wall time between frames while the window had work to show (renders on their way, input), the longest since start and the host's frame time before it — a long gap with a short host frame waited outside the UI thread, e.g. presenting behind GPU work, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`, `adjustQuality` = what a slider drag renders with high quality adjustment previews on: `idle` (no drag, or the setting is off), `full`, `draft` (too slow at full quality and the slider is moving) or `settled` (too slow, but the slider holds still) — see `docs/high-quality-adjustment-previews.md`; `loupeSteps` = how the loupe showed each photo it was stepped to, measured on the frames it drew: `{steps: [{photo, anyMs, anySource, fullMs, fullSource, sharpMs, dwellMs}], current}` — ms from the step to the first frame with anything of the photo, with a full-size picture (`embedded` camera JPEG, `last` / `draft` / `cached` or `render`), and with the app's own render; `dwellMs` is how long it stayed, the latest 256 steps), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack shows it, same shape as `activity.list`; a task shows once it is 0.5 s old. Classic: in the module bar in the identity plate's place, `activity:plate`, with ✕ = `activity:cancel:` for a single task and thin bars `activity:bar:` for several; a click there or `view.activityList` opens the list `activity:list` with rows `activity:row:` and their ✕. Modern: a floating card of rows `activity:row:`, `activity:more` expands past 3. Compact: as Classic; see `docs/background-tasks.md`), `activityList` (Classic and Compact: the list of tasks is open), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied), `toasts` (the messages at the bottom centre still showing, oldest first: `{text, kind, secsLeft}`; `kind` is `message`, `error`, `action` or `sticky`; a sticky one has a `key` and no `secsLeft`), `toastAction` (the message with a button: `{text, button, command, secsLeft}`, else `null`), `osd` (the on-screen overlay pill, as `osd.state` returns it: `settings`, `shown` = `{title, value, caption, icon, ageS}` or `null`, `held`)) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | | `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?}` (`button: "right"` right-clicks) / `{id, toX?, toY?, dx?, dy?, steps?}` / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews) | -| `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points. In every pointer and scroll gesture (also `ui.clickWidget`, `ui.dragWidget`, `ui.hoverWidget`, `ui.pointer`, `ui.scroll`) a number other than `count` and `steps` must lie between −1,000,000 and 1,000,000, or the request is refused and queues nothing | +| `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points. In every pointer and scroll gesture (also `ui.clickWidget`, `ui.dragWidget`, `ui.hoverWidget`, `ui.pointer`, `ui.scroll`) a number other than `count` and `steps` must lie between −1,000,000 and 1,000,000, or the request is refused and queues nothing. At most 4096 synthetic events (pointer, key, text, scroll, zoom) wait for the frames that take them; a request that would queue past that is refused (wait and retry), except one lone release (`ui.pointer` `up`, `ui.key` `up`) so a held button or key is never left down | | `ui.pointer` | `{events: [{kind: down\|drag\|up, x, y}], alt?, shift?, cmd?}` | Gesture in normalized image coordinates (Detail view) | | `ui.key` | `{key, action?: press\|down\|repeat\|up, cmd?, shift?, alt?, ctrl?}` | Key press (default), or the key going `down` and staying held until an `up` (Space held over a `ui.pointer` drag); `repeat` is an auto-repeat while held (Space's are ignored: it is a modifier) | | `ui.text` | `{text}` | Text input | From 589ae0254760e23aab6bb3ddca581a0fa64e235b Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 13:59:48 +1100 Subject: [PATCH 017/112] upstream #1204: macOS opens photos from Finder, the Dock and Open With Hand-ported (adapted from upstream #1204, LR-IMP-DRAGDROP / issue #506): - new crates/opendocs (lcc-opendocs, L0): adds `application:openURLs:` to winit's application delegate at NSApplicationWillFinishLaunching and queues the file paths; safe API (install / set_waker / take), `// SAFETY:` on each unsafe block, no-op elsewhere. Reuses objc2 0.6.4 / objc2-app-kit 0.3.2 / objc2-foundation 0.3.2 / block2 0.6.2 already in Cargo.lock (no new crate). Named in AGENTS.md's unsafe list; registered in xtask layers. - packaging/macos/Info.plist.in declares CFBundleDocumentTypes (camera raw + the image types EXTENSIONS imports, AVIF added), LSHandlerRank Alternate. - apps/app hands opened files to the UI as dropped files, so the fork's existing drop path applies (import review / presets / face model, and library_problem::hold_dropped keeps them while no library is open). Upstream's library-problem changes (its 2nd/3rd commits) are already covered by the fork's pending_import / waiting_import handling, so they were not ported. A renderer relaunch passes queued files on as arguments. Upstream #1837 (same feature through the external `fmv-macos-events` crate's 'odoc' + 'quit' Apple-event handler) is superseded by this port and skipped: it adds a third-party unsafe dependency instead of an AGENTS.md helper crate. Checked: cargo clippy -D warnings for lcc-opendocs on aarch64-apple-darwin (cross check, incl. the macOS-only class_addMethod test) and for lcc-opendocs + lcc-app on Windows; cargo test -p lcc-opendocs and the app's opened-file / relaunch tests; xtask layers, parity, notes, brand check. Not run on a Mac. Manual: docs/manual-site/src/content/docs/library/import.mdx, docs/manual/import-export.md Co-authored-by: Marco Arnulfo Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 +- Cargo.lock | 12 ++ Cargo.toml | 1 + apps/app/Cargo.toml | 2 + apps/app/src/main.rs | 39 +++- apps/app/src/window_gpu.rs | 8 +- crates/opendocs/Cargo.toml | 26 +++ crates/opendocs/src/lib.rs | 198 ++++++++++++++++++ .../2026-11-29-macos-open-from-finder.md | 3 + .../src/content/docs/library/import.mdx | 1 + docs/manual/import-export.md | 3 + docs/parity-checklist.md | 2 +- .../2026-11-29-macos-open-from-finder.md | 4 + packaging/macos/Info.plist.in | 43 ++++ xtask/src/layers.rs | 1 + 15 files changed, 340 insertions(+), 6 deletions(-) create mode 100644 crates/opendocs/Cargo.toml create mode 100644 crates/opendocs/src/lib.rs create mode 100644 docs/changelog/unreleased/2026-11-29-macos-open-from-finder.md create mode 100644 docs/whats-new/2026-11-29-macos-open-from-finder.md diff --git a/AGENTS.md b/AGENTS.md index 1b7f0cc785..9698e9530a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,7 +62,8 @@ never a panic. Never ship a panic path; fix crashes before building on them. Thi (JNI VM/activity adoption), `crates/winspool` (Win32 print spooler), `crates/winmsi` (`MsiEnumClientsW` + `MsiGetComponentPathW` for the updater), `crates/winjob` (a kill-on-close job object, so the Windows CLI launcher's app ends with it), `crates/firstclick` (macOS: replaces `acceptsFirstMouse:` on winit's window view, - for the background-click setting), `crates/libraw` (FFI into its C shim over LibRaw, opt-in, see Non-negotiables), and `apps/android`'s `#[unsafe(no_mangle)] android_main`. Every other + for the background-click setting), `crates/opendocs` (macOS: adds `application:openURLs:` to winit's application + delegate, so photos opened from Finder, the Dock or Open With reach the app), `crates/libraw` (FFI into its C shim over LibRaw, opt-in, see Non-negotiables), and `apps/android`'s `#[unsafe(no_mangle)] android_main`. Every other production crate root has `#![forbid(unsafe_code)]`. New unsafe need → isolated, well-tested helper crate: `// SAFETY:` everywhere, safe API, safe fallback, and a line here naming it. - Input-derived numbers are hostile: `get()` not `[i]`/`[a..b]`; checked/saturating math; no division by zero, diff --git a/Cargo.lock b/Cargo.lock index daa5a75e4f..09bf4f5d67 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4581,6 +4581,7 @@ dependencies = [ "lcc-gpu", "lcc-gpumem", "lcc-hdrmeta", + "lcc-opendocs", "lcc-pipeline", "lcc-preview", "lcc-raster", @@ -5331,6 +5332,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "lcc-opendocs" +version = "26.48.2" +dependencies = [ + "block2 0.6.2", + "log", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "lcc-pdf" version = "26.48.2" diff --git a/Cargo.toml b/Cargo.toml index 4dfdbec683..3cb3b0a486 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ lcc-winspool = { path = "crates/winspool" } lcc-winmsi = { path = "crates/winmsi" } lcc-winjob = { path = "crates/winjob" } lcc-firstclick = { path = "crates/firstclick" } +lcc-opendocs = { path = "crates/opendocs" } lcc-android-host = { path = "crates/android-host" } lcc-peer = { path = "crates/peer" } lcc-sync = { path = "crates/sync" } diff --git a/apps/app/Cargo.toml b/apps/app/Cargo.toml index 93a96481b9..3c36b5f3be 100644 --- a/apps/app/Cargo.toml +++ b/apps/app/Cargo.toml @@ -38,6 +38,8 @@ libraw = ["lcc-engine/libraw", "lcc-cli/libraw"] # the command-line tool, run when the program is started as `` (`main`); its features follow # the app's, so a build without HEIF leaves it out of the CLI too lcc-cli = { path = "../cli", default-features = false } +# photos macOS hands the app from Finder, the Dock or Open With (a no-op elsewhere) +lcc-opendocs = { workspace = true } # reading the Logi plugin package's version (`logi_plugin`) and the control-surface e2e test lcc-surface = { workspace = true } lcc-brand = { workspace = true } diff --git a/apps/app/src/main.rs b/apps/app/src/main.rs index 1e662e23fb..2be6893f43 100644 --- a/apps/app/src/main.rs +++ b/apps/app/src/main.rs @@ -169,6 +169,8 @@ impl eframe::App for App { } fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { self.0.raw_input_hook(raw); + // after the hook, which replaces `dropped_files` with the control channel's drops + raw.dropped_files.extend(opened_as_dropped(lcc_opendocs::take())); } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { self.0.perf.host_frame_ms = frame.info().cpu_usage.map(|s| f64::from(s) * 1000.0); @@ -1246,6 +1248,25 @@ fn launch_imports(args: &[String]) -> LaunchArgs { launch_imports_in(args, cwd.as_deref(), home.as_deref()) } +/// A file the system asked the app to open (`lcc_opendocs`; macOS: Finder, the Dock, Open With), +/// handed to the UI as a file dropped on the window: imported like a drop, or held while no library +/// is open yet (`library_problem::hold_dropped`). Adapted from upstream #1204. +#[derive(Debug)] +struct OpenedFile(std::path::PathBuf); + +impl egui::DroppedFile for OpenedFile { + fn path(&self) -> &std::path::Path { + &self.0 + } + fn bytes(&self) -> Result, String> { + std::fs::read(&self.0).map_err(|e| e.to_string()) + } +} + +fn opened_as_dropped(paths: Vec) -> impl Iterator { + paths.into_iter().map(|p| std::sync::Arc::new(OpenedFile(p.into())) as egui::DroppedFileHandle) +} + /// What the launch arguments ask for: files and folders to import, a library to open (a library's `catalog.snap` /// or folder, double-clicked in the file manager), and a notice for each argument /// left alone. @@ -1645,11 +1666,17 @@ fn run() -> eframe::Result { b.with_x11(); })); } + // macOS hands photos opened from Finder, the Dock or Open With to the running app, not as + // arguments; installed before the event loop exists, so the ones it was launched with arrive too + lcc_opendocs::install(); let started = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { eframe::run_native( lcc_brand::DISPLAY_NAME, options, Box::new(move |cc| { + // opened files that arrive from now on wake the window, which takes them as drops + let opened_ctx = cc.egui_ctx.clone(); + lcc_opendocs::set_waker(move || opened_ctx.request_repaint()); // the window's renderer is up (eframe calls this after creating it) win_files_app.started(window_renderer); came_up_app.store(true, std::sync::atomic::Ordering::Relaxed); @@ -1866,7 +1893,7 @@ fn run() -> eframe::Result { let started = started.unwrap_or_else(|_| Err(eframe::Error::AppCreation("the window's renderer panicked while starting".into()))); if let Err(e) = &started { // the renderer never came up: start again, which tries the next one in the chain - if window_gpu::relaunch_after_failure(&win_files) { + if window_gpu::relaunch_after_failure(&win_files, lcc_opendocs::take()) { log::error!("{} could not open its window with {}: {e}; trying the next renderer", lcc_brand::DISPLAY_NAME, window_renderer.name()); return Ok(()); } @@ -1926,6 +1953,16 @@ fn startup_failed(error: &str, log_file: Option<&std::path::Path>) { mod tests { use super::*; + /// Files the system asks the app to open (macOS, `lcc_opendocs`) reach the UI as dropped files, + /// path for path and in order. + #[test] + fn opened_files_are_handed_over_as_drops() { + let dropped: Vec<_> = opened_as_dropped(vec!["/tmp/a b.arw".into(), "/tmp/c.heic".into()]).collect(); + let paths: Vec<_> = dropped.iter().map(|f| f.path().to_path_buf()).collect(); + assert_eq!(paths, [std::path::PathBuf::from("/tmp/a b.arw"), std::path::PathBuf::from("/tmp/c.heic")]); + assert_eq!(opened_as_dropped(Vec::new()).count(), 0); + } + fn os(args: &[&str]) -> Vec { args.iter().map(std::ffi::OsString::from).collect() } diff --git a/apps/app/src/window_gpu.rs b/apps/app/src/window_gpu.rs index f7039a4a0e..b4637eb19f 100644 --- a/apps/app/src/window_gpu.rs +++ b/apps/app/src/window_gpu.rs @@ -464,7 +464,7 @@ pub fn check_pipeline(device: &wgpu::Device, build: impl FnOnce(&wgpu::Device)) /// The start failed (error or panic) before the window's renderer came up: start the app again, /// which then tries the next renderer. `false`: not relaunched (it came up, nothing written to /// disk, or the retries are used up). -pub fn relaunch_after_failure(files: &Files) -> bool { +pub fn relaunch_after_failure(files: &Files, opened: Vec) -> bool { if !files.armed() { return false; } @@ -479,6 +479,8 @@ pub fn relaunch_after_failure(files: &Files) -> bool { log::warn!("window: the renderer failed to start; starting again with the next one"); std::process::Command::new(exe) .args(std::env::args_os().skip(1)) + // files the system handed this launch (macOS: opened from Finder), so the next one imports them + .args(opened) .env(lcc_brand::env_var(RETRY_VAR), (tries + 1).to_string()) .spawn() .map_err(|e| log::error!("window: could not start again: {e}")) @@ -543,7 +545,7 @@ mod tests { // nothing written without a settings folder let none = Files::new(None); none.arm(dx); - assert!(!none.armed() && !relaunch_after_failure(&none)); + assert!(!none.armed() && !relaunch_after_failure(&none, Vec::new())); let _ = std::fs::remove_dir_all(&d); } @@ -633,7 +635,7 @@ mod tests { let f = Files::new(Some(d.clone())); assert_eq!(f.take_failed(), None); f.arm(WindowRenderer::Glow); - assert!(!f.armed() && !relaunch_after_failure(&f)); + assert!(!f.armed() && !relaunch_after_failure(&f, Vec::new())); let _ = std::fs::remove_dir_all(&d); } diff --git a/crates/opendocs/Cargo.toml b/crates/opendocs/Cargo.toml new file mode 100644 index 0000000000..542a9fa750 --- /dev/null +++ b/crates/opendocs/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "lcc-opendocs" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Files macOS hands the app (L0): photos opened from Finder, the Dock or another app's Open With. One of the crates allowed `unsafe` (adds one Objective-C method); does nothing elsewhere." + +# Opts out of the workspace lints only to keep `unsafe_code = "deny"` overridable for the single +# `macos` module below, as in crates/firstclick; every other crate root has `#![forbid(unsafe_code)]`. +# See AGENTS.md. +[lints.rust] +unsafe_code = "deny" + +[lints.clippy] +dbg_macro = "warn" +todo = "warn" + +[dependencies] +log = { workspace = true } + +[target.'cfg(target_os = "macos")'.dependencies] +# All already in the tree through winit and muda: no new crate, only features. +block2 = "0.6" +objc2 = { workspace = true } +objc2-app-kit = { workspace = true } +objc2-foundation = { workspace = true, features = ["block2", "NSEnumerator", "NSNotification", "NSOperation", "NSString", "NSURL"] } diff --git a/crates/opendocs/src/lib.rs b/crates/opendocs/src/lib.rs new file mode 100644 index 0000000000..2fc7a6b391 --- /dev/null +++ b/crates/opendocs/src/lib.rs @@ -0,0 +1,198 @@ +//! Files the operating system asks the app to open: on macOS, a photo opened from Finder (Open +//! With, a drop on the Dock icon), from another app (Photo Mechanic's "Open with", Files) or with +//! `open -a photo.arw`. +//! +//! macOS doesn't pass these on the command line: AppKit hands them to the application delegate's +//! `application:openURLs:`, and when the delegate has no such method it asks `NSDocumentController`, +//! which fails with " cannot open files in the … format" because the app isn't an +//! `NSDocument` app. winit 0.30's delegate doesn't implement the method, so [`install`] adds it to +//! the delegate's class when the app is about to finish launching: after winit set the delegate and +//! before AppKit delivers the files the app was launched with. The handler queues the paths and +//! calls the waker ([`set_waker`]); the app collects them with [`take`]. +//! +//! Adapted from upstream #1204 (LR-IMP-DRAGDROP, issue #506), which followed VectorCraft's +//! `open_documents.rs`; Apple's AppKit (`application(_:open:)`) and Objective-C runtime +//! (`class_addMethod`) documentation. +//! +//! Adding a method to another crate's Objective-C class has no safe API: this is one of the crates +//! allowed `unsafe` (AGENTS.md), here inside `macos`. Its API +//! is safe, and elsewhere [`install`] does nothing and [`take`] stays empty. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::sync::{Mutex, OnceLock, PoisonError}; + +/// Paths that arrived and haven't been taken yet. +static PENDING: Mutex> = Mutex::new(Vec::new()); +/// Called when paths arrive (unset until the window exists; the app takes them on its first frame). +static WAKER: OnceLock> = OnceLock::new(); + +/// Receive the files the operating system asks the app to open from now on. Call once, before the +/// event loop runs. Does nothing except on macOS, where such files come as arguments elsewhere. +pub fn install() { + #[cfg(target_os = "macos")] + macos::install(); +} + +/// Call `wake` whenever files arrive, e.g. to repaint the window that takes them. Only the first +/// waker set is kept. +pub fn set_waker(wake: impl Fn() + Send + Sync + 'static) { + let _ = WAKER.set(Box::new(wake)); +} + +/// The paths that arrived since the last call, in order. +pub fn take() -> Vec { + std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner)) +} + +/// Queue `paths` and wake the app (called by the macOS handler; elsewhere only by the tests). +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +fn arrived(paths: impl IntoIterator) { + let len = { + let mut pending = PENDING.lock().unwrap_or_else(PoisonError::into_inner); + pending.extend(paths); + pending.len() + }; + if len > 0 + && let Some(wake) = WAKER.get() + { + wake(); + } +} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod macos { + use std::ptr::NonNull; + + use block2::RcBlock; + use objc2::MainThreadMarker; + use objc2::runtime::{AnyClass, AnyObject, Imp, Sel}; + use objc2::sel; + use objc2_app_kit::{NSApplication, NSApplicationWillFinishLaunchingNotification}; + use objc2_foundation::{NSArray, NSNotification, NSNotificationCenter, NSURL}; + + /// The handler's signature, as the Objective-C runtime calls it. + type OpenUrls = extern "C-unwind" fn(&AnyObject, Sel, &AnyObject, &NSArray); + + pub fn install() { + let block = RcBlock::new(|_: NonNull| add_to_delegate()); + // SAFETY: the name is AppKit's notification constant; no object or queue filter, so the + // block runs on the posting thread (AppKit posts it on the main thread). The notification + // center keeps the registration (and the block) for the life of the app; the returned + // observer token is only needed to unregister, which we never do. + unsafe { + NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock( + Some(NSApplicationWillFinishLaunchingNotification), + None, + None, + &block, + ); + } + } + + /// `application:openURLs:` on the application delegate's class (winit's). + fn add_to_delegate() { + let Some(mtm) = MainThreadMarker::new() else { return }; + let Some(delegate) = NSApplication::sharedApplication(mtm).delegate() else { + log::warn!("no application delegate: photos opened from Finder or other apps won't arrive"); + return; + }; + if !add_open_urls(AsRef::::as_ref(&*delegate).class()) { + log::warn!("the application delegate already handles open-document events"); + } + } + + /// Add [`open_urls`] to `class` as `application:openURLs:`. False when the class already has + /// that method (it is then left as it is). + pub(crate) fn add_open_urls(class: &AnyClass) -> bool { + let handler: OpenUrls = open_urls; + // SAFETY: `Imp` is the untyped form of a method implementation; the Objective-C runtime + // calls it with the arguments the type encoding declares, which match `open_urls`: no + // return value (`v`), the receiver (`@`), the selector (`:`), the application (`@`) and the + // URL array (`@`). `class_addMethod` copies the encoding string and never replaces an + // existing method; the class is a registered class, alive for the life of the process. + let added = unsafe { + let imp = std::mem::transmute::(handler); + objc2::ffi::class_addMethod(std::ptr::from_ref(class).cast_mut(), sel!(application:openURLs:), imp, c"v@:@@".as_ptr()) + }; + added.as_bool() + } + + /// Queue the files among `urls`. Never panics: it runs inside AppKit. + extern "C-unwind" fn open_urls(_delegate: &AnyObject, _cmd: Sel, _app: &AnyObject, urls: &NSArray) { + // Only file URLs: macOS 27 turns an https URL's path into a file path too. + super::arrived(urls.iter().filter(|u| u.isFileURL()).filter_map(|u| u.to_file_path()).map(|p| p.to_string_lossy().into_owned())); + } +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::*; + + /// The queue is global: tests that fill it take turns. + static QUEUE: Mutex<()> = Mutex::new(()); + static WOKEN: AtomicUsize = AtomicUsize::new(0); + + fn turn() -> std::sync::MutexGuard<'static, ()> { + let guard = QUEUE.lock().unwrap_or_else(PoisonError::into_inner); + let _ = take(); + guard + } + + #[test] + fn files_wait_until_taken_and_wake_the_app() { + let _turn = turn(); + set_waker(|| { + WOKEN.fetch_add(1, Ordering::SeqCst); + }); + let before = WOKEN.load(Ordering::SeqCst); + arrived(["/tmp/a.arw".to_string(), "/tmp/b c.jpg".to_string()]); + assert_eq!(WOKEN.load(Ordering::SeqCst), before + 1); + arrived(["/tmp/d.heic".to_string()]); + assert_eq!(take(), ["/tmp/a.arw", "/tmp/b c.jpg", "/tmp/d.heic"]); + assert!(take().is_empty()); + // nothing arrived: nothing to wake the app for + let before = WOKEN.load(Ordering::SeqCst); + arrived(Vec::new()); + assert_eq!(WOKEN.load(Ordering::SeqCst), before); + } + + #[cfg(not(target_os = "macos"))] + #[test] + fn install_elsewhere_queues_nothing() { + let _turn = turn(); + install(); + assert!(take().is_empty()); + } + + /// The method `install` adds, called the way AppKit calls it: only file URLs are queued, and a + /// class that already has the method keeps its own. + #[cfg(target_os = "macos")] + #[test] + #[allow(unsafe_code)] + fn an_open_urls_message_queues_the_files() { + use objc2::rc::Retained; + use objc2::runtime::{AnyObject, ClassBuilder, NSObject}; + use objc2::{ClassType, msg_send, sel}; + use objc2_foundation::{NSArray, NSString, NSURL}; + + let _turn = turn(); + let class = ClassBuilder::new(c"LccOpenDocsTestDelegate", NSObject::class()).unwrap().register(); + assert!(!class.responds_to(sel!(application:openURLs:))); + assert!(macos::add_open_urls(class)); + assert!(!macos::add_open_urls(class), "a second add leaves the method alone"); + + let web = NSURL::URLWithString(&NSString::from_str("https://example.com/a.jpg")).unwrap(); + let urls = + NSArray::from_retained_slice(&[NSURL::from_file_path("/tmp/a b.arw").unwrap(), web, NSURL::from_file_path("/tmp/c.heic").unwrap()]); + // SAFETY: `class` is an NSObject subclass (`new` returns a retained instance), and it now + // has `application:openURLs:` with the signature the message is sent with. + let delegate: Retained = unsafe { msg_send![class, new] }; + let app = NSObject::new(); + let () = unsafe { msg_send![&*delegate, application: &*app, openURLs: &*urls] }; + assert_eq!(take(), ["/tmp/a b.arw", "/tmp/c.heic"]); + } +} diff --git a/docs/changelog/unreleased/2026-11-29-macos-open-from-finder.md b/docs/changelog/unreleased/2026-11-29-macos-open-from-finder.md new file mode 100644 index 0000000000..3f030dcc30 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-29-macos-open-from-finder.md @@ -0,0 +1,3 @@ +## Library + +- macOS: photos opened from Finder (Open With, the Dock icon) or another app are imported; before, macOS said the app could not open them. diff --git a/docs/manual-site/src/content/docs/library/import.mdx b/docs/manual-site/src/content/docs/library/import.mdx index 259bab27f1..c5483ea2ee 100644 --- a/docs/manual-site/src/content/docs/library/import.mdx +++ b/docs/manual-site/src/content/docs/library/import.mdx @@ -19,6 +19,7 @@ import Shot from '../../../components/Shot.astro'; - **Rename** with a template and live example; the **Tags** picker inserts `{name}`, `{seq:4}`, `{date:…}`, `{camera}`, `{lens}`, `{iso}` and more. - **Apply on import**: develop preset, metadata preset (copyright, creator), keywords, a collection, and **Batch edits** sliders (Light, Vibrance, Clarity, Sharpening, Grain, Vignette) as one History step. - **Drag and drop**: files or folders dropped on the window open the review (or import at once with **Settings ▸ Import ▸ Import dropped photos without review**). A card says what the drop will do. +- **From Finder or another app (macOS)**: a photo opened with **Open With ▸ **, dropped on the app's Dock icon, or opened with `open -a` from another app arrives like a file dropped on the window, whether the app was running or not. The app is offered for camera raws and the image types it imports, but never becomes the default app for them. - **Import presets**: save and reuse the dialog's settings (**Save as Preset**). - **Raw defaults** (**Settings**): built-in, a preset, or per camera model; applied to new photos. - Raw, JPEG, TIFF, PNG, WebP, JPEG XL, PSD and DNG are read. Unreadable files are reported, never crash the import; a batch the library couldn't add (a save that failed) is reported as "not added", with the reason, not as unreadable. Images over 512 megapixels are refused with a message giving their size and the limit. Previews are built in the background after import. diff --git a/docs/manual/import-export.md b/docs/manual/import-export.md index 278f3a7158..1ae78e26d1 100644 --- a/docs/manual/import-export.md +++ b/docs/manual/import-export.md @@ -15,6 +15,9 @@ File → Import Photos… (`Cmd+Shift+I`) or Import from Folder… (`library.imp memory held by a drive that stopped responding, a failed conversion) is imported as its raw copy and listed by reason in File → More Imports → Import Warnings…; Convert Photo to DNG… converts it later. - Apply a develop preset, a metadata preset, keywords, and add the photos to a collection. +- On macOS, photos opened from Finder (Open With, a drop on the Dock icon) or another app arrive like files dropped + on the window, at launch or while the app runs. The app is offered for camera raws and the image types it imports, + never as their default app. - Files on several drives, cards or shares are read side by side. Each drive starts with as many readers as before and then finds its own number: it gets more while more readers read it faster (an SSD, a RAID or a fast card), fewer when they slow it down (a hard drive seeking between files), one drive trying a change at a time, never fewer than diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 1f345d21f1..6f5fd42534 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -145,7 +145,7 @@ under the UI command that wraps it (a no-op error); the UI command now wins. | LR-HDR-EDIT | HDR editing | P2 | ✅ | `cmd:develop.hdr`, `crates/pipeline/src/tone.rs` (`ToneMap::hdr`), `crates/pipeline/src/tests_hdr.rs`, `crates/gpu/src/wgsl/finish.wgsl` | HDR tone map (SDR curve through the midtones, highlights up to the headroom limit) and float HDR render, on the GPU too (linear float output up to the peak, the CPU as oracle: `hdr_renders_match` in `crates/gpu/tests/it/equivalence.rs`; gap 14); shown on HDR displays in every view (LR-VIEW-HDR-DISPLAY); `crs:HDREditMode`, `HDRMaxValue`, `SDRBlend` and the SDR sliders are read from XMP | | LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:dialog.import`, `cmd:file.addPhotos`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with 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), preset, keywords; the folder scan runs on a background thread with a progress window and 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, with a progress window and Cancel; one undo step. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lcc_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/app/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`); a rating, reject flag and colour label embedded in the file (XMP / EXIF) are kept on import, a sidecar still winning (`crates/engine/src/tests_import.rs`); the review (and `library.importPreview`: `truncated`, `skipped {unreadable, unsupported}`) 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 not counted; upstream #2944); `library.import` returns the same `skipped` counts (upstream #4321) | | 2026-10-12 | minor | LR-IMP-FORMATS: Mamiya MEF decodes from sensor data and is imported (`vendor/mef.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 (import N items, review a folder for import, import N presets, open the face model; a note to close the open dialog first when one is open); dropped photo files and folders open the import review as File ▸ Import does, or, with Settings ▸ Import ▸ Import dropped photos without review (off by default; from OneSlips), are added at once on a worker thread with the library's import settings (the web build imports both at once); 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-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`, `crates/opendocs/src/lib.rs`, `packaging/macos/Info.plist.in` | while files are dragged over the window a veil and a card say what dropping does (import N items, review a folder for import, import N presets, open the face model; a note to close the open dialog first when one is open); dropped photo files and folders open the import review as File ▸ Import does, or, with Settings ▸ Import ▸ Import dropped photos without review (off by default; from OneSlips), are added at once on a worker thread with the library's import settings (the web build imports both at once); 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; macOS: photos opened from Finder (Open With, a drop on the Dock icon), from another app or with `open -a` arrive as dropped files (upstream #1204; the bundle offers the app for camera raws and the image types it imports, never as the default app); 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`, `crates/ui-egui/src/import.rs`, `crates/ui-egui/src/headless.rs` | Only library records (including Recently Deleted) count as existing content; a copy merely browsed in Local does not block importing another path. A browsed file at the same path is offered by the scan (not "In library") and promoted with its edits, unless a library match or an earlier promotion already has its content; background import batches deduplicate promoted files too. The review offers such a file only when adding in place (copy and move would add it where it is), and notes that keywords and presets apply to new files only. | | LR-IMP-RECIPE | Batch edits during import | P2 | ✅ | `cmd:library.import` (`recipe`), `cmd:preset.saveRecipe`, `crates/ui-egui/src/import.rs`, `crates/ui-egui/src/import_screen.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 (`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-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/import.rs`) | diff --git a/docs/whats-new/2026-11-29-macos-open-from-finder.md b/docs/whats-new/2026-11-29-macos-open-from-finder.md new file mode 100644 index 0000000000..c664d4dc3b --- /dev/null +++ b/docs/whats-new/2026-11-29-macos-open-from-finder.md @@ -0,0 +1,4 @@ +### Open photos from Finder on macOS + +- Open With, a drop on the Dock icon, or `open -a` from another app now hands the photos to the app, which imports them like files dropped on its window, at launch or while it runs. Before, macOS said the app couldn't open files in that format. +- The app is offered for camera raws and the image types it imports, but never becomes their default app. diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in index 750ca8240c..e4050782ae 100644 --- a/packaging/macos/Info.plist.in +++ b/packaging/macos/Info.plist.in @@ -72,6 +72,49 @@ NSHumanReadableCopyright Copyright © {{vendor}}. MIT. + + CFBundleDocumentTypes + + + CFBundleTypeName + Camera Raw Image + CFBundleTypeRole + Viewer + LSHandlerRank + Alternate + LSItemContentTypes + + public.camera-raw-image + + + + CFBundleTypeName + Image + CFBundleTypeRole + Viewer + LSHandlerRank + Alternate + LSItemContentTypes + + public.jpeg + public.heic + public.heif + public.avif + public.tiff + public.png + org.webmproject.webp + public.jpeg-xl + com.adobe.photoshop-image + com.compuserve.gif + com.microsoft.bmp + + + + UTExportedTypeDeclarations diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 8d0f33a3b1..423e7cdf26 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -48,6 +48,7 @@ pub const TABLE: &[(&str, Class)] = &[ ("winmsi", Class::Layer(0)), ("winjob", Class::Layer(0)), ("firstclick", Class::Layer(0)), + ("opendocs", Class::Layer(0)), // LibRaw (C++, opt-in) behind a C shim: the raw mosaic for `lcc_engine::raw_decoder` ("libraw", Class::Layer(0)), ("android-host", Class::Layer(0)), From 530afa63228d3bc0dbefc7c4d761bc2a19864e80 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:09:33 +0100 Subject: [PATCH 018/112] upstream #4633: proof: preserve the selected ICC profile path Cherry-picked from upstream 24f5683eb (crate names renamed to lcc_). proof::load no longer trims the path it is given, so a profile whose file name ends in whitespace (here a no-break space) loads instead of failing with "not found". The path comes from a file picker, so it needs no trimming. Checked: cargo test -p lcc-engine proof (new loads_an_icc_path_with_trailing_whitespace passes on Windows). Manual: none, no user-visible change (cherry picked from commit 24f5683eb80beaba90e9e1d567be31e5269951d0) Co-authored-by: Mex <44814932+MMexicann@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/proof.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/proof.rs b/crates/engine/src/proof.rs index 046ff0a85b..3584bba3b3 100644 --- a/crates/engine/src/proof.rs +++ b/crates/engine/src/proof.rs @@ -16,7 +16,6 @@ pub struct ProofProfile { /// Load the profile at `path` for proofing with `intent`, simulating paper and ink or not. pub fn load(path: &str, intent: ProofIntent, paper_ink: bool) -> Result { - let path = path.trim(); let meta = std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?; if meta.len() > MAX_PROFILE_BYTES as u64 { return Err(format!("{path}: too large for an ICC profile")); @@ -45,6 +44,17 @@ mod tests { use super::*; use lcc_codecs::space::NamedSpace; + #[test] + fn loads_an_icc_path_with_trailing_whitespace() { + let profile = lcc_codecs::icc::write_named(NamedSpace::DisplayP3); + let path = std::env::temp_dir().join(format!("lc-proof-{}.icc\u{00a0}", std::process::id())); + std::fs::write(&path, &profile).unwrap(); + let result = load(path.to_str().unwrap(), ProofIntent::Perceptual, false); + std::fs::remove_file(&path).unwrap(); + let expected = from_bytes(&profile, ProofIntent::Perceptual, false, "x").unwrap(); + assert_eq!(result.unwrap().id, expected.id); + } + #[test] fn profiles_register_by_content_and_options() { let p3 = lcc_codecs::icc::write_named(NamedSpace::DisplayP3); From 0519c8df8c57d573fd7c0ee9155b7c90072782df Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:07:59 +1100 Subject: [PATCH 019/112] upstream #4568: reject malformed saved-set slots keyword.saveSet validates every supplied slot (string, null, array of strings) before replacing or renaming a saved set; malformed input leaves the saved sets intact. Cherry-picked dec2f6c8be + 95bfc3dc6f (new tests in crates/engine/tests/keyword_set_inputs.rs). Checked: clippy + tests for lcc-engine. Sources: storytold/lightcraft#4568 Manual: none, no user-visible change Co-authored-by: Terra854 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/keywords.rs | 19 ++++--- crates/engine/tests/keyword_set_inputs.rs | 61 +++++++++++++++++++++++ 2 files changed, 74 insertions(+), 6 deletions(-) create mode 100644 crates/engine/tests/keyword_set_inputs.rs diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index 858f3ff4b0..c58f49b59d 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -286,14 +286,21 @@ pub fn specs() -> Vec { ), None => None, }; - // keywords not given: the renamed set's own, else the current nine - let keywords = if p.get("keywords").is_some() { - slots(&strs(p, "keywords")) - } else { - match renames.and_then(|at| s.keyword_sets.get(at)) { + // Validate every supplied slot before replacing or renaming the saved set. + let invalid_keywords = || bad("keyword.saveSet", "`keywords` must be a string, null or an array of strings"); + let keywords = match p.get("keywords") { + Some(Value::String(k)) => slots(std::slice::from_ref(k)), + Some(Value::Array(a)) => { + let typed = a.iter().map(|k| k.as_str().map(str::to_string).ok_or_else(invalid_keywords)).collect::>>()?; + slots(&typed) + } + Some(Value::Null) => Vec::new(), + Some(_) => return Err(invalid_keywords()), + // keywords not given: the renamed set's own, else the current nine + None => match renames.and_then(|at| s.keyword_sets.get(at)) { Some(x) => x.keywords.clone(), None => current_keywords(s), - } + }, }; let set = KeywordSet { name: name.clone(), keywords }; match renames { diff --git a/crates/engine/tests/keyword_set_inputs.rs b/crates/engine/tests/keyword_set_inputs.rs new file mode 100644 index 0000000000..13116b5b42 --- /dev/null +++ b/crates/engine/tests/keyword_set_inputs.rs @@ -0,0 +1,61 @@ +//! Invalid keyword-set slots must not erase a set or shift its keyboard shortcuts. + +use lcc_engine::Session; +use serde_json::{Value, json}; + +fn sets(s: &mut Session) -> Value { + s.execute("keyword.sets", &json!({})).unwrap() +} + +fn named(s: &mut Session, name: &str) -> Value { + sets(s)["sets"].as_array().unwrap().iter().find(|set| set["name"] == name).unwrap()["keywords"].clone() +} + +#[test] +fn malformed_keyword_slots_leave_saved_sets_and_current_set_unchanged() { + let mut s = Session::new(); + s.execute("keyword.saveSet", &json!({"name": "Saved", "keywords": ["first", "", "third"]})).unwrap(); + s.execute("keyword.saveSet", &json!({"name": "Other", "keywords": ["other"]})).unwrap(); + let before = sets(&mut s); + for keywords in [ + json!(true), + json!(7), + json!(1.5), + json!({"name": "replacement"}), + json!(["first", null, "third"]), + json!(["first", false, "third"]), + json!(["first", 7, "third"]), + json!(["first", {}, "third"]), + json!(["first", [], "third"]), + ] { + for mut params in [json!({"name": "Saved"}), json!({"name": "Renamed", "replace": "Saved"}), json!({"name": "New", "new": true})] { + params["keywords"] = keywords.clone(); + let error = s.execute("keyword.saveSet", ¶ms).unwrap_err().to_string(); + assert!(error.contains("`keywords`"), "{params}: {error}"); + assert_eq!(sets(&mut s), before, "{params}: saved or current sets changed"); + } + } +} + +#[test] +fn valid_keyword_slot_forms_keep_their_existing_meaning() { + let mut s = Session::new(); + s.execute("keyword.saveSet", &json!({"name": "Text", "keywords": " Parent | Child "})).unwrap(); + assert_eq!(named(&mut s, "Text"), json!(["Parent|Child"]), "text stays a single slot"); + s.execute("keyword.saveSet", &json!({"name": "Slots", "keywords": [" Alpha ", "", "Été", "été", "Last", ""]})).unwrap(); + assert_eq!(named(&mut s, "Slots"), json!(["Alpha", "", "Été", "", "Last"])); + + s.execute("keyword.saveSet", &json!({"name": "Inherited"})).unwrap(); + assert_eq!(named(&mut s, "Inherited"), named(&mut s, "Slots"), "omission inherits the current slots"); + s.execute("keyword.saveSet", &json!({"name": "Renamed", "replace": "Text"})).unwrap(); + assert_eq!(named(&mut s, "Renamed"), json!(["Parent|Child"]), "rename without keywords keeps the renamed set's slots"); + + s.execute("keyword.saveSet", &json!({"name": "Slots", "keywords": null})).unwrap(); + assert_eq!(named(&mut s, "Slots"), json!([]), "explicit null still clears"); + s.execute("keyword.saveSet", &json!({"name": "Renamed", "keywords": []})).unwrap(); + assert_eq!(named(&mut s, "Renamed"), json!([]), "an empty list still clears"); + + let many: Vec = (1..=10).map(|n| n.to_string()).collect(); + s.execute("keyword.saveSet", &json!({"name": "Nine", "keywords": many})).unwrap(); + assert_eq!(named(&mut s, "Nine"), json!(many[..9]), "the nine-slot limit is unchanged"); +} From 71e926cecc55b8cb23d73ee67c38456575e89064 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:08:01 +1100 Subject: [PATCH 020/112] upstream #4572: report oversized cell pages without overflow Layout::validate formats the 1-based page as u64, so a hostile page u32::MAX no longer overflows. Hand-ported (test module layout differs); upstream test added as page_overflow_tests. Checked: clippy, test. Sources: storytold/lightcraft#4572 Manual: none, no user-visible change Co-authored-by: Mex <44814932+MMexicann@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/print/layout.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/print/layout.rs b/crates/engine/src/print/layout.rs index afff879ed5..8c783d4e9f 100644 --- a/crates/engine/src/print/layout.rs +++ b/crates/engine/src/print/layout.rs @@ -632,7 +632,7 @@ impl Layout { return Err(format!("duplicate cell id {}", c.id)); } if c.page >= self.pages { - return Err(format!("cell {} is on page {} but the layout has {} pages", c.id, c.page + 1, self.pages)); + return Err(format!("cell {} is on page {} but the layout has {} pages", c.id, u64::from(c.page) + 1, self.pages)); } self.check_rect(&c.rect, area)?; } @@ -1409,3 +1409,23 @@ mod tests { } } } + +#[cfg(test)] +mod page_overflow_tests { + use super::{Layout, Style}; + + #[test] + fn oversized_cell_pages_are_errors_without_changing_the_layout() { + let mut source = Layout { style: Style::PicturePackage, ..Default::default() }; + let id = source.add_cell(2.0, 2.0).unwrap(); + source.validate().unwrap(); + for (page, shown) in [(1, "2"), (u32::MAX, "4294967296")] { + let mut value = serde_json::to_value(&source).unwrap(); + value["cells"][0]["page"] = serde_json::json!(page); + let mut imported: Layout = serde_json::from_value(value).unwrap(); + let before = imported.clone(); + assert_eq!(imported.validate().unwrap_err(), format!("cell {id} is on page {shown} but the layout has 1 pages")); + assert_eq!(imported, before, "a rejected page changed the layout"); + } + } +} From 9ddf4c3d5e6d547d0fb04b78e354ab3ff1c99051 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:08:03 +1100 Subject: [PATCH 021/112] upstream #4622: skip photo effects when there is no photo compose_with returns after the backdrop when there is no photo: no shadow, stroke or frame drawn around nothing. Applied upstream diff cleanly with its test. Checked: clippy, lcc-slideshow tests. Sources: storytold/lightcraft#4622 Manual: none, no user-visible change Co-authored-by: Mex <44814932+MMexicann@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/slideshow/src/compose.rs | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/slideshow/src/compose.rs b/crates/slideshow/src/compose.rs index 6ea02cd2b1..89ca02bf98 100644 --- a/crates/slideshow/src/compose.rs +++ b/crates/slideshow/src/compose.rs @@ -252,6 +252,9 @@ pub fn compose_with( }); } behind(&mut out, &l); + if !has_photo { + return (out, l); + } // cast shadow: a blurred rectangle (separable: the product of two blurred steps) if let Some((r, sigma)) = l.shadow { let op = s.shadow_opacity as f32; @@ -273,9 +276,7 @@ pub fn compose_with( if l.frame != l.visible { fill(&mut out, &l.frame, s.stroke_color); } - if has_photo { - draw_image(&mut out, photo, &l.photo, &l.cell, 1.0); - } + draw_image(&mut out, photo, &l.photo, &l.cell, 1.0); (out, l) } @@ -487,6 +488,24 @@ mod tests { assert_eq!(px(&img, 100, 50), GREEN, "and the photo covers it"); } + #[test] + fn an_empty_photo_draws_the_backdrop_without_a_frame() { + let s = SlideSettings { + backdrop_color: RED, + margin_left: 0.25, + stroke_border: true, + stroke_color: GREEN, + stroke_width: 0.05, + cast_shadow: true, + shadow_opacity: 1.0, + ..SlideSettings::default() + }; + let mut drew_behind = false; + let (img, _) = compose_with(&Rgba8::new(0, 0), None, &s, 40, 24, &mut |_, _| drew_behind = true); + assert!(drew_behind); + assert!(img == solid(40, 24, RED), "photo effects changed the backdrop"); + } + #[test] fn hostile_input_never_panics() { let wild = SlideSettings { From c7fa4cad0efa5ab626eee2a03e9f594a15f872fc Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:08:04 +1100 Subject: [PATCH 022/112] upstream #4627: reject malformed preset IDs before exporting preset.export rejects an `ids` that is not an array of strings before writing, so the existing output file is kept. Hand-ported (fork code at preset_files.rs export()); upstream test moved to tests_export.rs. Checked: clippy, preset_export tests. Sources: storytold/lightcraft#4627 Manual: none, no user-visible change Co-authored-by: Mex <44814932+MMexicann@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/preset_files.rs | 9 +++++++-- crates/engine/src/tests_export.rs | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/preset_files.rs b/crates/engine/src/cmd/preset_files.rs index 4d08e42518..07f55b4be9 100644 --- a/crates/engine/src/cmd/preset_files.rs +++ b/crates/engine/src/cmd/preset_files.rs @@ -136,13 +136,18 @@ fn export(s: &mut Session, p: &Value) -> Result { if path.extension().is_none() { path.set_extension(LCPRESET_EXT); } - let ids = strings(p, "ids"); + let invalid_ids = || bad("preset.export", "`ids` must be an array of preset IDs"); + let ids = match p.get("ids") { + None | Some(Value::Null) => None, + Some(Value::Array(ids)) => Some(ids.iter().map(|id| id.as_str().ok_or_else(invalid_ids)).collect::>>()?), + Some(_) => return Err(invalid_ids()), + }; let group = str_param(p, "group"); let chosen: Vec<_> = s .presets .iter() .filter(|x| match (&ids, group) { - (Some(ids), _) => ids.contains(&x.id), + (Some(ids), _) => ids.contains(&x.id.as_str()), (None, Some(g)) => x.group == g, (None, None) => !x.builtin, }) diff --git a/crates/engine/src/tests_export.rs b/crates/engine/src/tests_export.rs index 2d3797c5bc..6bd2e54652 100644 --- a/crates/engine/src/tests_export.rs +++ b/crates/engine/src/tests_export.rs @@ -2053,3 +2053,26 @@ fn jpeg_with_extended_gps() -> Vec { out.extend(&jpeg[2..]); out } + +#[test] +fn preset_export_rejects_malformed_ids_without_replacing_the_output() { + let dir = temp_dir("preset-export-ids"); + let mut s = Session::with_demo(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.6})).unwrap(); + s.execute("preset.create", &json!({"name": "Bright", "group": "Travel"})).unwrap(); + s.execute("develop.set", &json!({"control": "effects.clarity", "value": 30})).unwrap(); + s.execute("preset.create", &json!({"name": "Crisp", "group": "Street"})).unwrap(); + let path = dir.join("selected.lcpreset"); + let prior = b"previous output"; + std::fs::write(&path, prior).unwrap(); + let path_text = path.to_string_lossy(); + + for ids in [json!("lc.warm-glow"), json!(["lc.warm-glow", 7]), json!([])] { + assert!(s.execute("preset.export", &json!({"path": path_text, "ids": ids})).is_err(), "{ids}"); + assert_eq!(std::fs::read(&path).unwrap().as_slice(), prior); + } + assert_eq!(s.execute("preset.export", &json!({"path": path_text})).unwrap()["count"], 2); + assert_eq!(s.execute("preset.export", &json!({"path": path_text, "ids": null, "group": "Travel"})).unwrap()["count"], 1); + assert_eq!(s.execute("preset.export", &json!({"path": path_text, "ids": ["lc.warm-glow"], "group": "Nope"})).unwrap()["count"], 1); + let _ = std::fs::remove_dir_all(dir); +} From d5b22ebc0365edf58704585a5b19a87e1bb1e822 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:08:04 +1100 Subject: [PATCH 023/112] upstream #4730: report final slideshow PDF bytes The slideshow PDF summary reports the finished file's size (read after sync), not the writer's length before the trailer. Hand-ported onto the fork's sync_file/drop sequence; upstream assertions added to tests_slideshow_export.rs. Checked: clippy, pdf test. Sources: storytold/lightcraft#4730 Manual: none, no user-visible change Co-authored-by: acebear17 <121527825+acebear17@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/slideshow_export.rs | 3 ++- crates/engine/src/tests_slideshow_export.rs | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/slideshow_export.rs b/crates/engine/src/slideshow_export.rs index 846bf6b153..9296278041 100644 --- a/crates/engine/src/slideshow_export.rs +++ b/crates/engine/src/slideshow_export.rs @@ -511,10 +511,11 @@ impl Prepared { if pages == 0 { return Err("no slide could be rendered".into()); } - let bytes = pdf.len(); let catalog = if self.request.settings.full_screen { " /PageMode /FullScreen" } else { "" }; let pdf_file = pdf.finish(catalog)?.into_inner().map_err(|e| format!("PDF: {}", e.error()))?; lcc_catalog::safe_file::sync_file(&pdf_file, false).map_err(|e| format!("PDF: {e}"))?; + // the finished file's size: the trailer and cross-reference table come after the pages + let bytes = pdf_file.metadata().map_err(|e| format!("PDF: {e}"))?.len(); // closed before the rename: Windows can't rename a file that is still open drop(pdf_file); part.commit(&self.guard)?; diff --git a/crates/engine/src/tests_slideshow_export.rs b/crates/engine/src/tests_slideshow_export.rs index ce38c2a9f6..13e5c793c8 100644 --- a/crates/engine/src/tests_slideshow_export.rs +++ b/crates/engine/src/tests_slideshow_export.rs @@ -133,6 +133,7 @@ fn pdf_has_a_page_per_slide_titles_included() { let r = export(&mut s, json!({"format": "pdf", "path": path, "size": 160, "quality": 80, "ids": ids})); assert_eq!((r["pages"].as_u64(), r["slides"].as_u64(), r["width"].as_u64(), r["height"].as_u64()), (Some(5), Some(5), Some(160), Some(90))); let bytes = std::fs::read(&path).unwrap(); + assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64)); assert!(bytes.starts_with(b"%PDF-1.4")); let pages = pdf_pages(&bytes); assert_eq!(pages.len(), 5); @@ -152,7 +153,9 @@ fn pdf_has_a_page_per_slide_titles_included() { s.execute("slideshow.layout", &json!({"aspect": "4:3"})).unwrap(); let r = export(&mut s, json!({"format": "pdf", "path": path, "size": 120, "fullScreen": false, "ids": ids})); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(120), Some(90))); - assert!(!String::from_utf8_lossy(&std::fs::read(&path).unwrap()).contains("/FullScreen")); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64)); + assert!(!String::from_utf8_lossy(&bytes).contains("/FullScreen")); } #[test] From ef74a81ed123fee46f54b5bf69874b13500a39ad Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:08:05 +1100 Subject: [PATCH 024/112] upstream #4741: skip image probes for linked catalog videos Lightroom catalog import no longer runs the image probe on present VIDEO originals (it read whole files only to reject them). Adapted from upstream: added is_catalog_video helper (fork lacked it); test uses .MOV since the fork does not take .MPG from catalogs. Checked: clippy, native_catalog/native_video tests. Sources: storytold/lightcraft#4741 Manual: none, no user-visible change Co-authored-by: murdawkmedia <119478503+murdawkmedia@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_catalog.rs | 33 ++++++++++++++++++++++++++ crates/engine/src/lightroom_job.rs | 8 ++++--- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 46775e432b..419b7c7e36 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -1560,6 +1560,14 @@ fn read_lightroom(path: &Path, reader: Reader, source_guard: SourceGuard, cancel Ok(out) } +/// A video the catalog lists with the format `VIDEO` and a video extension. It becomes a video record +/// by reference, so the import never runs an image probe on it (adapted from upstream #4741). +pub(crate) fn is_catalog_video(p: &CatalogPhoto) -> bool { + const EXTENSIONS: [&str; 12] = ["mp4", "mov", "m4v", "avi", "mts", "m2ts", "3gp", "mkv", "webm", "wmv", "mpg", "mpeg"]; + text(&p.image, "fileFormat").eq_ignore_ascii_case("VIDEO") + && Path::new(&p.path).extension().and_then(|e| e.to_str()).is_some_and(|e| EXTENSIONS.iter().any(|x| e.eq_ignore_ascii_case(x))) +} + /// How many of the images left out of an import (no file, folder or root record) the warnings name one by one. const LEFT_OUT_NAMED: usize = 20; /// Drop the virtual copies whose master was skipped, adding them to the skipped images: a copy has @@ -5104,6 +5112,31 @@ pub(crate) mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn native_catalog_links_present_video_without_an_image_probe_failure() { + let dir = std::env::temp_dir().join(format!("app-lrcat-video-link-{}", std::process::id())); + std::fs::create_dir_all(dir.join("Photos")).unwrap(); + let path = dir.join("videos.lrcat"); + let clip = dir.join("Photos").join("clip.MOV"); + std::fs::write(&clip, b"opaque movie bytes").unwrap(); + let mut tables = photo_tables((dir.to_str().unwrap(), "")); + tables[2].2[2] = SqlValue::Text("clip.MOV".into()); + tables[3].2[3] = SqlValue::Text("VIDEO".into()); + std::fs::write(&path, native_catalog(&tables)).unwrap(); + let mut s = crate::Session::new(); + s.media.file_probe = Some(Arc::new(|_| Err("unsupported image format".into()))); + + let imported = s.execute("library.importLightroom", &json!({"path": path})).unwrap(); + + assert_eq!(imported["failed"], json!([])); + assert_eq!(imported["missing"], json!([])); + let id = PhotoId(imported["mapping"]["1"].as_u64().unwrap()); + let photo = s.catalog.photo(id).unwrap(); + assert_eq!(photo.kind, lcc_catalog::MediaKind::Video); + assert_eq!(photo.source, Source::File { path: clip.to_str().unwrap().into() }); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn native_video_reimport_repairs_kind_without_losing_edits_or_memberships() { let dir = std::env::temp_dir().join(format!("app-lrcat-video-reimport-{}", std::process::id())); diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index ed9f2122b5..40641993dc 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -483,10 +483,12 @@ fn original_paths(data: &CatalogImport, cancel: &AtomicBool) -> crate::Result<(V if !seen.insert(key.clone()) { continue; } - if photo.original_is_file() { - paths.push(photo.path.clone()); - } else { + if !photo.original_is_file() { missing.insert(key); + } else if !lightroom_catalog::is_catalog_video(photo) { + // Catalog videos are references. The image probe reads the entire + // file before rejecting it, even though its catalog entry is added. + paths.push(photo.path.clone()); } } Ok((paths, missing)) From 8421e396910c0ddaff096c9fdd9e5de96c888d44 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:08:22 +1100 Subject: [PATCH 025/112] upstream #4565: normalize preset and import keywords Metadata-preset keywords are cleaned (keywords::clean) and deduplicated with Unicode case folding, as import-dialog keywords now are too (to_lowercase instead of ASCII-only matching). Hand-ported: the fork's import keywords live in import.rs apply_settings, not import/commit.rs. Upstream integration test crates/engine/tests/import_keywords.rs brought over. Checked: clippy, tests. Sources: storytold/lightcraft#4565 Manual: none, no user-visible change Co-authored-by: Mex <44814932+MMexicann@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/metadata.rs | 6 +- crates/engine/src/import.rs | 12 ++-- crates/engine/tests/import_keywords.rs | 98 ++++++++++++++++++++++++++ 3 files changed, 110 insertions(+), 6 deletions(-) create mode 100644 crates/engine/tests/import_keywords.rs diff --git a/crates/engine/src/cmd/metadata.rs b/crates/engine/src/cmd/metadata.rs index 7bfa3718da..5d3281d66c 100644 --- a/crates/engine/src/cmd/metadata.rs +++ b/crates/engine/src/cmd/metadata.rs @@ -93,9 +93,11 @@ pub fn apply_to(m: &mut Meta, fields: &Value) { m.copyright_status = st; } } else if k == "keywords" { + let mut seen: std::collections::HashSet = m.keywords.iter().map(|k| k.to_lowercase()).collect(); for kw in v.as_array().into_iter().flatten().filter_map(Value::as_str) { - if !m.keywords.iter().any(|x| x.eq_ignore_ascii_case(kw)) { - m.keywords.push(kw.to_string()); + let kw = lcc_catalog::keywords::clean(kw); + if !kw.is_empty() && seen.insert(kw.to_lowercase()) { + m.keywords.push(kw); } } } else if let (Some(f), Some(l)) = (list_field(m, k), text_list(v)) { diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 992d4177a2..5890df9875 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -2803,10 +2803,14 @@ fn apply_settings(s: &Session, p: &mut Photo, opts: &ImportOptions, now: &str) { if let Some(mp) = opts.metadata_preset.as_ref().and_then(|n| s.metadata_presets.iter().find(|m| m.name.eq_ignore_ascii_case(n))) { crate::cmd::metadata::apply_to(&mut p.meta, &mp.fields); } - for k in &opts.keywords { - let k = lcc_catalog::keywords::clean(k); - if !k.is_empty() && !p.meta.keywords.iter().any(|x| x.eq_ignore_ascii_case(&k)) { - p.meta.keywords.push(k); + // Most imports add no keywords: don't index the file's existing keywords then. + if !opts.keywords.is_empty() { + let mut seen: std::collections::HashSet = p.meta.keywords.iter().map(|k| k.to_lowercase()).collect(); + for k in &opts.keywords { + let k = lcc_catalog::keywords::clean(k); + if !k.is_empty() && seen.insert(k.to_lowercase()) { + p.meta.keywords.push(k); + } } } // the camera profile before the presets: a preset doesn't take it away unless the import says so diff --git a/crates/engine/tests/import_keywords.rs b/crates/engine/tests/import_keywords.rs new file mode 100644 index 0000000000..7a5ea52ee6 --- /dev/null +++ b/crates/engine/tests/import_keywords.rs @@ -0,0 +1,98 @@ +//! Keyword normalization is the same for import presets and import-dialog keywords. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use lcc_engine::Session; +use serde_json::json; + +struct Input(PathBuf); + +impl Input { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let path = std::env::temp_dir().join(format!("import-keywords-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir(&path).unwrap(); + let image = lcc_raster::Rgba8 { width: 2, height: 1, data: vec![[20, 40, 60, 255], [80, 100, 120, 255]] }; + let bytes = lcc_codecs::encode_png(&lcc_codecs::EncodeImage::rgba8(&image), &lcc_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(path.join("photo.png"), bytes).unwrap(); + Self(path) + } + + fn photo(&self) -> PathBuf { + self.0.join("photo.png") + } + + fn sidecar(&self) { + std::fs::write( + self.0.join("photo.xmp"), + r#"ÉtéPortraitOriginalÉté|PortraitOriginal"#, + ) + .unwrap(); + } +} + +impl Drop for Input { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn keywords(s: &Session) -> Vec { + assert_eq!(s.catalog.len(), 1); + s.catalog.photos().next().unwrap().meta.keywords.clone() +} + +fn import(s: &mut Session, path: &Path, mut options: serde_json::Value) { + options["paths"] = json!([path.to_string_lossy()]); + let report = s.execute("library.import", &options).unwrap(); + assert_eq!(report["imported"].as_array().unwrap().len(), 1, "{report}"); + assert_eq!(report["failed"], json!([]), "{report}"); +} + +#[test] +fn default_metadata_preset_cleans_keywords_and_ignores_unicode_duplicates() { + let input = Input::new(); + let mut s = Session::new().with_fs(); + s.execute( + "metadata.savePreset", + &json!({"name": "Default", "fields": {"creator": "Studio", "keywords": [ + " || ", " Été | Portrait ", "été|portrait", "Ärger", "ärger", "studio", "STUDIO" + ]}}), + ) + .unwrap(); + s.execute("library.preferences", &json!({"import": {"metadataPreset": "Default"}})).unwrap(); + + import(&mut s, &input.photo(), json!({})); + assert_eq!(keywords(&s), ["Été|Portrait", "Ärger", "studio"]); + assert_eq!(s.catalog.photos().next().unwrap().meta.creator, "Studio"); +} + +#[test] +fn explicit_preset_and_import_keywords_keep_first_sidecar_spellings_and_order() { + let input = Input::new(); + input.sidecar(); + let mut s = Session::new().with_fs(); + s.execute("metadata.savePreset", &json!({"name": "Import", "fields": {"keywords": [" été | portrait ", " | ", "Ärger", "ärger"]}})).unwrap(); + + import( + &mut s, + &input.photo(), + json!({"metadataPreset": "Import", "keywords": ["ÉTÉ|PORTRAIT", " ÄRGER ", " New | Child ", "new|child", " || "]}), + ); + let expected = ["Été|Portrait", "Original", "Ärger", "New|Child"]; + assert_eq!(keywords(&s), expected); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.is_empty(), "the whole import is one undo step"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(keywords(&s), expected); +} + +#[test] +fn import_keywords_without_a_preset_use_unicode_keyword_identity() { + let input = Input::new(); + input.sidecar(); + let mut s = Session::new().with_fs(); + import(&mut s, &input.photo(), json!({"keywords": [" été | portrait ", "Ärger", "ärger", " New || Child ", "new|child", " || "]})); + assert_eq!(keywords(&s), ["Été|Portrait", "Original", "Ärger", "New|Child"]); +} From d30dfd4f350f4c637a11cca5f51c73026e477e72 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:08:33 +1100 Subject: [PATCH 026/112] upstream #1638: walk overlapping photo and preset import roots once Adapted from upstream: walk.rs gains files_in_with_seen, an opt-in shared set of canonical folders (one canonicalize per folder, only for multi-root requests; plain files_in keeps the fork's no-extra-syscall walk). Import expansion and preset.import share it across their roots, so a folder named twice, nested in another root or reached by a link is walked once and keeps the first path; an alias of the library folder is skipped too. Tests: crates/engine/tests/overlapping_roots.rs (nested roots, portable; upstream's symlink CLI tests not ported). Checked: clippy, tests. Sources: storytold/lightcraft#1638 Manual: none (bug fix; manual already describes the intended import); whats-new entry added Co-authored-by: SarimSyed Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/preset_files.rs | 5 ++- crates/engine/src/import.rs | 9 +++-- crates/engine/src/presets.rs | 10 ++++- crates/engine/src/walk.rs | 33 ++++++++++++++-- crates/engine/tests/overlapping_roots.rs | 39 +++++++++++++++++++ .../2026-11-29-overlapping-import-roots.md | 2 + 6 files changed, 89 insertions(+), 9 deletions(-) create mode 100644 crates/engine/tests/overlapping_roots.rs create mode 100644 docs/whats-new/2026-11-29-overlapping-import-roots.md diff --git a/crates/engine/src/cmd/preset_files.rs b/crates/engine/src/cmd/preset_files.rs index 07f55b4be9..cbcf6beab6 100644 --- a/crates/engine/src/cmd/preset_files.rs +++ b/crates/engine/src/cmd/preset_files.rs @@ -5,7 +5,7 @@ use serde_json::{Value, json}; use super::mask_effect_files as mef; use super::{CommandSpec, always, bad, cmd, str_param}; use crate::preset_import::{group_from_dir, read_presets}; -use crate::presets::{LCPRESET_EXT, expand_preset_paths, to_lcpreset}; +use crate::presets::{LCPRESET_EXT, expand_preset_paths_with_seen, to_lcpreset}; use crate::{Result, Session}; fn strings(p: &Value, key: &str) -> Option> { @@ -28,9 +28,10 @@ fn import(s: &mut Session, p: &Value) -> Result { let mut export_found = Vec::new(); // every file's presets, added in one go below (adding one at a time indexed the library each time) let mut pending: Vec<(lcc_develop::Preset, Value)> = Vec::new(); + let mut seen_dirs = std::collections::HashSet::new(); for top in &paths { let from_dir = std::path::Path::new(top).is_dir(); - for f in expand_preset_paths(std::slice::from_ref(top)) { + for f in expand_preset_paths_with_seen(std::slice::from_ref(top), &mut seen_dirs) { // presets in a folder go to a group named after it (unless the file names its own) // the path from the imported folder (inclusive) to the file's folder let base = std::path::Path::new(top).parent().unwrap_or(std::path::Path::new("")); diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 5890df9875..44a07b26f6 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -745,9 +745,12 @@ fn expand_report_noting( subfolders: bool, ) -> Expansion { let mut out = Expansion::default(); + // canonical folders walked so far: overlapping roots (an alias, a folder inside another) are walked once + let mut seen_dirs = std::collections::HashSet::new(); + let skipped = skip.and_then(|p| std::fs::canonicalize(p).ok()); for p in paths { let p = Path::new(p); - if skip.is_some_and(|s| p == s) { + if skip.is_some_and(|s| p == s) || skipped.as_ref().is_some_and(|s| std::fs::canonicalize(p).as_ref().ok() == Some(s)) { continue; } if p.is_dir() { @@ -762,8 +765,8 @@ fn expand_report_noting( keep }; let w = match note.as_mut() { - Some(note) => crate::walk::files_in_noting(p, skip, walk_limits, keep, &mut **note), - None => crate::walk::files_in(p, skip, walk_limits, keep), + Some(note) => crate::walk::files_in_with_seen(p, skip, walk_limits, keep, Some(&mut **note), &mut seen_dirs), + None => crate::walk::files_in_with_seen(p, skip, walk_limits, keep, None, &mut seen_dirs), }; let truncated = if subfolders { w.truncated } else { w.entries >= limits.max_entries }; if truncated { diff --git a/crates/engine/src/presets.rs b/crates/engine/src/presets.rs index 7ca2ea91a9..71ffb59c9c 100644 --- a/crates/engine/src/presets.rs +++ b/crates/engine/src/presets.rs @@ -233,6 +233,13 @@ pub fn without_unavailable_masks(preset: &Preset, available: bool) -> (Preset, V /// Expand files/folders (recursively, bounded: see [`crate::walk`]) into preset files /// (`.lcpreset`, `.xmp`). pub fn expand_preset_paths(paths: &[String]) -> Vec { + expand_preset_paths_with_seen(paths, &mut std::collections::HashSet::new()) +} + +/// [`expand_preset_paths`] sharing the canonical folders and files already expanded in `seen`, so +/// overlapping roots of one import (an alias, a folder inside another) yield each preset once, under +/// the first path that reached it (adapted from upstream #1638). +pub(crate) fn expand_preset_paths_with_seen(paths: &[String], seen: &mut std::collections::HashSet) -> Vec { let preset_file = |p: &Path| { let ext = p.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); lcc_brand::preset_exts().any(|e| e == ext) @@ -252,12 +259,13 @@ pub fn expand_preset_paths(paths: &[String]) -> Vec { for p in paths { let path = Path::new(p); if path.is_dir() { - let w = crate::walk::files_in(path, None, crate::walk::Limits::default(), preset_file); + let w = crate::walk::files_in_with_seen(path, None, crate::walk::Limits::default(), preset_file, None, seen); out.extend(w.files.into_iter().map(|f| f.to_string_lossy().to_string())); } else { out.push(p.clone()); } } + out.retain(|p| std::fs::canonicalize(p).map_or(true, |real| seen.insert(real))); out } diff --git a/crates/engine/src/walk.rs b/crates/engine/src/walk.rs index afffd45be3..86ac888282 100644 --- a/crates/engine/src/walk.rs +++ b/crates/engine/src/walk.rs @@ -143,7 +143,7 @@ pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, Entr /// 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) + walk(root, skip, limits, keep, |_| true, None, None) } /// [`files_in`], entering a folder below `root` only when `enter` accepts it: a folder it turns @@ -156,14 +156,30 @@ pub fn files_in_entering( keep: impl FnMut(&Path) -> bool, enter: impl FnMut(&Path) -> bool, ) -> Walked { - walk(root, skip, limits, keep, enter, None) + walk(root, skip, limits, keep, enter, None, None) } /// [`files_in`], handing the listing of every folder it reads to `note`: who walks a folder to /// find its files has, with that, the answer to "is this name there" for everything in it, and /// need not ask the disk again (a round trip for each name on a network share). pub fn files_in_noting(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool, note: NoteFolder) -> Walked { - walk(root, skip, limits, keep, |_| true, Some(note)) + walk(root, skip, limits, keep, |_| true, Some(note), None) +} + +/// [`files_in`] (or [`files_in_noting`] with `note`) sharing canonical folder identities across +/// the roots of one request in `seen`: a folder already walked from an earlier root (named twice, +/// inside another root, or reached through a link) is not walked again, and the first spelling of +/// its path is the one kept. It costs one `canonicalize` per folder (not per entry), which is why +/// only multi-root requests ask for it. Adapted from upstream #1638. +pub(crate) fn files_in_with_seen( + root: &Path, + skip: Option<&Path>, + limits: Limits, + keep: impl FnMut(&Path) -> bool, + note: Option, + seen: &mut HashSet, +) -> Walked { + walk(root, skip, limits, keep, |_| true, note, Some(seen)) } fn walk( @@ -173,6 +189,7 @@ fn walk( mut keep: impl FnMut(&Path) -> bool, mut enter: impl FnMut(&Path) -> bool, mut note: Option, + mut shared: Option<&mut HashSet>, ) -> Walked { let mut out = Walked::default(); // canonical folders reached through a link, so a link loop is walked at most once @@ -196,6 +213,16 @@ fn walk( if skip.is_some_and(|s| path == s) || skip_canonical.as_ref().is_some_and(|s| std::fs::canonicalize(&path).is_ok_and(|p| p.starts_with(s))) { continue; } + if let Some(seen) = shared.as_deref_mut() { + let Ok(real) = std::fs::canonicalize(&path) else { continue }; + if seen.len() >= MAX_ENTRIES && !seen.contains(&real) { + out.truncated = true; + break; + } + if !seen.insert(real) { + continue; + } + } if depth >= limits.max_depth { out.truncated = true; continue; diff --git a/crates/engine/tests/overlapping_roots.rs b/crates/engine/tests/overlapping_roots.rs new file mode 100644 index 0000000000..ef161c2850 --- /dev/null +++ b/crates/engine/tests/overlapping_roots.rs @@ -0,0 +1,39 @@ +//! Overlapping import roots (a folder named twice, or inside another root) are walked once and +//! keep the first path spelling; the same holds for preset imports (adapted from upstream #1638). + +use lcc_engine::Session; +use serde_json::json; + +fn temp(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("overlapping-roots-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("real")).unwrap(); + dir +} + +#[test] +fn overlapping_photo_roots_are_walked_once_and_keep_the_first_path() { + let dir = temp("photos"); + let real = dir.join("real"); + std::fs::write(real.join("photo.jpg"), b"not really a jpeg").unwrap(); + let roots = [real.to_string_lossy().to_string(), dir.to_string_lossy().to_string(), real.to_string_lossy().to_string()]; + let (files, truncated) = lcc_engine::import::expand_within(&roots, None, lcc_engine::walk::Limits::default()); + assert!(!truncated); + assert_eq!(files, [real.join("photo.jpg").to_string_lossy().to_string()]); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn overlapping_preset_roots_import_once_and_keep_the_first_path() { + let dir = temp("presets"); + let real = dir.join("real"); + let file = real.join("look.lrtemplate"); + std::fs::write(&file, r#"return { title = "Linked Look", value = { settings = { Exposure2012 = 0.5 } } }"#).unwrap(); + let mut s = Session::new(); + let r = s.execute("preset.import", &json!({"paths": [real, dir, file], "dryRun": true})).unwrap(); + let imported = r["imported"].as_array().unwrap(); + assert_eq!(imported.len(), 1, "{r}"); + assert_eq!(imported[0]["file"], file.to_string_lossy().as_ref()); + assert_eq!(r["failed"], json!([])); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/docs/whats-new/2026-11-29-overlapping-import-roots.md b/docs/whats-new/2026-11-29-overlapping-import-roots.md new file mode 100644 index 0000000000..517f58125f --- /dev/null +++ b/docs/whats-new/2026-11-29-overlapping-import-roots.md @@ -0,0 +1,2 @@ +### Overlapping import folders are read once +- Importing photos or presets from folders that overlap (a folder and one inside it, or a link to another chosen folder) reads each folder once and keeps the first path, so nothing is offered twice. From c224702d19801f33351628823c69e762562f38f3 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:08:34 +1100 Subject: [PATCH 027/112] upstream #4628: preserve absolute filesystem roots in Local browse browse_folder_string keeps a filesystem root's separator (/, C:\, UNC share) and trims others; used by library.browse, stamp_browsed folder timestamps, the UI browse and local.addRoot. Hand-ported: the fork's UI code is in ui-egui/src/import.rs and menus.rs (upstream's resolve_browse_root has no fork counterpart). Upstream unit tests added. Checked: clippy (engine, ui-egui), tests. Sources: storytold/lightcraft#4628 Manual: none (bug fix); whats-new entry added Co-authored-by: Mex <44814932+MMexicann@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/browse.rs | 7 ++--- crates/engine/src/import.rs | 31 +++++++++++++++++++ crates/ui-egui/src/import.rs | 2 +- crates/ui-egui/src/menus.rs | 2 +- .../2026-11-29-local-browse-drive-roots.md | 2 ++ 5 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 docs/whats-new/2026-11-29-local-browse-drive-roots.md diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 514a43f3d8..6fc99ea653 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -17,7 +17,7 @@ use lcc_catalog::{Op, PhotoId, Source}; use serde_json::{Value, json}; use super::{CommandSpec, always, bad, bool_or, cmd, str_param}; -use crate::import::{ImportMode, ImportOptions, import_with, is_supported}; +use crate::import::{ImportMode, ImportOptions, browse_folder_string, import_with, is_supported}; use crate::{Browse, LibrarySource, Result, Session}; fn browse(s: &mut Session, p: &Value) -> Result { @@ -27,7 +27,7 @@ fn browse(s: &mut Session, p: &Value) -> Result { if !dir.is_dir() { return Err(bad(C, format!("{path}: not a folder"))); } - let dir_s = dir.to_string_lossy().trim_end_matches(['/', '\\']).to_string(); + let dir_s = browse_folder_string(&dir); // subfolders: given, it wins; left out, a re-browse of the same folder keeps the choice and a // new folder starts with subfolders in (the Import tab's browse applies the same rule) let subfolders = bool_or(p, "subfolders", s.browse.as_ref().is_none_or(|b| b.path != dir_s || b.subfolders)); @@ -143,8 +143,7 @@ const RESTAMP_SECS: i64 = 3600; fn stamp_browsed(s: &mut Session, root: &str, files: &[String]) { let now = (s.clock)(); let now_s = lcc_catalog::stacks::iso_seconds(&now); - let mut folders: std::collections::BTreeSet = - files.iter().filter_map(|f| Path::new(f).parent().map(|d| d.to_string_lossy().trim_end_matches(['/', '\\']).to_string())).collect(); + let mut folders: std::collections::BTreeSet = files.iter().filter_map(|f| Path::new(f).parent().map(browse_folder_string)).collect(); folders.insert(root.to_string()); let ops: Vec = folders .into_iter() diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 44a07b26f6..ebe10ce03a 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -792,6 +792,37 @@ fn expand_report_noting( out } +/// The string used for an absolute folder in Local browse: trailing separators trimmed, except on a +/// filesystem root (`/`, `C:\`, a UNC share), which keeps its own (adapted from upstream #4628). +pub fn browse_folder_string(path: &Path) -> String { + let text = path.to_string_lossy(); + if path.parent().is_none() { text.into_owned() } else { text.trim_end_matches(['/', '\\']).to_string() } +} + +#[cfg(test)] +mod browse_folder_tests { + use super::{Path, browse_folder_string}; + + #[test] + fn browse_folder_string_keeps_filesystem_roots() { + #[cfg(windows)] + { + assert_eq!(browse_folder_string(Path::new(r"C:\")), r"C:\"); + assert_eq!(browse_folder_string(Path::new(r"\\server\share\")), r"\\server\share\"); + } + #[cfg(not(windows))] + assert_eq!(browse_folder_string(Path::new("/")), "/"); + } + + #[test] + fn browse_folder_string_removes_trailing_separators_from_other_folders() { + #[cfg(windows)] + assert_eq!(browse_folder_string(Path::new(r"C:\photos\")), r"C:\photos"); + #[cfg(not(windows))] + assert_eq!(browse_folder_string(Path::new("/photos/")), "/photos"); + } +} + /// What a path given on the command line at launch becomes ([`launch_path`]). #[derive(Clone, Debug, PartialEq, Eq)] pub enum LaunchPath { diff --git a/crates/ui-egui/src/import.rs b/crates/ui-egui/src/import.rs index 36568e7ae5..b522fb4ba9 100644 --- a/crates/ui-egui/src/import.rs +++ b/crates/ui-egui/src/import.rs @@ -755,7 +755,7 @@ pub fn browse(app: &mut LccApp, path: &str, subfolders: Option, show: Opti if app.scan.as_ref().is_some_and(|t| !t.browse) || app.import.as_ref().is_some_and(|t| !t.browse) { return Err("an import is running".into()); } - let dir_s = dir.to_string_lossy().trim_end_matches(['/', '\\']).to_string(); + let dir_s = lcc_engine::import::browse_folder_string(&dir); // subfolders: given, it wins; left out, a re-browse of the same folder keeps the choice and a // new folder starts with subfolders in — a folder picked to import means the tree under it // (the engine's library.browse applies the same rule) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index dcfd082090..3eede8bc0c 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1960,7 +1960,7 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option { // a folder kept in Local's sidebar (saved with the UI state); nothing on disk changes let Some(path) = p.get("path").and_then(Value::as_str) else { return Some(Err("local.addRoot needs a path".into())) }; - let abs = std::path::absolute(path).map(|a| a.to_string_lossy().trim_end_matches(['/', '\\']).to_string()).unwrap_or(path.into()); + let abs = std::path::absolute(path).map(|a| lcc_engine::import::browse_folder_string(&a)).unwrap_or(path.into()); let abs = if abs.is_empty() { path.to_string() } else { abs }; if !std::path::Path::new(&abs).is_dir() { return Some(Err(format!("{path}: not a folder"))); diff --git a/docs/whats-new/2026-11-29-local-browse-drive-roots.md b/docs/whats-new/2026-11-29-local-browse-drive-roots.md new file mode 100644 index 0000000000..49bc60742d --- /dev/null +++ b/docs/whats-new/2026-11-29-local-browse-drive-roots.md @@ -0,0 +1,2 @@ +### Local browse keeps drive roots +- Browsing or adding a whole drive or share in Local (`/`, `C:\`, a network share) now keeps its root, instead of turning it into an empty or relative path. From be29ce4029e725bc2fa939377d6c7cc63fb3d0cf Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:10:37 +1100 Subject: [PATCH 028/112] upstream #4538: `cli mcp FOLDER` keeps serving when the folder has no photos library.import refuses an empty path list, which ended the server before it started. Now an empty expansion is reported on stderr and the server runs. Hand-ported from upstream #4538 (apps/cli/src/lib.rs here), with its end-to-end test as apps/cli/tests/mcp_empty_folder.rs. Checked: clippy -D warnings on lcc-cli, the new test and mcp_shutdown pass. Manual: none (docs/mcp.md already says photos can be imported later); whats-new entry added Co-authored-by: mattbuschh Co-Authored-By: Claude Opus 5.5 --- apps/cli/src/lib.rs | 11 +++++-- apps/cli/tests/mcp_empty_folder.rs | 29 +++++++++++++++++++ docs/whats-new/2026-11-29-mcp-empty-folder.md | 3 ++ 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 apps/cli/tests/mcp_empty_folder.rs create mode 100644 docs/whats-new/2026-11-29-mcp-empty-folder.md diff --git a/apps/cli/src/lib.rs b/apps/cli/src/lib.rs index ff10e6f24e..e1f121fdfb 100644 --- a/apps/cli/src/lib.rs +++ b/apps/cli/src/lib.rs @@ -644,8 +644,15 @@ fn mcp(args: &[String]) -> Result<(), String> { }; if !files.is_empty() { let paths = expand_paths(&files); - let r = h.session.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string())?; - eprintln!("{CLI} mcp: imported {} photo(s)", r.get("imported").and_then(Value::as_array).map_or(0, Vec::len)); + // A folder with no photos yet still serves (photos come later through `import`); + // `library.import` refuses an empty list, which would end the server before it starts + // (adapted from upstream #4538). + if paths.is_empty() { + eprintln!("{CLI} mcp: no photos found in {}; nothing imported", files.join(", ")); + } else { + let r = h.session.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string())?; + eprintln!("{CLI} mcp: imported {} photo(s)", r.get("imported").and_then(Value::as_array).map_or(0, Vec::len)); + } } Box::new(h) } diff --git a/apps/cli/tests/mcp_empty_folder.rs b/apps/cli/tests/mcp_empty_folder.rs new file mode 100644 index 0000000000..ebfe31c9db --- /dev/null +++ b/apps/cli/tests/mcp_empty_folder.rs @@ -0,0 +1,29 @@ +//! ` mcp FOLDER` serves even when the folder holds no photos yet (adapted from upstream #4538). + +use std::io::Write; +use std::process::{Command, Stdio}; + +#[test] +fn empty_folder_still_serves() { + let dir = std::env::temp_dir().join(format!("lcc-cli-test-{}", std::process::id())).join("mcp-empty-folder"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut child = Command::new(env!("CARGO_BIN_EXE_app-cli")) + .arg("mcp") + .arg(&dir) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut input = child.stdin.take().unwrap(); + input.write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"clientInfo\":{\"name\":\"test\",\"version\":\"1\"}}}\n").unwrap(); + drop(input); + let out = child.wait_with_output().unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + let _ = std::fs::remove_dir_all(&dir); + assert!(out.status.success(), "an empty folder must not stop the server: {stderr}"); + assert!(stderr.contains("serving MCP on stdio"), "CLI must reach the MCP transport: {stderr}"); + assert!(stdout.contains("\"id\":1") && stdout.contains("\"result\""), "initialize must be answered: {stdout}"); +} diff --git a/docs/whats-new/2026-11-29-mcp-empty-folder.md b/docs/whats-new/2026-11-29-mcp-empty-folder.md new file mode 100644 index 0000000000..be269614e8 --- /dev/null +++ b/docs/whats-new/2026-11-29-mcp-empty-folder.md @@ -0,0 +1,3 @@ +### ` mcp FOLDER` serves an empty folder + +- Starting the MCP server on a folder with no photos yet no longer exits with an import error: it says nothing was imported and serves, and photos can come later through `import`. From e3b59f20c7ed35bfbfe4124415484c1dbb62758b Mon Sep 17 00:00:00 2001 From: Paolo Rizzo Date: Thu, 15 Oct 2026 01:54:53 +0200 Subject: [PATCH 029/112] upstream #1828: denoise X-Trans raws through an RGGB re-mosaic Adapted from upstream #1828 (cherry picked from 8da2f0088 and 19c4c6d76, conflicts resolved by hand). AI denoise no longer refuses non-Bayer CFAs: lcc_raw::demosaic::remosaic_rggb rebuilds the mosaic as RGGB of the same size (one interpolated channel per site, shared sites keep their sample) and the Bayer model runs on that. layout_of now rejects non-Bayer patterns outright (16 of 36 X-Trans phases look Bayer in the top-left 2x2). Fork adaptations: the fork's X-Trans Method::Ahd goes through xtrans_ri (LMMSE), so the re-mosaic is documented and tested against xtrans::directional (Method::Ppg), the interpolator it mirrors; round-trip PSNR direct/through-RGGB: smooth 56.1/57.3 dB, edgy 33.5/32.8 dB. Kept the fork's repair_pixels before denoise; tests use the fork's 4-arg load_vec_pair; testkit skip! for the real-file test. No change to existing renders: Bayer paths unchanged, X-Trans was refused before. Checked: lcc-raw lib tests (736 ok), lcc-engine denoise tests (34 ok), clippy -D warnings on lcc-raw; lcc-engine clippy fails only on pre-existing Windows dead code in import_move.rs (unix-gated tests), not touched here. brand check, xtask parity OK. Gap 11 narrows (not closed: no shippable weights, unmeasured on re-mosaiced sensors); parity/raw-parity rows updated, status unchanged. Manual: ai/denoise.mdx Co-authored-by: Paolo Rizzo Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/denoise.rs | 32 ++- crates/engine/src/tests_denoise.rs | 99 +++++++- crates/engine/src/tests_xmp.rs | 6 +- crates/raw/src/demosaic/mod.rs | 211 ++++++++++++++++++ crates/raw/src/demosaic/xtrans.rs | 107 ++++++--- docs/denoise.md | 17 +- docs/gaps.md | 4 +- .../src/content/docs/ai/denoise.mdx | 2 +- docs/parity-checklist.md | 2 +- docs/raw-parity.md | 4 +- .../whats-new/2026-11-29-xtrans-ai-denoise.md | 2 + 11 files changed, 435 insertions(+), 51 deletions(-) create mode 100644 docs/whats-new/2026-11-29-xtrans-ai-denoise.md diff --git a/crates/engine/src/denoise.rs b/crates/engine/src/denoise.rs index e09335f532..90e2d9df75 100644 --- a/crates/engine/src/denoise.rs +++ b/crates/engine/src/denoise.rs @@ -1563,8 +1563,13 @@ fn loaded(spec: &JobSpec) -> Result, MakeError> { Ok(m) } -/// The cell `[(0,0), (1,0), (0,1), (1,1)]` colours of a Bayer mosaic and so its layout. -fn layout_of(cfa: &lcc_raw::Cfa) -> Option { +/// The layout of a Bayer mosaic, from the colours of its cell `[(0,0), (1,0), (0,1), (1,1)]`; `None` for any other +/// pattern. The pattern itself must be the 2 × 2 cell: 16 of X-Trans's 36 phases have a top-left 2 × 2 that reads as a +/// Bayer cell, and one of those packed as Bayer would hand the model a sensor it was not looking at. +pub(crate) fn layout_of(cfa: &lcc_raw::Cfa) -> Option { + if !cfa.is_bayer() { + return None; + } Layout::from_cell([cfa.color_at(0, 0), cfa.color_at(1, 0), cfa.color_at(0, 1), cfa.color_at(1, 1)]) } @@ -1602,20 +1607,35 @@ pub(crate) fn make_product(spec: &JobSpec, progress: Option<&Progress>) -> Resul drop(bytes); // hot, dead and stuck pixels go before the denoiser sees them, as in the plain development crate::files::repair_pixels(&mut raw, &crate::files::RawOptions::for_path(&spec.path, true)); - if raw.cpp != 1 || !raw.cfa.as_ref().is_some_and(lcc_raw::Cfa::is_bayer) { + if raw.cpp != 1 || raw.cfa.is_none() { return Err(MakeError::Unsupported( - "only Bayer raw files can be denoised (this one has another sensor layout or is already demosaiced)".into(), + "only raw files with a colour filter array can be denoised (this one is monochrome or already demosaiced)".into(), )); } let n = raw.normalized().map_err(|e| MakeError::Failed(e.to_string()))?; drop(raw); - let layout = - n.cfa.as_ref().and_then(layout_of).ok_or_else(|| MakeError::Unsupported("the colour filter layout is not a Bayer pattern".into()))?; + let layout = n.cfa.as_ref().and_then(layout_of); (n, layout) }; if cancelled() { return Err(MakeError::Cancelled); } + // X-Trans and the other non-Bayer layouts: the model's contract is four RGGB planes, so the mosaic is interpolated + // and rebuilt as RGGB first. The picture keeps its size and the sites the two patterns share keep their own + // samples; the rest reach the model already interpolated (see docs/denoise.md). This holds the mosaic, its green + // plane and the RGGB copy at once, after the decode's memory has gone back. + let (mosaic, layout) = match layout { + Some(layout) => (mosaic, layout), + None => { + let _held = crate::memory::work_gate().acquire(mosaic.data.len().saturating_mul(12)); + let rggb = lcc_raw::demosaic::remosaic_rggb(&mosaic) + .ok_or_else(|| MakeError::Unsupported("this sensor layout cannot be read as a Bayer mosaic, so it cannot be denoised".into()))?; + (rggb, Layout { dx: 0, dy: 0 }) + } + }; + if cancelled() { + return Err(MakeError::Cancelled); + } let decoded = began.elapsed(); let model = loaded(spec)?; model.prepare(&mosaic.data, mosaic.width, mosaic.height); diff --git a/crates/engine/src/tests_denoise.rs b/crates/engine/src/tests_denoise.rs index fbe5ce9cee..439d132d72 100644 --- a/crates/engine/src/tests_denoise.rs +++ b/crates/engine/src/tests_denoise.rs @@ -14,7 +14,7 @@ use serde_json::{Value, json}; use crate::Session; use crate::denoise::{Loader, Model, PhotoState, RunOn}; use crate::export::{ExportOptions, export_photo}; -use crate::tests_xmp::{synthetic_dng_of, temp_dir}; +use crate::tests_xmp::{synthetic_dng_cfa, synthetic_dng_of, temp_dir}; /// A model that makes every output pixel half of its cell's colour: a picture that is plainly not the plain one. struct Dim { @@ -591,6 +591,103 @@ fn files_that_cannot_be_denoised_fail_with_a_reason_and_never_a_panic() { let _ = std::fs::remove_dir_all(&dir); } +/// Only a Bayer pattern has a Bayer layout. 16 of X-Trans's 36 phases start with a 2 × 2 that reads as a Bayer cell +/// (rows 2 and 3 at column 1 are R G / G B), so a file whose active area began at one of them would have had its +/// X-Trans mosaic packed as Bayer. +#[test] +fn an_x_trans_phase_that_starts_like_a_bayer_cell_is_not_taken_for_one() { + use crate::denoise::layout_of; + use lcc_raw::Cfa; + let mut looks_bayer = 0; + for dy in 0..6 { + for dx in 0..6 { + let cfa = Cfa::xtrans().shifted(dx, dy); + let cell = [cfa.color_at(0, 0), cfa.color_at(1, 0), cfa.color_at(0, 1), cfa.color_at(1, 1)]; + looks_bayer += usize::from(lcc_denoise::bayer::Layout::from_cell(cell).is_some()); + assert_eq!(layout_of(&cfa), None, "X-Trans at phase ({dx}, {dy})"); + } + } + assert_eq!(looks_bayer, 16, "the phases this test is about"); + for name in ["RGGB", "GRBG", "GBRG", "BGGR"] { + assert!(layout_of(&Cfa::bayer(name).unwrap()).is_some(), "{name}"); + } +} + +/// X-Trans (and any other non-Bayer colour filter array) reaches the model through the RGGB re-mosaic: +/// the picture comes out whole and the right size, where before the file was refused outright. +#[test] +fn a_non_bayer_sensor_is_denoised_through_the_rggb_remosaic() { + let dir = temp_dir("xtrans"); + let (w, h) = (192usize, 160usize); + let data: Vec = (0..w * h).map(|i| 600 + ((i % w) * 30 + (i / w) * 35) as u16).collect(); + let f = dir.join("xtrans.dng"); + std::fs::write(&f, synthetic_dng_cfa(w, h, lcc_raw::Cfa::xtrans(), data, None, Default::default())).unwrap(); + let runs = Arc::new(AtomicUsize::new(0)); + let spec = crate::denoise::JobSpec { + path: f.to_string_lossy().into_owned(), + read: None, + product: dir.join("xtrans.lcdn"), + key: "k".into(), + manifest: manifest("stand-in"), + onnx: dir.join("model.onnx"), + model: Default::default(), + loader: dim_loader(&runs), + parallel: 2, + run_on: RunOn::Auto, + }; + assert_eq!(crate::denoise::make_product(&spec, None), Ok(true)); + let header = lcc_denoise::product::read_header_at(&spec.product).unwrap(); + assert_eq!((header.width, header.height), (w, h), "the denoised picture keeps the sensor's size"); + let rgb = lcc_denoise::product::read(&spec.product, "k", 1).unwrap(); + assert_eq!((rgb.width, rgb.height), (w, h)); + assert!(rgb.data.iter().flatten().all(|v| v.is_finite()), "no sample is left non-finite"); + assert!(rgb.data.iter().any(|p| p.iter().any(|v| *v > 0.0)), "the picture is not all black"); + assert_eq!(crate::denoise::make_product(&spec, None), Ok(false), "the product is already there"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The denoised picture of an X-Trans file is used where the photo is shown, not only made: in a preview binned 3 × 3 +/// (the only binning X-Trans allows) and at full size, from a default crop whose sides 3 does not divide. Before +/// non-Bayer sensors could be denoised nothing ever read such a product, and a twin that does not match the plain +/// picture's size is silently dropped, so a mismatch here would leave the Amount slider doing nothing in the loupe. +#[test] +fn an_x_trans_photo_shows_its_denoised_picture_binned_and_at_full_size() { + use crate::media::DenoiseSpec; + let dir = temp_dir("xtrans-twin"); + let (w, h) = (384usize, 288usize); + let data: Vec = (0..w * h).map(|i| 900 + ((i % w) * 23 + (i / w) * 31 + (i * 7919) % 401) as u16).collect(); + let mut raw = lcc_raw::decode(&synthetic_dng_cfa(w, h, lcc_raw::Cfa::xtrans(), data, None, Default::default())).unwrap(); + raw.crop = lcc_raw::Rect::new(5, 7, 371, 271); + let bytes = lcc_raw::write_dng(&raw, &Default::default()).unwrap(); + assert_eq!(lcc_raw::decode(&bytes).unwrap().crop, raw.crop, "the crop survives the DNG"); + let f = dir.join("xtrans.dng"); + std::fs::write(&f, &bytes).unwrap(); + let spec = crate::denoise::JobSpec { + path: f.to_string_lossy().into_owned(), + read: None, + product: dir.join("xtrans.lcdn"), + key: "k".into(), + manifest: manifest("stand-in"), + onnx: dir.join("model.onnx"), + model: Default::default(), + loader: dim_loader(&Arc::new(AtomicUsize::new(0))), + parallel: 2, + run_on: RunOn::Auto, + }; + assert_eq!(crate::denoise::make_product(&spec, None), Ok(true)); + let twin = DenoiseSpec { product: spec.product.clone(), key: "k".into(), make: None }; + for (max_edge, binned) in [(128, true), (100_000, false)] { + let (plain, denoised, _) = crate::files::load_vec_pair(bytes.clone(), max_edge, &twin, crate::media::LoadOptions::default()).unwrap(); + assert_eq!(plain.width < 371, binned, "max_edge {max_edge}: {}×{}", plain.width, plain.height); + let denoised = denoised.unwrap_or_else(|| panic!("max_edge {max_edge}: the denoised picture was dropped")); + assert_eq!((denoised.width, denoised.height), (plain.width, plain.height), "max_edge {max_edge}"); + // the stand-in model halves every sample: the picture shown is the denoised one, not the plain one again + let mean = |img: &lcc_raster::Rgb32f| img.data.iter().map(|p| f64::from(p[1])).sum::() / img.data.len() as f64; + assert!(mean(&denoised) < 0.75 * mean(&plain), "max_edge {max_edge}: {} vs {}", mean(&denoised), mean(&plain)); + } + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn two_threads_making_the_same_picture_make_it_once() { let dir = temp_dir("twice"); diff --git a/crates/engine/src/tests_xmp.rs b/crates/engine/src/tests_xmp.rs index 9ce598eaee..9a213aa86b 100644 --- a/crates/engine/src/tests_xmp.rs +++ b/crates/engine/src/tests_xmp.rs @@ -924,8 +924,12 @@ pub(crate) fn synthetic_dng_with(xmp: Option<&str>, metadata: lcc_meta::Metadata /// A synthetic Bayer DNG for denoise and cache tests. pub(crate) fn synthetic_dng_of(w: usize, h: usize, cfa: &str, data: Vec, xmp: Option<&str>, metadata: lcc_meta::Metadata) -> Vec { + synthetic_dng_cfa(w, h, lcc_raw::Cfa::bayer(cfa).unwrap(), data, xmp, metadata) +} + +/// [`synthetic_dng_of`] for any colour filter array, Bayer or not (X-Trans). +pub(crate) fn synthetic_dng_cfa(w: usize, h: usize, cfa: lcc_raw::Cfa, data: Vec, xmp: Option<&str>, metadata: lcc_meta::Metadata) -> Vec { use lcc_raw::*; - let cfa = Cfa::bayer(cfa).unwrap(); let raw = RawImage { format: RawFormat::Dng, width: w, diff --git a/crates/raw/src/demosaic/mod.rs b/crates/raw/src/demosaic/mod.rs index ee1b00d80d..423e6e66ab 100644 --- a/crates/raw/src/demosaic/mod.rs +++ b/crates/raw/src/demosaic/mod.rs @@ -16,6 +16,8 @@ //! - [`Method::Ppg`] → `xtrans::directional`: our own edge-weighted colour-difference interpolation (faster). //! - [`Method::Bilinear`] → bilinear. //! +//! [`remosaic_rggb`] goes the other way, for callers that need Bayer geometry from a sensor that has none. +//! //! Every method reproduces a constant-colour mosaic exactly. mod ahd; @@ -150,6 +152,40 @@ pub fn demosaic_with(n: &Normalized, method: Method, opts: Options) -> Rgb32f { } } +/// Adapted from upstream #1828; the fork's quality X-Trans path (`xtrans_ri`) is not used here. +/// A non-Bayer mosaic (Fujifilm X-Trans, …) rebuilt as an RGGB mosaic of the same size, so that tools +/// written around Bayer geometry can read a sensor they were not written for: the AI denoiser, whose +/// model contract is four RGGB planes. The mosaic is interpolated as `xtrans::directional` ([`Method::Ppg`]) would and one channel is +/// kept per site, the one RGGB wants there, without building the full RGB picture in between. +/// +/// Where the sensor already carries that colour at that site the interpolation returns the sample +/// itself, so those sites keep their original value and their original noise, while the rest are +/// interpolated and so already a little smoother. Anything reading the result sees noise that varies +/// from site to site, and the interpolation's own errors: this is an approximation of the sensor, not +/// the sensor. +/// +/// `None` when the mosaic is not one this can rebuild: already demosaiced data (`cpp != 1`), no CFA, a +/// CFA that is already Bayer (read that one as it is), a pattern whose size does not match its colours +/// or holding a colour that is not red, green or blue (RGBE, CYGM) or missing one of the three, or a +/// size that does not match the samples. +pub fn remosaic_rggb(n: &Normalized) -> Option { + let cfa = n.cfa.as_ref()?; + if n.cpp != 1 || cfa.is_bayer() { + return None; + } + if cfa.width == 0 || cfa.height == 0 || cfa.width.checked_mul(cfa.height) != Some(cfa.pattern.len()) { + return None; + } + if !(0..=2).all(|c| cfa.pattern.contains(&c)) || cfa.pattern.iter().any(|&c| c > 2) { + return None; + } + if n.width == 0 || n.height == 0 || n.width.checked_mul(n.height) != Some(n.data.len()) { + return None; + } + let data = xtrans::rggb(&Mosaic { w: n.width, h: n.height, data: &n.data, cfa }); + Some(Normalized { width: n.width, height: n.height, cpp: 1, data, cfa: Some(Cfa::bayer_static("RGGB")) }) +} + /// Build a mosaic from an RGB image by sampling each pixel's CFA colour (for tests and synthetic data). pub fn mosaic_from_rgb(img: &Rgb32f, cfa: &Cfa) -> Normalized { let data = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).map(|(x, y)| img.get(x, y)[cfa.color_at(x, y) as usize]).collect(); @@ -179,6 +215,13 @@ pub fn psnr(a: &Rgb32f, b: &Rgb32f, border: usize) -> f64 { mod tests { use super::*; + fn smooth_scene(w: usize, h: usize) -> Rgb32f { + Rgb32f::from_fn(w, h, |x, y| { + let (fx, fy) = (x as f32 / w as f32, y as f32 / h as f32); + [0.2 + 0.6 * fx * fy, 0.3 + 0.4 * (fx * 3.0).sin().abs() * 0.5 + 0.2 * fy, 0.1 + 0.5 * (1.0 - fx) * (0.5 + 0.5 * (fy * 5.0).cos())] + }) + } + /// A photo-like scene: sharp luminance structure (disc, stripes, diagonal edge, fine texture) modulating a /// smoothly varying colour — edges are mostly luminance edges, as in natural images. fn edgy_scene(w: usize, h: usize) -> Rgb32f { @@ -384,4 +427,172 @@ mod tests { assert_eq!(reflect(3, 1), 0); assert_eq!(reflect(-7, 2), 1); } + + /// The single-pass re-mosaic must give exactly what demosaicing and then keeping each site's RGGB + /// colour gives: every phase of the pattern, the borders, and samples with no structure to hide behind. + #[test] + fn remosaic_matches_the_demosaic_sampled_as_rggb() { + let mut seed = 2024u32; + for (dx, dy) in [(0, 0), (1, 2), (5, 3)] { + let cfa = Cfa::xtrans().shifted(dx, dy); + let (w, h) = (37, 29); + let data: Vec = (0..w * h) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 + }) + .collect(); + let n = Normalized { width: w, height: h, cpp: 1, data, cfa: Some(cfa) }; + let want = mosaic_from_rgb(&demosaic(&n, Method::Ppg), &Cfa::bayer("RGGB").unwrap()); + let got = remosaic_rggb(&n).unwrap(); + assert_eq!((got.width, got.height, got.cpp), (w, h, 1)); + assert!(got.data.iter().zip(&want.data).all(|(a, b)| a.to_bits() == b.to_bits()), "phase ({dx}, {dy})"); + } + } + + #[test] + fn remosaic_keeps_a_constant_colour_exactly() { + let colour = [0.3f32, 0.55, 0.8]; + let n = mosaic_from_rgb(&Rgb32f::filled(19, 14, colour), &Cfa::xtrans()); + let r = remosaic_rggb(&n).unwrap(); + let cfa = r.cfa.clone().unwrap(); + assert_eq!(cfa.name(), "RGGB"); + for y in 0..r.height { + for x in 0..r.width { + let want = colour[cfa.color_at(x, y) as usize]; + assert!((r.data[y * r.width + x] - want).abs() < 1e-5, "({x}, {y})"); + } + } + } + + /// The sites where X-Trans already carries the colour RGGB wants keep their own sample, untouched. + #[test] + fn remosaic_keeps_the_samples_the_two_patterns_share() { + let img = edgy_scene(40, 32); + let xt = Cfa::xtrans(); + let n = mosaic_from_rgb(&img, &xt); + let r = remosaic_rggb(&n).unwrap(); + let rggb = r.cfa.clone().unwrap(); + let mut shared = 0; + for y in 0..32 { + for x in 0..40 { + let c = rggb.color_at(x, y); + if xt.color_at(x, y) != c { + continue; + } + shared += 1; + assert_eq!(r.data[y * 40 + x].to_bits(), img.get(x, y)[c as usize].to_bits(), "({x}, {y})"); + } + } + // about two sites in five: 20/36 greens against RGGB's half, 8/36 reds and blues against its quarters + assert!(shared > 40 * 32 / 4, "only {shared} shared sites"); + } + + /// Reading the re-mosaic back as Bayer costs a little against demosaicing the X-Trans mosaic directly, + /// but must stay close: it is the picture the denoiser's Bayer contract starts from. + #[test] + fn remosaic_round_trip_stays_close_to_the_direct_demosaic() { + for img in [smooth_scene(96, 80), edgy_scene(96, 80)] { + let n = mosaic_from_rgb(&img, &Cfa::xtrans()); + let direct = psnr(&img, &demosaic(&n, Method::Ppg), 6); // the interpolator the re-mosaic uses + let through = psnr(&img, &demosaic(&remosaic_rggb(&n).unwrap(), Method::Ahd), 6); + eprintln!("direct {direct:.1} dB, through RGGB {through:.1} dB"); + assert!(through > 24.0, "through RGGB {through:.1} dB"); + assert!(through > direct - 2.0, "through RGGB {through:.1} dB against direct {direct:.1} dB"); + } + } + + #[test] + fn remosaic_refuses_what_it_cannot_rebuild() { + let img = smooth_scene(12, 10); + let xtrans = || mosaic_from_rgb(&img, &Cfa::xtrans()); + // already Bayer: the caller reads that mosaic as it is + assert!(remosaic_rggb(&mosaic_from_rgb(&img, &Cfa::bayer("GRBG").unwrap())).is_none()); + // already demosaiced + let mut three = xtrans(); + three.cpp = 3; + assert!(remosaic_rggb(&three).is_none()); + // no colour filter array at all (a monochrome sensor) + let mut mono = xtrans(); + mono.cfa = None; + assert!(remosaic_rggb(&mono).is_none()); + // a fourth colour (RGBE), a pattern missing blue, and patterns whose size does not match their colours + // (a zero side would divide by zero when looking a colour up, a short pattern would read past its end) + for (width, height, pattern) in + [(2, 2, vec![0, 1, 1, 3]), (2, 2, vec![0, 1, 1, 1]), (0, 2, vec![0, 1, 2]), (2, 2, vec![0, 1, 2]), (6, 6, vec![])] + { + let mut odd = xtrans(); + odd.cfa = Some(Cfa { width, height, pattern }); + assert!(remosaic_rggb(&odd).is_none(), "{width}×{height}"); + } + // samples that do not match the size + let mut short = xtrans(); + short.data.pop(); + assert!(remosaic_rggb(&short).is_none()); + let mut empty = xtrans(); + (empty.width, empty.height, empty.data) = (0, 0, Vec::new()); + assert!(remosaic_rggb(&empty).is_none()); + } + + /// The re-mosaic on a real non-Bayer file, which no synthetic pattern stands in for (the active-area crop + /// moves the pattern's phase, and sensor noise is what the denoiser is given the result for): + /// `LC_XTRANS_RAW= cargo test --release -p lcc-raw --lib -- --ignored --nocapture remosaic_a_real_file` + #[test] + #[ignore = "needs LC_XTRANS_RAW pointing at a real non-Bayer raw file"] + fn remosaic_a_real_file() { + let Some(path) = std::env::var_os("LC_XTRANS_RAW") else { + lcc_testkit::skip!(Input, "set LC_XTRANS_RAW="); + return; + }; + let raw = crate::decode(&std::fs::read(&path).unwrap()).unwrap(); + let n = raw.normalized().unwrap(); + let cfa = n.cfa.clone().unwrap(); + assert!(!cfa.is_bayer(), "not a non-Bayer file"); + let t = std::time::Instant::now(); + let r = remosaic_rggb(&n).unwrap(); + let ms = t.elapsed().as_secs_f64() * 1e3; + assert_eq!((r.width, r.height), (n.width, n.height)); + assert!(r.data.iter().all(|v| v.is_finite())); + let rggb = r.cfa.clone().unwrap(); + let (mut shared, mut kept) = (0usize, 0usize); + for y in 0..n.height { + for x in 0..n.width { + if cfa.color_at(x, y) == rggb.color_at(x, y) { + shared += 1; + kept += usize::from(r.data[y * n.width + x].to_bits() == n.data[y * n.width + x].to_bits()); + } + } + } + let t = std::time::Instant::now(); + let direct = demosaic(&n, Method::Ahd); + let direct_ms = t.elapsed().as_secs_f64() * 1e3; + println!( + "{}×{}: re-mosaic {ms:.0} ms (a full demosaic {direct_ms:.0} ms), {shared} shared sites ({:.1} %), {kept} of them \ + untouched, PSNR through RGGB against the direct demosaic {:.1} dB", + n.width, + n.height, + 100.0 * shared as f64 / (n.width * n.height) as f64, + psnr(&direct, &demosaic(&r, Method::Ahd), 8) + ); + assert_eq!(kept, shared, "a shared site lost its own sample"); + } + + #[test] + #[ignore] + fn throughput() { + let (w, h) = (6000, 4000); + let img = smooth_scene(w, h); + let cfa = Cfa::bayer("RGGB").unwrap(); + let n = mosaic_from_rgb(&img, &cfa); + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let t = std::time::Instant::now(); + let _ = demosaic(&n, m); + let s = t.elapsed().as_secs_f64(); + println!("{m:?}: {:.1} MP/s ({:.0} ms for 24 MP)", (w * h) as f64 / 1e6 / s, s * 1e3); + } + let n = mosaic_from_rgb(&img, &Cfa::xtrans()); + let t = std::time::Instant::now(); + let _ = demosaic(&n, Method::Ahd); + println!("X-Trans directional: {:.1} MP/s", (w * h) as f64 / 1e6 / t.elapsed().as_secs_f64()); + } } diff --git a/crates/raw/src/demosaic/xtrans.rs b/crates/raw/src/demosaic/xtrans.rs index 32768ea8d6..af814f4bb4 100644 --- a/crates/raw/src/demosaic/xtrans.rs +++ b/crates/raw/src/demosaic/xtrans.rs @@ -139,6 +139,45 @@ fn green(m: &Mosaic, off: &Offsets) -> Vec { g } +/// Step 2 at an interior pixel `i` with green `gp`: green plus the edge-weighted mean colour difference of +/// the same-colour samples at `list` (precomputed offsets, no reflection). +#[inline] +fn colour_inside(m: &Mosaic, g: &[f32], i: usize, gp: f32, list: &[(isize, isize)]) -> f32 { + let w = m.w as isize; + let (mut s, mut ws) = (0.0f32, 0.0f32); + for &(dx, dy) in list { + let j = (i as isize + dy * w + dx) as usize; + let gq = g[j]; + let d2 = (dx * dx + dy * dy) as f32; + let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); + s += wt * (m.data[j] - gq); + ws += wt; + } + if ws > 0.0 { gp + s / ws } else { gp } +} + +/// Step 2 near the border, for colour `c` (0 red, 2 blue) at `(x, y)` with green `gp`: the 5×5 +/// neighbourhood read with reflection. +#[inline] +fn colour_at_border(m: &Mosaic, g: &[f32], x: isize, y: isize, gp: f32, c: usize) -> f32 { + let (w, h) = (m.w, m.h); + let gg = |x: isize, y: isize| g[super::reflect(y, h) * w + super::reflect(x, w)]; + let (mut s, mut ws) = (0.0f32, 0.0f32); + for dy in -2isize..=2 { + for dx in -2isize..=2 { + if m.color(x + dx, y + dy) as usize != c { + continue; + } + let gq = gg(x + dx, y + dy); + let d2 = (dx * dx + dy * dy) as f32; + let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); + s += wt * (m.get(x + dx, y + dy) - gq); + ws += wt; + } + } + if ws > 0.0 { gp + s / ws } else { gp } +} + pub(crate) fn directional(m: &Mosaic) -> Rgb32f { let (w, h) = (m.w, m.h); let off = Offsets::new(m); @@ -153,50 +192,50 @@ pub(crate) fn directional(m: &Mosaic) -> Rgb32f { let i = y * w + x; let own = m.cfa.color_at(x, y) as usize; let gp = g[i]; - px[1] = gp; let lists = &off.rb[off.phase(x, y)]; - for (li, c) in [0usize, 2].into_iter().enumerate() { - if c == own { - px[c] = m.data[i]; - continue; - } - let (mut s, mut ws) = (0.0f32, 0.0f32); - for &(dx, dy) in &lists[li] { - let j = (i as isize + dy * w as isize + dx) as usize; - let gq = g[j]; - let d2 = (dx * dx + dy * dy) as f32; - let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); - s += wt * (m.data[j] - gq); - ws += wt; - } - px[c] = if ws > 0.0 { gp + s / ws } else { gp }; - } + px[1] = gp; + px[0] = if own == 0 { m.data[i] } else { colour_inside(m, &g, i, gp, &lists[0]) }; + px[2] = if own == 2 { m.data[i] } else { colour_inside(m, &g, i, gp, &lists[1]) }; continue; } let x = x as isize; let own = m.color(x, yi) as usize; let gp = gg(x, yi); px[1] = gp; - for c in [0usize, 2] { - if c == own { - px[c] = m.get(x, yi); + px[0] = if own == 0 { m.get(x, yi) } else { colour_at_border(m, &g, x, yi, gp, 0) }; + px[2] = if own == 2 { m.get(x, yi) } else { colour_at_border(m, &g, x, yi, gp, 2) }; + } + }); + out +} + +/// The mosaic interpolated and read back as RGGB: sample for sample what [`directional`] followed by +/// keeping the RGGB colour of each site gives, without the full RGB picture in between — a third of the +/// memory, and one colour interpolated only at the sites that want red or blue. +pub(crate) fn rggb(m: &Mosaic) -> Vec { + let (w, h) = (m.w, m.h); + let off = Offsets::new(m); + let g = green(m, &off); + let mut out = vec![0f32; w * h]; + par_rows(&mut out, w, |y, row| { + let interior_y = y >= 2 && y + 2 < h; + let yi = y as isize; + for (x, o) in row.iter_mut().enumerate() { + let i = y * w + x; + let c = match (y % 2, x % 2) { + (0, 0) => 0, + (1, 1) => 2, + _ => { + *o = g[i]; continue; } - let (mut s, mut ws) = (0.0f32, 0.0f32); - for dy in -2isize..=2 { - for dx in -2isize..=2 { - if m.color(x + dx, yi + dy) as usize != c { - continue; - } - let gq = gg(x + dx, yi + dy); - let d2 = (dx * dx + dy * dy) as f32; - let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); - s += wt * (m.get(x + dx, yi + dy) - gq); - ws += wt; - } - } - px[c] = if ws > 0.0 { gp + s / ws } else { gp }; + }; + if interior_y && x >= 2 && x + 2 < w { + *o = if m.cfa.color_at(x, y) as usize == c { m.data[i] } else { colour_inside(m, &g, i, g[i], &off.rb[off.phase(x, y)][c / 2]) }; + continue; } + let x = x as isize; + *o = if m.color(x, yi) as usize == c { m.get(x, yi) } else { colour_at_border(m, &g, x, yi, g[i], c) }; } }); out diff --git a/docs/denoise.md b/docs/denoise.md index 22880ccd32..75df74f97c 100644 --- a/docs/denoise.md +++ b/docs/denoise.md @@ -370,7 +370,18 @@ Native apps enable inference through their `denoise` feature. A build without it the web build report inference unavailable. Manifest/cache primitives still compile for WASM. Settings and models remain opt-in; nothing is downloaded on launch. -This implementation supports **Bayer RAW only**. X-Trans, Foveon, demosaiced DNG and -non-RAW images remain unsupported by this model contract. No measured quality parity -with Lightroom is claimed. Apple/Metal and wider hardware verification, model policy, +The model contract itself is **Bayer only**. A non-Bayer colour filter array — Fujifilm's +X-Trans, and any other pattern laid out in red, green and blue — reaches it through a +re-mosaic: the sensor is interpolated and read back as an RGGB mosaic of the same size +(`remosaic_rggb`, `crates/raw/src/demosaic`), so the picture keeps its resolution and every +step after the model is unchanged. It interpolates only the colour each site needs, without +the full RGB picture in between: on a 26 MP X-Trans frame it takes ~65 ms (a full demosaic +~80 ms) and holds three planes at once, the mosaic, its green and the RGGB copy, under its +own share of the working-memory gate. 39 % of the frame's sites already carry the colour +RGGB wants there and keep the sensor's own sample, and reading the result back as RGB comes +within 42 dB (PSNR) of demosaicing the X-Trans mosaic directly. The rest reach the model +already interpolated, so it sees noise that varies from site to site: this is an +approximation of an X-Trans sensor, not a model trained on one, and its quality is +unmeasured. Foveon, demosaiced DNG and non-RAW +images remain unsupported. No measured quality parity with Lightroom is claimed. Apple/Metal and wider hardware verification, model policy, a linear-RGB contract and a side-by-side fidelity suite remain future work. diff --git a/docs/gaps.md b/docs/gaps.md index b390033522..148a863e77 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -2,7 +2,7 @@ - 2026-10-12: Print colour management (G15): printer ICC profile, Perceptual / Relative with black point compensation, Print Adjustment, 16-bit PDF output. -> **Last updated:** 2026-11-27 · **Change:** patch (gap 41 narrows: a Lightroom import is committed and saved in parts, #1361); patch (gap 41 narrows: a large step is saved as many small log records, #1361); imported photos' metadata status compares their sidecars with the catalog, in step or a conflict, #1312); patch (gap 41 narrows: no row cap on Lightroom import tables, a memory budget from the computer instead, #1361); patch (gaps 13 and 41 narrow: cached-XMP records over 64 MiB and packets over 16 MiB are read without their camera-profile tables, #1311); patch (gap 39: ONNX Runtime on the GPU exists, #491; the aesthetic model is what is left); patch (gap 41 narrows: the recovery archive and the history settings budget follow the drive, the catalog and the memory, newest steps first, #1312); patch (feature-freeze parity pass: CF-PROCESS-RECIPES row restored, gap 43 cites the skin-uniformity row; no ranked gap closes); patch (#1360: scoped, cancellable face maintenance and confirmed reset; no ranked gap closes); patch (gap 42 narrows: OpenEXR scene-linear export, plan 7.5); minor (gap 11: Lens Blur renders from the depth model or the subject, focus picker and bokeh shapes, plan 7.1); patch (gap 16: plug-in publish services get the account, collection, photo metadata and remote comments, plan 7.14); patch (gap 43 narrows: skin-tone uniformity on Point Color, plan 7.9); patch (gap 43: Match Look, Capture One's Smart Adjustments, plan 7.6); minor (gap 18 narrows: lens corrections, Upright and Transform on video frames, poster frame picked, plan 7.11); patch (gap 43 narrows: process recipes, several export presets in one run with one decode per photo, plan 7.4); minor (gap 42 narrows: Tone Equalizer ported from darktable, plan 7.10); minor (gap 42 narrows: inpaint opposed and guided Laplacian highlight reconstruction, ported from darktable, plan 7.2); minor (adaptive presets, plan 7.8; no gap change: P2 rows without a gap entry; adaptive profiles left); patch (the Export screen previews the first photo as its file will be, with an SDR / HDR choice; minor (HDR export: gain map files for AVIF and JPEG XL with `hdrMode: gainMap`, LR-HDR-EXPORT; no ranked gap closes); patch (gap 37: OS folder notifications, single-instance hand-off, URL scheme on Windows and Linux, plan 5.9); patch (gap 43 narrows: speed-edit keys, hold a key and drag or scroll to move a Develop slider, plan 5.10); patch (gap 23: the brush by keyboard; Library and Develop core widgets checked in the AccessKit tree, plan 5.8); patch (gap 26: 100k wheel-scroll frame timed frame by frame, 3–5 ms median, within budget, plan 4.8); minor (gap 2 narrows: CRX partial subbands, multi-tile 0x200 and adaptive low-frequency gains decode, ported from LibRaw `crx.cpp`, synthetic tests only); patch (gap 1: LibRaw matrices for about 400 newer bodies; every body with a pinned sample has colour matrices; SIL ΔE cross-check; no chart shots yet); patch (gap 8: lensfun's database fetched on first run, picked lens written to XMP, plan 3.9); minor (gap 10: SRF and S200 EXR RAF decode, 47 Olympus / OM bodies verified: 645 verified, 89% on a verified body; target not met); minor (gap 19: the plug-in marketplace — search, install, update, remove and opt-in automatic updates from an index of each plug-in's newest release, vetted and community tiers); patch (gap 9: weekly model-reference job for SAM 2.1, BiRefNet, EoMT and MediaPipe); patch (gap 1: LibRaw matrices for six newer bodies that used the neutral matrix, #451; no chart shots yet); patch (gap 3: render-fidelity reference suite with ΔE2000 / SSIM tolerances and a synthetic ColorChecker check, plan 3.5); patch (gap 3: process V10 applies the Tone Curve in a wide working space, #1142); patch (gap 1: one ranked colour-source order, a Lightroom calibration that loses to the per-photo JPEG fit serves converted DNGs only, #1119; Adobe Standard DNGs without a tone curve get their BaselineExposure once more, #1174); minor (gaps 41–43: Lightroom migration limits left from #1311 / #1312, darktable raw-processing depth, Capture One workflow features); patch (gap 9: PRs run changed-crate tests; the nightly full run covers macOS and Windows, files an issue when red, and blocks releases); patch (gap 40 closed: `apps/android` denies `indexing_slicing`, clippy runs on it in the Android check); patch (never-crash tooling: pure-Rust fuzz targets with a nightly long run; no gap change); patch (gap 40: `apps/cli` and the chart-profile dialog converted); patch (tests only: loopback mock servers for generative fill errors, publish uploads while the server is down and misbehaving IPP printers; slideshow export in SIL; no gap changes); patch (gap 9: nightly corpus + fonts run with a skip gate, GPU equivalence on software adapters); patch (gap 37: folder polling notices new dated folders in a photo tree); minor (gap 38 closed: mixed metadata across a selection, `photo.sharedMeta`); patch (gap 9: timing probes and benchmarks are opt-in `probe` skips, not `#[ignore]`); patch (gap 9: engine import → export → re-import SIL scenario); minor (gap 40 added: checked indexing in the UI; unconverted modules carry a tracked allow); patch (gap 31: the sync merge rules are property-tested in the SIL run); patch (gap 13: required-table record losses always warned; remaining Lightroom size limits listed, #1311); patch (gap 13: the Lightroom import index is no longer capped at 16 MiB, #1312); patch (gap 13: one bad Lightroom record costs only itself; keyword assignments streamed, #1311); minor (gap 19: signed plug-ins find updates in their author's feed, checked when the Plug-in Manager opens and installed by the user); minor (gap 19: plug-in author signatures pin a plug-in's signer, #1271); minor (People: the People view sorts faces into Unknown, Suggested and Confirmed, and reviews the suggested ones a person at a time, #1050); minor (gap 20: Nikon NEFX, NX Studio's merged pixel-shift images, decodes; ARQ pixel shift is what is left of pixel shift); minor (gap 13: Capture One develop settings — exposure, orientation, crop, flips, white balance); minor (gap 13: saved prints in Lightroom catalogs import as Saved Prints with their layout); minor (gap 33 closed: the translation coverage check reads `trf!` and the helpers that translate; gap 21 re-measured: every language has every interface message); minor (gap 19: plug-ins look at a photo's pixels, set its crop and make virtual copies, #891); minor (gap 5: AI mask edges follow the photo's, no outline under a raised Exposure, upstream #3298); minor (gap 11 narrows: AI Super Resolution and AI Sharpen with an opt-in upscaler, upstream #3493); minor (gap 11 narrows: AI Denoise for finished pictures, upstream #3279); patch (gap 36: the ISO country code is carried over in preset save and import, #784); minor (gap 5: AI masks as recipes computed on the AI worker, Update AI Mask, masks under geometry, a Color Mixer per mask); patch (gap 26: smoother edits and lasting previews); minor (gap 5: Object masks can run on SAM 2.1, an open model, ported from OneSlips); minor (gap 12: generative remove through cloud providers with your own key, from OneSlips); minor (gap 36: the IPTC Content fields — headline, description writer, category, supplemental categories, subject codes — are stored, so Lightroom metadata presets carry them); minor (gap 19: plug-ins add a tool's files to the library, stacked or in the source album); minor (gap 19: plug-ins start installed programs; plug-in work no longer on hold); minor (gap 11: AI Denoise works out of the box with a built-in BM3D denoiser, upstream #2982); minor (gap 1: colour-chart calibration); patch (gap 1: calibrations matched to other editors); minor (gap 11 shrinks: the upstream project's own AI Denoise model is a download in the desktop app); patch (gap 3: probe DNGs and slider sweeps); minor (gap 1: dcraw's colour matrices replace the neutral fallback for about 550 models); patch (gap 3: `calibrate-lightroom verify`, edited raws against edited exports); patch (gap 3: ` compare`, ΔE00 between renders from any editor); minor (gaps 1 and 3: Lightroom-matched calibration tool, 0 cameras calibrated yet); minor (upstream merge: gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: grid-cycle key shown in View, #2500; gap 21: Thai glyphs in export text, #2052; gap 15: Japanese photo and postcard paper sizes); patch (HDR zoom: recent windows kept, encoded off the UI thread); patch (HDR adjustment previews: review follow-up); minor (upstream merge: gap 38 added: multi-select metadata editing UI, upstream's gap 30; XMP foreign namespaces and PSD/PSB embedded metadata, no gap change); patch (HDR adjustment previews keep float HDR output during slider drags); minor (opt-in Windows VRR compositor workaround); minor (gap 37 added: folder watching leftovers after issue #123's polling); minor (gap 36 added: what preset import doesn't carry over); minor (M15 decisions: CMYK won't do; Flickr / SmugMug and tethering blocked); minor (gap 11: the Enhance dialog); minor (gap 14 closed: HDR renders on the GPU; X11 SDR is a platform limit); minor (gap 14 narrows: zoomed, Before/After, Compare and second window show HDR, HDR Preview toggle); minor (gap 11 narrows: Raw Details and Super Resolution; gap 18: M14 closed, interlaced H.264 and faster AV1); minor (full audit 2026-10-20: rows refreshed against code; gaps 8 and 2 no longer beta blockers; gaps 34–35 added: Android camera roll and built-in camera; gap 34 narrows: picked folders rescanned); minor (gap 29 narrows: JPEG response curves and half-float frames) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last updated:** 2026-11-29 · **Change:** patch (gap 11 narrows: X-Trans reaches AI denoise through an RGGB re-mosaic, upstream #1828); patch (gap 41 narrows: a Lightroom import is committed and saved in parts, #1361); patch (gap 41 narrows: a large step is saved as many small log records, #1361); imported photos' metadata status compares their sidecars with the catalog, in step or a conflict, #1312); patch (gap 41 narrows: no row cap on Lightroom import tables, a memory budget from the computer instead, #1361); patch (gaps 13 and 41 narrow: cached-XMP records over 64 MiB and packets over 16 MiB are read without their camera-profile tables, #1311); patch (gap 39: ONNX Runtime on the GPU exists, #491; the aesthetic model is what is left); patch (gap 41 narrows: the recovery archive and the history settings budget follow the drive, the catalog and the memory, newest steps first, #1312); patch (feature-freeze parity pass: CF-PROCESS-RECIPES row restored, gap 43 cites the skin-uniformity row; no ranked gap closes); patch (#1360: scoped, cancellable face maintenance and confirmed reset; no ranked gap closes); patch (gap 42 narrows: OpenEXR scene-linear export, plan 7.5); minor (gap 11: Lens Blur renders from the depth model or the subject, focus picker and bokeh shapes, plan 7.1); patch (gap 16: plug-in publish services get the account, collection, photo metadata and remote comments, plan 7.14); patch (gap 43 narrows: skin-tone uniformity on Point Color, plan 7.9); patch (gap 43: Match Look, Capture One's Smart Adjustments, plan 7.6); minor (gap 18 narrows: lens corrections, Upright and Transform on video frames, poster frame picked, plan 7.11); patch (gap 43 narrows: process recipes, several export presets in one run with one decode per photo, plan 7.4); minor (gap 42 narrows: Tone Equalizer ported from darktable, plan 7.10); minor (gap 42 narrows: inpaint opposed and guided Laplacian highlight reconstruction, ported from darktable, plan 7.2); minor (adaptive presets, plan 7.8; no gap change: P2 rows without a gap entry; adaptive profiles left); patch (the Export screen previews the first photo as its file will be, with an SDR / HDR choice; minor (HDR export: gain map files for AVIF and JPEG XL with `hdrMode: gainMap`, LR-HDR-EXPORT; no ranked gap closes); patch (gap 37: OS folder notifications, single-instance hand-off, URL scheme on Windows and Linux, plan 5.9); patch (gap 43 narrows: speed-edit keys, hold a key and drag or scroll to move a Develop slider, plan 5.10); patch (gap 23: the brush by keyboard; Library and Develop core widgets checked in the AccessKit tree, plan 5.8); patch (gap 26: 100k wheel-scroll frame timed frame by frame, 3–5 ms median, within budget, plan 4.8); minor (gap 2 narrows: CRX partial subbands, multi-tile 0x200 and adaptive low-frequency gains decode, ported from LibRaw `crx.cpp`, synthetic tests only); patch (gap 1: LibRaw matrices for about 400 newer bodies; every body with a pinned sample has colour matrices; SIL ΔE cross-check; no chart shots yet); patch (gap 8: lensfun's database fetched on first run, picked lens written to XMP, plan 3.9); minor (gap 10: SRF and S200 EXR RAF decode, 47 Olympus / OM bodies verified: 645 verified, 89% on a verified body; target not met); minor (gap 19: the plug-in marketplace — search, install, update, remove and opt-in automatic updates from an index of each plug-in's newest release, vetted and community tiers); patch (gap 9: weekly model-reference job for SAM 2.1, BiRefNet, EoMT and MediaPipe); patch (gap 1: LibRaw matrices for six newer bodies that used the neutral matrix, #451; no chart shots yet); patch (gap 3: render-fidelity reference suite with ΔE2000 / SSIM tolerances and a synthetic ColorChecker check, plan 3.5); patch (gap 3: process V10 applies the Tone Curve in a wide working space, #1142); patch (gap 1: one ranked colour-source order, a Lightroom calibration that loses to the per-photo JPEG fit serves converted DNGs only, #1119; Adobe Standard DNGs without a tone curve get their BaselineExposure once more, #1174); minor (gaps 41–43: Lightroom migration limits left from #1311 / #1312, darktable raw-processing depth, Capture One workflow features); patch (gap 9: PRs run changed-crate tests; the nightly full run covers macOS and Windows, files an issue when red, and blocks releases); patch (gap 40 closed: `apps/android` denies `indexing_slicing`, clippy runs on it in the Android check); patch (never-crash tooling: pure-Rust fuzz targets with a nightly long run; no gap change); patch (gap 40: `apps/cli` and the chart-profile dialog converted); patch (tests only: loopback mock servers for generative fill errors, publish uploads while the server is down and misbehaving IPP printers; slideshow export in SIL; no gap changes); patch (gap 9: nightly corpus + fonts run with a skip gate, GPU equivalence on software adapters); patch (gap 37: folder polling notices new dated folders in a photo tree); minor (gap 38 closed: mixed metadata across a selection, `photo.sharedMeta`); patch (gap 9: timing probes and benchmarks are opt-in `probe` skips, not `#[ignore]`); patch (gap 9: engine import → export → re-import SIL scenario); minor (gap 40 added: checked indexing in the UI; unconverted modules carry a tracked allow); patch (gap 31: the sync merge rules are property-tested in the SIL run); patch (gap 13: required-table record losses always warned; remaining Lightroom size limits listed, #1311); patch (gap 13: the Lightroom import index is no longer capped at 16 MiB, #1312); patch (gap 13: one bad Lightroom record costs only itself; keyword assignments streamed, #1311); minor (gap 19: signed plug-ins find updates in their author's feed, checked when the Plug-in Manager opens and installed by the user); minor (gap 19: plug-in author signatures pin a plug-in's signer, #1271); minor (People: the People view sorts faces into Unknown, Suggested and Confirmed, and reviews the suggested ones a person at a time, #1050); minor (gap 20: Nikon NEFX, NX Studio's merged pixel-shift images, decodes; ARQ pixel shift is what is left of pixel shift); minor (gap 13: Capture One develop settings — exposure, orientation, crop, flips, white balance); minor (gap 13: saved prints in Lightroom catalogs import as Saved Prints with their layout); minor (gap 33 closed: the translation coverage check reads `trf!` and the helpers that translate; gap 21 re-measured: every language has every interface message); minor (gap 19: plug-ins look at a photo's pixels, set its crop and make virtual copies, #891); minor (gap 5: AI mask edges follow the photo's, no outline under a raised Exposure, upstream #3298); minor (gap 11 narrows: AI Super Resolution and AI Sharpen with an opt-in upscaler, upstream #3493); minor (gap 11 narrows: AI Denoise for finished pictures, upstream #3279); patch (gap 36: the ISO country code is carried over in preset save and import, #784); minor (gap 5: AI masks as recipes computed on the AI worker, Update AI Mask, masks under geometry, a Color Mixer per mask); patch (gap 26: smoother edits and lasting previews); minor (gap 5: Object masks can run on SAM 2.1, an open model, ported from OneSlips); minor (gap 12: generative remove through cloud providers with your own key, from OneSlips); minor (gap 36: the IPTC Content fields — headline, description writer, category, supplemental categories, subject codes — are stored, so Lightroom metadata presets carry them); minor (gap 19: plug-ins add a tool's files to the library, stacked or in the source album); minor (gap 19: plug-ins start installed programs; plug-in work no longer on hold); minor (gap 11: AI Denoise works out of the box with a built-in BM3D denoiser, upstream #2982); minor (gap 1: colour-chart calibration); patch (gap 1: calibrations matched to other editors); minor (gap 11 shrinks: the upstream project's own AI Denoise model is a download in the desktop app); patch (gap 3: probe DNGs and slider sweeps); minor (gap 1: dcraw's colour matrices replace the neutral fallback for about 550 models); patch (gap 3: `calibrate-lightroom verify`, edited raws against edited exports); patch (gap 3: ` compare`, ΔE00 between renders from any editor); minor (gaps 1 and 3: Lightroom-matched calibration tool, 0 cameras calibrated yet); minor (upstream merge: gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: grid-cycle key shown in View, #2500; gap 21: Thai glyphs in export text, #2052; gap 15: Japanese photo and postcard paper sizes); patch (HDR zoom: recent windows kept, encoded off the UI thread); patch (HDR adjustment previews: review follow-up); minor (upstream merge: gap 38 added: multi-select metadata editing UI, upstream's gap 30; XMP foreign namespaces and PSD/PSB embedded metadata, no gap change); patch (HDR adjustment previews keep float HDR output during slider drags); minor (opt-in Windows VRR compositor workaround); minor (gap 37 added: folder watching leftovers after issue #123's polling); minor (gap 36 added: what preset import doesn't carry over); minor (M15 decisions: CMYK won't do; Flickr / SmugMug and tethering blocked); minor (gap 11: the Enhance dialog); minor (gap 14 closed: HDR renders on the GPU; X11 SDR is a platform limit); minor (gap 14 narrows: zoomed, Before/After, Compare and second window show HDR, HDR Preview toggle); minor (gap 11 narrows: Raw Details and Super Resolution; gap 18: M14 closed, interlaced H.264 and faster AV1); minor (full audit 2026-10-20: rows refreshed against code; gaps 8 and 2 no longer beta blockers; gaps 34–35 added: Android camera roll and built-in camera; gap 34 narrows: picked folders rescanned); minor (gap 29 narrows: JPEG response curves and half-float frames) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is @@ -27,7 +27,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 8 | **No lens profile database of our own** (LR-EDIT-OPTICS-PROFILE): DNG opcodes, RW2 in-file distortion and Sony ILCE-7RM4A, ILCE-7RM6 and ZV-E10 distortion (`docs/sony-ilce7rm6-lens-corrections.md`), Nikon Z 6II / Z 8 / Z f in-file distortion (`docs/nikon-lens-corrections.md`), plus lensfun's database, fetched once on the desktop app's first run (activity stack) or set up / downloaded from Settings ▸ Lens profiles (CC-BY-SA, not bundled in the binary; a picked lens is written to XMP as `optics.lens`; profiles unverified against Lightroom) | 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 | **Full tests in CI not yet green on macOS, Windows and Linux x64**: pushes to main run fmt / clippy / build on all three OSes (green); full tests run only on `release` or a manual dispatch. The manual full run was green 2026-10-18 (run 39114677868); release 0.9.5 (run 39371069655) failed on macOS, Windows and Linux in four deterministic test groups: lcc-publish full-disk publish, ui-egui i18n catalog coverage (2 tests), empty-library icon layout, engine Immich album publish. Also left: real-disk sidecar-repair fixtures skip on case-insensitive volumes (FakeFs models them); CPU/GPU equivalence runs nightly on software adapters (lavapipe, WARP; `nightly.yml`, wider bounds), and a nightly corpus + fonts run fails when skips exceed `ci/skip-allowlist.toml`, both not yet seen green on CI (#1050); a weekly model-reference job (`models.yml`) runs SAM 2.1, BiRefNet, EoMT and the MediaPipe TFLite models from their pinned, sha256-checked downloads against stored numeric summaries of our own outputs; SAM 3 (SAM License, gated) and YuNet (retired, CC BY-NC-ND training data) are left out (docs/ci.md → Model references) | `.github/workflows/ci.yml`, runs 39114677868 / 39371069655 | regressions reach users on the main platforms until the full suite is green | 2–6 | [target-app-parity](target-app-parity.md#by-dimension) | | 10 B | **Per-model verification still partial**: 645 of 1,446 Adobe models verified (45%, measured 2026-11-24), ~89% of photographers on a verified body (plan target: 60% of models or 95% of photographers — not met); per maker in raw-parity.md. The cheap per-body fixes landed (Z 6II packed NEF #769, ARW version 1 for the A100 and A200…A390, A850, Z 8 and Z 9 lossless verified, pre-X FinePix SuperCCD RAF decoded); S200 EXR upright RAF and SRF decode, Olympus / OM bulk-checked (2026-11-24); left: phones (DNG, few public samples), the older / niche tail per maker, a four-colour path for the F828, and samples for the 90D, 250D, X-H2S, Z 6III, OM-1, OM-5 (none on raw.pixls.us) | measured: [raw/coverage.tsv](raw/coverage.tsv) | per-body bugs (levels, crops, WB) surface only from users | 15–30 | [raw-parity](raw-parity.md#by-maker-measured) | -| 11 | **Enhance: AI denoise without shippable weights or X-Trans; Raw Details and Super Resolution are classical** (Photo ▸ Enhance ▸ Raw Details / Super Resolution landed 2026-10-20: edge-aware residual demosaic and 2× iterative back-projection, each a new linear DNG stacked with the source, in the activity stack; no learned model, Raw Details Bayer only; the Enhance Preview dialog, Photo ▸ Enhance…, landed 2026-10-21) | ENH rows 🟡; denoise: Bayer raws, and finished pictures (JPEG / PNG / TIFF) once a model for them is installed (own model slot; opt-in NIND U-Net, GPL-3.0 weights, upstream #3279); a built-in classical denoiser (block-matching collaborative filtering, GPU-accelerated) works out of the box; the upstream project's own model (MIT OR Apache-2.0, CC0 training data, 0.1.0; [denoise.md](denoise.md#the-upstream-projects-own-model)) is a download in the desktop app, from the upstream release asset, else radfilms.com.au (same SHA-256); RawNIND weights dual-licensed GPL-3.0 and CC BY 4.0, offered under CC BY 4.0, and opt-in (#1760) (Lens Blur renders since 2026-11-25 from the depth model, else from the Subject selection: LR-EDIT-LENSBLUR 🟡, no depth refine brushes) | Fujifilm users get no AI denoise; classical Super Resolution recovers less texture than an AI model, and AI Super Resolution / AI Sharpen (an installed upscaler, upstream #3493) bake the photo's edits into an sRGB TIFF (Lightroom keeps an editable raw) | 20–45 + model decision | [raw-parity](raw-parity.md#demosaic-levels-crops-and-lens-metadata) | +| 11 | **Enhance: AI denoise without shippable weights (X-Trans only through an RGGB re-mosaic, 2026-11-29); Raw Details and Super Resolution are classical** (Photo ▸ Enhance ▸ Raw Details / Super Resolution landed 2026-10-20: edge-aware residual demosaic and 2× iterative back-projection, each a new linear DNG stacked with the source, in the activity stack; no learned model, Raw Details Bayer only; the Enhance Preview dialog, Photo ▸ Enhance…, landed 2026-10-21) | ENH rows 🟡; denoise: Bayer raws, X-Trans through an RGGB re-mosaic (`remosaic_rggb`, upstream #1828; unmeasured with a model trained on Bayer sensors), and finished pictures (JPEG / PNG / TIFF) once a model for them is installed (own model slot; opt-in NIND U-Net, GPL-3.0 weights, upstream #3279); a built-in classical denoiser (block-matching collaborative filtering, GPU-accelerated) works out of the box; the upstream project's own model (MIT OR Apache-2.0, CC0 training data, 0.1.0; [denoise.md](denoise.md#the-upstream-projects-own-model)) is a download in the desktop app, from the upstream release asset, else radfilms.com.au (same SHA-256); RawNIND weights dual-licensed GPL-3.0 and CC BY 4.0, offered under CC BY 4.0, and opt-in (#1760) (Lens Blur renders since 2026-11-25 from the depth model, else from the Subject selection: LR-EDIT-LENSBLUR 🟡, no depth refine brushes) | Fujifilm users get AI denoise only through a re-mosaic the model was not trained on; classical Super Resolution recovers less texture than an AI model, and AI Super Resolution / AI Sharpen (an installed upscaler, upstream #3493) bake the photo's edits into an sRGB TIFF (Lightroom keeps an editable raw) | 20–45 + model decision | [raw-parity](raw-parity.md#demosaic-levels-crops-and-lens-metadata) | | 12 | **Generative remove, detect distractions, reflections removal** (content-aware Remove exists: PatchMatch Fill spots, LR-REM-CONTENTAWARE 🟡) | REM rows 75%; generative remove works through cloud providers with the user's own key (LR-REM-GEN 🟡, ported from OneSlips; no on-device model), remove people stays out of scope (LR-REM-PEOPLE 🚫); open work is detect distractions and reflections | cleanup work goes back to Photoshop | 25–45 (+ generative model) | [target-app-parity](target-app-parity.md#ai) | | 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived; smart collections with unmappable rules (metadata status) stay static; 6 of 113 public flat `crs:` fields have no equivalent (Upright tool options, lens profile setup…) (most smart rules (rule mapping still being finished, 8296786e), stacks, develop history as History, snapshots as Versions, collection / capture / edit date rules incl. today / this week / month / year now import, G13); offline record counts and destination are shown in a lasting import result; before an import the app asks whether the catalog merges into the open library or goes into a new library (opt-out in Settings, #2672); video records classified, records without files skipped, large catalogs read in bounded pages; one oversized or damaged record is left out and counted instead of its table, keyword assignments are streamed past a million (#1311, #1312) — oversized cached-XMP records and packets are read without their camera-profile tables (#1311); imported photos start in step with their sidecars, or as a conflict where a sidecar disagrees (#1312); the recovery archive and the history budget grow with the catalog, the drive and the memory (#1312); the import index grows past 16 MiB so large re-imports add nothing twice; saved prints import as Saved Prints with their layout; Capture One catalogs (`.cocatalogdb`) import through the same path (photos, variants as virtual copies, ratings, colour tags but orange / pink, IPTC fields, keywords, albums in their projects and groups, capture time and camera of offline originals; develop settings: exposure, contrast, brightness, saturation, High Dynamic Range, clarity and structure, levels, the RGB / red / green / blue curves, orientation and straighten, crop, flips and white balance, every other setting named in the result window; not yet the colour editor, layers (as masks), the luma curve or smart albums, C1-IMPORT, C1-DEVELOP) | lightroom-catalog-import.md | switching users lose some looks | 6–10 | [file-format-parity](file-format-parity.md) | | 14 | ~~**HDR display leftovers**~~ — **closed 2026-10-21**: HDR display output (EDR / scRGB surface through a vendored egui-wgpu patch, UI at paper white, HDR edits above SDR white in every view, View ▸ HDR Preview `view.hdrPreview`), and HDR renders run on the GPU (float HDR tone map and output in `finish.wgsl`, CPU as oracle; HDR views, HDR exports and gain maps). X11 has no HDR surface (no colour-management protocol carries headroom or HDR metadata there; a platform limit, not planned): on Linux the app runs native Wayland whenever an output reports HDR headroom, else XWayland / X11 in SDR; slider drags show live HDR drafts too, zoomed in as well (2026-10-22); zoomed panes keep their recent HDR windows (2026-10-24) | HDR rows 85%; LR-HDR-EDIT ✅; LR-VIEW-HDR-DISPLAY 🟡 only for X11 (platform limit); `hdr_renders_match` in `crates/gpu/tests/it/equivalence.rs` | 6 MP HDR render CPU ~200 ms → GPU ~50–70 ms | 0 | [hardware-parity](hardware-parity.md) | diff --git a/docs/manual-site/src/content/docs/ai/denoise.mdx b/docs/manual-site/src/content/docs/ai/denoise.mdx index 2b3848a467..b49b22bc42 100644 --- a/docs/manual-site/src/content/docs/ai/denoise.mdx +++ b/docs/manual-site/src/content/docs/ai/denoise.mdx @@ -13,7 +13,7 @@ import { Aside } from '@astrojs/starlight/components'; - **Where**: Edit ▸ **Detail** ▸ under **AI Denoise**, the **Enable** switch and **Amount** (0 to 100). Turning it on starts at 50. - **Works out of the box**: a built-in denoiser (block matching and collaborative filtering after measuring the photo's noise). No download and no weights. It is a classical filter, not a trained network. -- **Raw only by default**: Bayer raw files. A JPEG, PNG or TIFF is denoised only with a model for finished pictures. X-Trans, Foveon and demosaiced DNG are not supported. The panel says so on photos it cannot handle. +- **Raw only by default**: raw files with a colour filter array. Bayer raws go to the model as they are; X-Trans (and other red/green/blue patterns) are first rebuilt as a Bayer mosaic, an approximation the model was not trained on. A JPEG, PNG or TIFF is denoised only with a model for finished pictures. Foveon, monochrome and demosaiced DNG are not supported. The panel says so on photos it cannot handle. - **Non-destructive**: the cleaned picture is cached data, made in the background and shown in previews and exports. Your file is never changed. Exports make it if it is missing. - **Manual noise reduction** (Luminance, Color) stays separate and works on every photo. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 1f345d21f1..ee661dd9f8 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -293,7 +293,7 @@ under the UI command that wraps it (a no-op error); the UI command now wins. | LR-EDIT-DETAIL-NR | Luminance noise reduction | P0 | ✅ | `ctl:detail.nrLuminance`, `ctl:detail.nrDetail`, `ctl:detail.nrContrast` | radii in the original's pixels, so grid, loupe and smaller exports look like the full-size render scaled down (`local::nr_params`, `Plan::detail_scale`, #960) | | LR-EDIT-DETAIL-CNR | Colour noise reduction | P0 | ✅ | `ctl:detail.nrColor`, `ctl:detail.nrColorDetail`, `ctl:detail.nrColorSmoothness` | preview-size independent like luminance NR (#960). From process V8 the joint method (adapted from upstream #1348, `docs/nr-color-joint.md`): linear R−Y / B−Y, edge-aware weights from a denoised guide, a speck brake; acts clearly at the default 25 and keeps colour edges at 100. CPU and GPU within 1/255 | | LR-EDIT-DETAIL-HOTPIXELS | Hot pixel removal | P1 | ✅ | `check:detail.nrOutliers`, `crates/raw/src/hotpixel.rs`, `crates/engine/src/files.rs` (`load_bytes_now`) | Lightroom has no control for this. A box under Noise Reduction (raws only), on for newly imported raws and off for edits saved before it existed (upstream #1345): isolated photosites far above their same-colour neighbours are replaced in the mosaic before demosaicing; stars and sparks spread over neighbours are kept | -| LR-EDIT-DETAIL-DENOISE | AI denoise | P2 | 🟡 | cmd:denoise.toggle, cmd:denoise.models.install, cmd:denoise.queue, cmd:denoise.models.select, ctl:enhance.denoise, `crates/denoise/`, `docs/denoise.md` | non-destructive Bayer RAW and finished pictures (JPEG/PNG/TIFF with a model for finished pictures, chosen separately: `rgbModel`, `kind: rgb`; the built-in denoiser stays raw-only; opt-in NIND U-Net `nind-rgb`, GPL-3.0 weights, under `rawnind-model`; upstream #3279), opt-in RawNIND weights (dual-licensed GPL-3.0 and CC BY 4.0, upstream #1760; offered under CC BY 4.0 with credit), pure-Rust CPU/GPU; GPU convolution uses independently written shared scalars (Metal equivalence regression, issue #479); tiles can also run on another computer's graphics card (`lcc-cli denoise-serve`, `crates/denoise/src/remote.rs`); X-Trans/linear RGB, model policy and Lightroom fidelity remain; closing the model setup without installing turns the switch back off (#922); with no model installed Settings ▸ AI Denoise says so plainly (this version has none and none can be downloaded from here yet; Luminance and Color under Detail meanwhile; Install from file for a model you have) instead of a file prompt, and the Detail panel note answers Why?; the desktop app offers the upstream project's own model (MIT OR Apache-2.0, `own-model` feature, `known::own_bayer`) from its release asset, else radfilms.com.au; works out of the box with a built-in classical denoiser (BM3D-style block matching and collaborative filtering after a per-plane noise fit, `crates/denoise-core/src/builtin.rs`, GPU kernels in `crates/gpu/src/bm3d.rs` checked against the CPU; id `builtin`, no weights), so turning AI Denoise on needs no set-up; a model of one's own stays optional (upstream #2982); the switch follows Auto Sync (every selected raw in one undo step), Settings ▸ Import ▸ AI Denoise from (ISO) switches it on at import, and a job over many photos is one batch row with the time left and its failures (upstream #2932); from process V6 the Amount eases in (`1 − (1 − a)³`, 50 leaves ~0.17 of the noise σ; not yet compared with Lightroom on a real high-ISO raw) | +| LR-EDIT-DETAIL-DENOISE | AI denoise | P2 | 🟡 | cmd:denoise.toggle, cmd:denoise.models.install, cmd:denoise.queue, cmd:denoise.models.select, ctl:enhance.denoise, `crates/denoise/`, `docs/denoise.md` | non-destructive Bayer RAW, X-Trans and other non-Bayer layouts through an RGGB re-mosaic (`remosaic_rggb`, unmeasured: the model is trained on Bayer sensors), and finished pictures (JPEG/PNG/TIFF with a model for finished pictures, chosen separately: `rgbModel`, `kind: rgb`; the built-in denoiser stays raw-only; opt-in NIND U-Net `nind-rgb`, GPL-3.0 weights, under `rawnind-model`; upstream #3279), opt-in RawNIND weights (dual-licensed GPL-3.0 and CC BY 4.0, upstream #1760; offered under CC BY 4.0 with credit), pure-Rust CPU/GPU; GPU convolution uses independently written shared scalars (Metal equivalence regression, issue #479); tiles can also run on another computer's graphics card (`lcc-cli denoise-serve`, `crates/denoise/src/remote.rs`); X-Trans/linear RGB, model policy and Lightroom fidelity remain; closing the model setup without installing turns the switch back off (#922); with no model installed Settings ▸ AI Denoise says so plainly (this version has none and none can be downloaded from here yet; Luminance and Color under Detail meanwhile; Install from file for a model you have) instead of a file prompt, and the Detail panel note answers Why?; the desktop app offers the upstream project's own model (MIT OR Apache-2.0, `own-model` feature, `known::own_bayer`) from its release asset, else radfilms.com.au; works out of the box with a built-in classical denoiser (BM3D-style block matching and collaborative filtering after a per-plane noise fit, `crates/denoise-core/src/builtin.rs`, GPU kernels in `crates/gpu/src/bm3d.rs` checked against the CPU; id `builtin`, no weights), so turning AI Denoise on needs no set-up; a model of one's own stays optional (upstream #2982); the switch follows Auto Sync (every selected raw in one undo step), Settings ▸ Import ▸ AI Denoise from (ISO) switches it on at import, and a job over many photos is one batch row with the time left and its failures (upstream #2932); from process V6 the Amount eases in (`1 − (1 − a)³`, 50 leaves ~0.17 of the noise σ; not yet compared with Lightroom on a real high-ISO raw) | | LR-EDIT-DETAIL-RAWDETAILS | Improved demosaic toggle | P2 | 🟡 | `cmd:enhance.rawDetails`, `crates/raw/src/demosaic/detail.rs` | Photo ▸ Enhance ▸ Raw Details: a new linear DNG (`-Enhanced-RD.dng`) demosaiced by gradient-weighted Hamilton–Adams green and edge-aware residual red/blue (own design after GBTF 2010 and residual interpolation 2013); +13 dB over bilinear, +1.5 dB over AHD, ¼ of bilinear's false colour on the procedural edge scene; Bayer only (X-Trans keeps the directional method); not a learned model, no fidelity check against Lightroom; no dialog | | LR-EDIT-DETAIL-SUPERRES | Super resolution | P2 | 🟡 | `cmd:enhance.superResolution`, `crates/merge/src/superres.rs` | Photo ▸ Enhance ▸ Super Resolution: Raw Details, then 2× per side by iterative back-projection (Irani & Peleg 1991) with a 3×3 range guard against ringing, into `-Enhanced-SR.dng`; raws and other photos; +3 dB over bicubic on a downsampled procedural scene; ≤ 400 MP out. With an installed upscaler (Real-ESRGAN General v3, BSD-3-Clause, opt-in `realesrgan-model` download, or any `rgbToRgb4x` ONNX; upstream #3493) the dialog also offers AI Super Resolution (`method: ai`, 2× or 4×, pure-Rust CPU/GPU, tiled, cancellable): the photo rendered as an export renders it (edits, crop and masks baked in) to sRGB, Display P3 or Adobe RGB (`space`), into a new 16-bit `-Enhanced-SR.tif` stacked with it, ≤ 110 MP out; the result is not an editable raw (Lightroom keeps a raw a raw) | | LR-EDIT-DETAIL-AISHARPEN | AI sharpen | OOS | 🟡 | `cmd:enhance.aiSharpen`, `crates/engine/src/enhance.rs`, `docs/super-resolution.md` | beyond Lightroom (upstream #3493): Photo ▸ Enhance… ▸ AI Sharpen, the installed upscaler's 4× answer averaged back to the photo's size (finer detail and slight defocus, not motion blur), rendered with the photo's edits into a new 16-bit TIFF stacked with it; needs an upscaler (`realesrgan-model` or one's own `rgbToRgb4x` ONNX) | diff --git a/docs/raw-parity.md b/docs/raw-parity.md index 597d65a9e1..1620fb766b 100644 --- a/docs/raw-parity.md +++ b/docs/raw-parity.md @@ -1,6 +1,6 @@ # RAW parity: cameras, formats, demosaic, colour and lens profiles -> **Last updated:** 2026-11-25 · **Change:** minor (highlight reconstruction: inpaint opposed and guided Laplacian from darktable, `sensor.highlightMode`); minor (CRX partial subbands, multi-tile 0x200 and adaptive low-frequency gains decode, ported from LibRaw `crx.cpp`; synthetic tests only; CR3 0.6 → 0.7); minor (ARW6 12-bit mode decodes when its tile headers match the verified variant; synthetic files only); minor (verification drive, plan 3.8: Sony SRF (DSC-F828 verified, DSC-V3) and the upright FinePix S200 EXR RAF decode; 47 more Olympus / OM bodies verified by a bulk check: 645 verified (45%), 89% of photographers on a verified body; the 60% / 95% verification target is not met); minor (Nikon NEFX, the merged pixel-shift image from NX Studio, decodes: five 16-shot Z 8 files; other shot counts and bodies unverified); minor (CR2 in-camera aspect crop from `AspectInfo`); patch (upstream #3097: CR3 white level at the sensor's saturation point, #2053); minor (upstream #2926: X-Trans demosaic, classified LMMSE green + residual interpolation); minor (Kelvin white balance for Canon ColorData presets and the Nikon Z5II; upstream: integration batch 36 and the camera-coverage sweep #1327, 545 models verified upstream; re-measured after the merge: 596 verified; Canon EOS R6 verified: 315 verified, use-weighted ~90%; Canon CRW decoded, 15 bodies verified; Epson ERF and Mamiya MEF decoded, 4 bodies verified: 314 verified, use-weighted ~90%; compressed ORF decoded: E-M1 and E-M10 Mark III verified; use-weighted 85% → 87%; compressed Samsung SRW 32770 / 32772 / 32773 decoded, 7 bodies checked; Minolta MRW decoded, 6 bodies verified; ARW version 1 and the Z 6II's packed NEF decode, 31 popular bodies verified: use-weighted 87% → 89%, 57% on verified bodies; Z 8 and Z 9 lossless verified: 280 verified, 59% on verified bodies; pre-X FinePix SuperCCD RAF decoded (`raf_superccd.rs`), 15 FinePix bodies verified: 295 verified, Fujifilm 93% → 99%, 60% on verified bodies); upstream: lossy JPEG XL DNG tiles with a non-linear declared transfer curve decode; X-Trans CMOS 4 bodies take the X-T3's spectral matrices · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 (Camera Raw 18.7) +> **Last updated:** 2026-11-29 · **Change:** minor (AI denoise reaches X-Trans through an RGGB re-mosaic, upstream #1828); minor (highlight reconstruction: inpaint opposed and guided Laplacian from darktable, `sensor.highlightMode`); minor (CRX partial subbands, multi-tile 0x200 and adaptive low-frequency gains decode, ported from LibRaw `crx.cpp`; synthetic tests only; CR3 0.6 → 0.7); minor (ARW6 12-bit mode decodes when its tile headers match the verified variant; synthetic files only); minor (verification drive, plan 3.8: Sony SRF (DSC-F828 verified, DSC-V3) and the upright FinePix S200 EXR RAF decode; 47 more Olympus / OM bodies verified by a bulk check: 645 verified (45%), 89% of photographers on a verified body; the 60% / 95% verification target is not met); minor (Nikon NEFX, the merged pixel-shift image from NX Studio, decodes: five 16-shot Z 8 files; other shot counts and bodies unverified); minor (CR2 in-camera aspect crop from `AspectInfo`); patch (upstream #3097: CR3 white level at the sensor's saturation point, #2053); minor (upstream #2926: X-Trans demosaic, classified LMMSE green + residual interpolation); minor (Kelvin white balance for Canon ColorData presets and the Nikon Z5II; upstream: integration batch 36 and the camera-coverage sweep #1327, 545 models verified upstream; re-measured after the merge: 596 verified; Canon EOS R6 verified: 315 verified, use-weighted ~90%; Canon CRW decoded, 15 bodies verified; Epson ERF and Mamiya MEF decoded, 4 bodies verified: 314 verified, use-weighted ~90%; compressed ORF decoded: E-M1 and E-M10 Mark III verified; use-weighted 85% → 87%; compressed Samsung SRW 32770 / 32772 / 32773 decoded, 7 bodies checked; Minolta MRW decoded, 6 bodies verified; ARW version 1 and the Z 6II's packed NEF decode, 31 popular bodies verified: use-weighted 87% → 89%, 57% on verified bodies; Z 8 and Z 9 lossless verified: 280 verified, 59% on verified bodies; pre-X FinePix SuperCCD RAF decoded (`raf_superccd.rs`), 15 FinePix bodies verified: 295 verified, Fujifilm 93% → 99%, 60% on verified bodies); upstream: lossy JPEG XL DNG tiles with a non-linear declared transfer curve decode; X-Trans CMOS 4 bodies take the X-T3's spectral matrices · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 (Camera Raw 18.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 @@ -216,7 +216,7 @@ sample files. A pointer for contributors, not legal advice. | Crop masks and aspect | ✅ | DefaultCrop, Sony recorded size, Canon AspectInfo, Panasonic in-camera crops, Nikon CropArea, measured Nikon bodies without it (D4, D90, D5000, D600, D610) | 🟡 7RM3 / 7RM4 crop origin 8–32 px off (cosmetic) | | Lens metadata | ✅ read for profile selection | EXIF lens fields read; used only for the in-file corrections below | 🟡 | | Highlight reconstruction | ✅ | neutral clip, chromaticity diffusion (`highlight.rs`); inpaint opposed and guided Laplacian from darktable (`highlight/opposed.rs`, `highlight/laplacian.rs`, `sensor.highlightMode`) | 🟡 tuned by eye | -| AI denoise | ✅ Bayer and X-Trans, model bundled | Bayer only, user-installed weights, pure-Rust CPU / GPU | 🟡 no X-Trans, no shippable weights | +| AI denoise | ✅ Bayer and X-Trans, model bundled | Bayer natively; X-Trans and other non-Bayer layouts through an RGGB re-mosaic; user-installed weights, pure-Rust CPU / GPU | 🟡 no shippable weights; the model is trained on Bayer sensors and unmeasured on a re-mosaiced one | | Super Resolution | ✅ | — | ⬜ | | HDR / panorama merge to raw DNG | ✅ | linear DNG (float16 HDR) with the source's colour tags | ✅ | | Convert to DNG | ✅ | uncompressed or LJ92 tiles (`dngwrite.rs`) | ✅ (no lossy DNG) | diff --git a/docs/whats-new/2026-11-29-xtrans-ai-denoise.md b/docs/whats-new/2026-11-29-xtrans-ai-denoise.md new file mode 100644 index 0000000000..c579d58408 --- /dev/null +++ b/docs/whats-new/2026-11-29-xtrans-ai-denoise.md @@ -0,0 +1,2 @@ +### AI denoise for Fujifilm X-Trans raws +- AI denoise no longer refuses X-Trans raws: the mosaic is rebuilt as a Bayer mosaic of the same size and handed to the installed Bayer model. The model was not trained on X-Trans, so results are an approximation. From 707e2a2856244043c74edc1a8779faf363f170b3 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:17:09 +1100 Subject: [PATCH 030/112] Intake merge: close the test the export and engine merges shared Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests_export.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/tests_export.rs b/crates/engine/src/tests_export.rs index 779587002c..b3ecb3d18f 100644 --- a/crates/engine/src/tests_export.rs +++ b/crates/engine/src/tests_export.rs @@ -2163,6 +2163,7 @@ fn original_psd_export_refuses_embedded_metadata_excluded_by_policy() { assert!(export_photo(&mut s, plain_id, &opts(policy, true), 1).is_ok(), "{policy}"); } let _ = std::fs::remove_dir_all(&dir); +} #[test] fn preset_export_rejects_malformed_ids_without_replacing_the_output() { From a0b9a0be3cf28dfc2841128fa44028feaff6292e Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 14:18:56 +1100 Subject: [PATCH 031/112] Upstream intake 2026-11-29: ledger rows and run log Co-Authored-By: Claude Opus 5.5 --- docs/upstream-pr-reviews/ledger.md | 44 ++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/docs/upstream-pr-reviews/ledger.md b/docs/upstream-pr-reviews/ledger.md index 56f68d810a..145c9813ec 100644 --- a/docs/upstream-pr-reviews/ledger.md +++ b/docs/upstream-pr-reviews/ledger.md @@ -45,6 +45,8 @@ PR head or commit SHA. A pipe inside a cell is escaped with a backslash. | #1048 | open | chore: add bug, feature, and performance issue forms | SKIP | - | Upstream's GitHub issue forms (their product name and triage flow); Chromaforge has no ISSUE_TEMPLATE and uses CONTRIBUTING.md. | ``f9549e9093`` | 2026-11-08 @ de096566ff | - | | #1063 | open | LR-PROF-IMPORT: import the user's own DNG camera profiles (.dcp) | SKIP | - | Chromaforge already imports a person's own .dcp (fork 344a04f7a, camera.listDcp, crates/raw/src/dcp.rs, camprof dcp writer); 45 files overlap fork-owned engine/UI; its D750 CC0 Lightroom comparison corpus is not needed | ``408636ab5fd5`` | 2026-11-05 @ 0b5e6c7a06 | - | | #1065 | merged | GPU-FULL: more of the render on the GPU, loupe drafts from GPU textures | SKIP | - | Already in Chromaforge: its author (OneSlips) ported the whole GPU-FULL series into the fork as the OS-gpu-perf / OS-gpu-window commits (v26.45.2) and closed the upstream PR saying so (2026-11-05 01:02); the maintainer merged it 3 h later unchanged. | ``9bfc34733b`` | 2026-11-06 @ 8a0b91a95c | - | +| #1069 | open | Normalize DNG black levels per plane with finite-range guards | PENDING | fork numbers; #1068 | Changes pixels on DNGs with non-uniform blacks (per-plane max instead of mean); needs a corpus measurement and a render-cache bump; sil has no such DNG. Upstream says #1068 first. | `e211776001` | 2026-11-29 @ 2d62488dd2 | - | +| #1079 | open | Reject stale mask results and disclose approximate selections | PENDING | split port | 684 lines over ~23 files mixing Rust 1.95 clippy fixes with stale-segment rejection and a new Masking notice string; port by concern. | `9922a180f5` | 2026-11-29 @ 2d62488dd2 | - | | #1095 | open | Import: what the photos themselves carry can be left in the files | PENDING | upstream approval | Useful per-kind import read choice (keywords, ratings, titles, location, develop settings), but CONFLICTING, 1.2k lines across fork-owned catalog/ui-egui/import, unresolved AlexChambers (sync read choices must stay fixed per import) and CodeRabbit findings, no maintainer review; revisit as an own-design port once settled. | ``7227ccb9bf`` | 2026-11-08 @ de096566ff | - | | #1115 | open | LR-EDIT-OPTICS-PROFILE: Sony ILCE-7RM6 lateral CA corrected on the raw mosaic before demosaic | PENDING | undrafted / ready | Sony ILCE-7RM6 lateral CA corrected on the raw mosaic before demosaic (red/blue sites resampled from same-colour taps; applied only to lenses measured to improve, CA_IMPROVES); approved by FredApps and CI green, but still a draft, and it changes every ARW render (cache bump) and the fork's own decision (8c64c467f) kept the Sony CA planes off by default. | ``4420b0b5330e`` | 2026-11-08 @ de096566ff | - | | #1117 | open | Auto Import: option to include subfolders of the watched folder (#1109) | ADOPT | - | Taken in the fork's own form: Settings ▸ Import ▸ Auto Import gains Include subfolders (off by default), listed through the bounded folder walk (16 levels, 200,000 entries, hidden entries and the library folder skipped, folder links entered once so loops end, unreadable subfolders skipped; subfolders list supported photo types only, the top level lists every file as before). The fork's own `auto_options` setting and the walk replace upstream's `listingWarnings` and `prefs.json` key; the same change adds file naming, develop preset, metadata preset and keywords for arriving photos. | `edef73d86a` | 2026-11-11 @ a974417dc | (this PR) | @@ -56,12 +58,14 @@ PR head or commit SHA. A pipe inside a cell is escaped with a backslash. | #1159 | open | test(gpu): preserve active markers across nested panics | ADOPT | - | Adds the missing nested-panic regression test for the GPU init marker (inner scope panics while an outer scope is active); no product code. Adapted to the fork's slot-based with_marker_in; passes. | ``7c70fb74da`` | 2026-11-08 @ de096566ff | `985c64662` | | #1162 | closed | M11: decode lossless Olympus and OM System ORF | SKIP | - | Closed 2026-11-08: its author split it into #3944, #3939 and #3964 (see their rows); #3939 is ported, the decoder part is still the competing Olympus decoder. | `d0b966a0fe` | 2026-11-09 @ 7e2b8a6b27 | - | | #1181 | open | LR-BEHAV-RENDER-FIDELITY: tools/render_fidelity.py measures single-slider responses against your own Lightroom exports | PENDING | upstream approval + a maintainer wanting a second Lightroom-comparison tool | Stand-alone 4k-line Python tool and docs (no product change): pairs a person's own Lightroom exports with raws and scores slider responses. Overlaps the fork's `calibrate-lightroom` fit/add flow, drives upstream's CLI name, and has no maintainer review; not read line by line, so not taken. 2026-11-17: head moved (main merges / follow-ups), decision unchanged. | `a3d1698b34` | 2026-11-17 @ aa08a77060 | - | +| #1204 | open | LR-IMP-DRAGDROP: photos opened from Finder or other apps reach LightCraft on macOS (#506) | ADOPT | - | Fork had no CFBundleDocumentTypes and no openURLs handler. Hand-ported as the new unsafe helper crate crates/opendocs (named in AGENTS.md), reusing objc2 already in Cargo.lock; files go through the fork's drop path. Clippy cross-checked for aarch64-apple-darwin; not run on a Mac. Upstream's library-problem commits not needed (fork's hold_dropped). | `48d4a4332f` | 2026-11-29 @ 2d62488dd2 | `589ae0254` | | #1206 | open | LR-PROF-CAMERACOLOR: dark, muted scenes learn their matrix | PENDING | #784 lands | Merges only; stacked on unapproved #784 2026-11-25: head moved (re-read by the monitor; main merges or follow-ups), decision unchanged. | `1f6cc72b91` | 2026-11-25 @ ddc0eef377 | - | | #1208 | open | LR-META-EXIF-FULL: HEIC/HEIF/AVIF EXIF and XMP | ADOPT | - | Merges only; own commits unchanged; fork port complete | `ea5416d2e92a09f98e5231da5411e426affc72d2` | 2026-11-15 @ 80de5f8fae | `456ec0cca` | | #1221 | open | HDR display: show HDR edits in HDR on HDR displays (Linux; macOS EDR next) | PENDING | CI green and egui pin in storytold/egui | Red CI (Git dependencies job): pins every egui crate to a personal fork (JordyUSA/egui) for prefer_hdr, a supply-chain item FredApps would not approve; Chromaforge already ships HDR (crates/hdrmeta, all 3 OSes); only the loupe HDR rendition idea might be worth comparing later. Re-read 2026-11-11: head moved by a merge of main only; CHANGES_REQUESTED and the egui pin question stand. 2026-11-25: head moved (re-read by the monitor; main merges or follow-ups), decision unchanged. | `342cbc0bf1` | 2026-11-25 @ ddc0eef377 | - | | #1209 | open | Show Fujifilm film-simulation settings from the MakerNote | PENDING | own-design port with a catalog format bump | Useful (Info panel and CLI/MCP show film simulation, DR, Copy recipe; crates/meta/fuji.rs is portable), but storing the recipe needs a catalog format bump and changes in crates/catalog and ui-egui, which the fork owns (upstream format 13 vs the fork's 16); open AlexChambers cache-key finding. The parser alone has no consumer. | ``35ad3a1f9f`` | 2026-11-08 @ de096566ff | - | | #1243 | open | LRC-LIB-LIBFOLDERS: Folders skips the folders that only lead to your photos, with Show Parent Folder to list them | SKIP | - | Fork already draws Folders without the lead-only chain (sidebar_folders in ui-egui left.rs: a folder with no photo, no label and one child gives its row to the child) and has Show Parent Folder (switches the source to the parent); only the persisted Hide This Parent list is missing, a UI nicety on fork-owned paths. | ``59944f6e9beb`` | 2026-11-05 @ 0b5e6c7a06 | - | | #1244 | open | Sidebar: the row of what is shown has a bar, and a folded section says what it holds | SKIP | - | Only crates/ui-egui panels and locale catalogs: fork-owned UI (the Modern layout sidebar was rewritten); no shared logic | ``77b0863f1f`` | 2026-11-05 @ 0b5e6c7a06 | - | +| #1261 | open | Make a positive paint vignette blend toward white. | ADOPT | - | Fork's positive Paint overlay equalled the Color lift. Hand-ported in pipeline finish.rs: blends toward white (0.18 grey at amount 100 in the corner: 0.877 -> 1.0 linear); other styles and signs unchanged; sil 9 passed. #980 not touched. | `41ebe6dd08` | 2026-11-29 @ 2d62488dd2 | `027178033` | | #1348 | merged | Colour noise reduction: joint linear chroma filter with speck brake, CPU and GPU (#815) | ADOPT | - | merged 3943279105; joint chroma NR; fix NRV2_GPU_BAND_MB prefix, use lcc-gpumem not nvidia-smi, measure first. Ported in the next PR, Process V8 (#1348, #3783 and #3509 change existing renders together under one process version) | ``f2d051cbee`` | 2026-11-06 @ 8a0b91a95c | `0a99b96be` | | #1374 | open | LR-PREF-INTERFACE: text sizes have names, the seven type roles of the theme | SKIP | - | Only crates/ui-egui (Settings dialogs, panels, theme); upstream-owned paths the fork rewrote. | ``b341826e11`` | 2026-11-04 @ 03e03f382e | - | | #1384 | closed | LR-EDIT-OPTICS-PROFILE: enable Sony ILCE-7M3 (A7 III) embedded distortion correction | SKIP | - | Closed as superseded by #3144; already in the fork as c98908977 (ILCE-7M3 in DISTORTION_MODELS). | ``ede4eb70dd8f`` | 2026-11-05 @ 0b5e6c7a06 | - | @@ -79,14 +83,19 @@ PR head or commit SHA. A pipe inside a cell is escaped with a backslash. | #1626 | open | LR-BEHAV-SIDEBAR-COLLAPSE: the sidebar's trees open as they were left | SKIP | - | Only crates/ui-egui sidebar/state; the fork has its own sidebar. Idea (persist tree open state) noted, no trapped shared fix. | ``3d28e091ef`` | 2026-11-04 @ 03e03f382e | - | | #1631 | open | LR-BEHAV-SIDEBAR-SECTIONS: Option-click on a triangle opens or folds the whole branch (stacked on #1626) | SKIP | - | Only `crates/ui-egui` left panel (upstream-owned paths), stacked on unmerged #1626, +1863 lines; Chromaforge's panel is its own design | ``0d0456315d`` | 2026-11-04 @ 03e03f382e | - | | #1635 | open | LR-IMP-DEVICE: import from PTP cameras on Windows and macOS (#1005, includes #1169) | WATCH | upstream approval | One new commit fixing a CodeRabbit finding (a staged camera file always leaves the temp folder on Copy/Move, `camera_import::is_staged`, job.rs guard, test `a_staged_camera_file_leaves_the_temp_folder`); nothing changes the ledger's blockers (3.4k lines, ~95 unsafe in new crates/cameras, includes open #1169, no approval). Re-read 2026-11-08: head moved (refresh); decision unchanged. Re-read 2026-11-11: unchanged. | `1288a2923f6b30cf93328d827fbf09bf6e3e162d` | 2026-11-11 @ c2e9c456c9 | - | +| #1638 | open | Avoid rescanning overlapping photo and preset import roots | ADOPT | - | Adapted onto the fork's walk.rs: opt-in walk::files_in_with_seen with a shared canonical-folder set, used by import expansion and preset.import. Portable nested-root tests instead of upstream's Unix symlink CLI tests. | `29d7283572` | 2026-11-29 @ 2d62488dd2 | `d30dfd4f3` | | #1639 | open | Preserve Survey groups and make photo removal reliably clickable | ADOPT | - | Filmstrip half ported (plain Survey filmstrip clicks add or activate, keeping the group; headless test). The remove-button half was already in the fork (contains_pointer, surveyRemove widget) | ``1c0d090260`` | 2026-11-04 @ 03e03f382e | `c0c67b307` | | #1649 | open | LR-BEHAV-BG-TASKS: an export or import that ended stays in the list under the bell (stacked on #1642 and #3151) | SKIP | - | stack on fork-owned bell/locales; the fork's activity stack already keeps finished-batch summaries (`Activity::finished`) and has its own panel | ``8c2311c6c9`` | 2026-11-04 @ 03e03f382e | - | | #1674 | open | [agent] Top bar and sidebar buttons show hover feedback and the pointing hand | ADOPT | - | icon_button shows the pointing hand and the full hover fill (hand port, fork commit 32cde9305) | ``b4feea9d43`` | 2026-11-04 @ 03e03f382e | ``32cde9305`` | | #1700 | open | LR-VIEW-HDR-DISPLAY: HDR edits show in HDR on HDR displays | SKIP | - | Already in Chromaforge (hdrmeta crate, apps/app/src/hdr_display.rs, Wayland metadata; fork commit 5ceee3327 fixed follow-ups; HDR confirmed on all 3 OSes); upstream PR is conflicting and unchanged in intent. | ``de0bd390c5`` | 2026-11-05 @ 0b5e6c7a06 | - | +| #1704 | open | Export: Original and DNG follow the metadata setting (#1505) | ADOPT | - | Privacy: the Original sidecar and DNG packet carried title/creator/location under narrower policies. Hand-ported (MetadataPolicy::restrict, CopyrightContact kept); an Original embedding excluded metadata is refused via lcc_meta::try_extract. Upstream tests ported. | `711a90e6fc` | 2026-11-29 @ 2d62488dd2 | `fd1730607` | | #1711 | open | LR-BEHAV-BG-TASKS: a background task says how it ended; the engine's own jobs do (part 1 of 3) | PENDING | upstream approval | Unchanged head; conflicting, unapproved, part 1 of 3 and must be read against the fork's activity stack (TaskGuard rule, shared AI backend row) | ``1233e35b2035`` | 2026-11-08 @ de096566ff | - | | #1735 | open | LRC-LIB-CATALOG-IMPORT: catalogs import in batches | LEARN | - | Merges only; approval stands; hand-port plan unchanged | `346d500136d54aa1519ea4aefca1a5d2749de752` | 2026-11-15 @ 80de5f8fae | - | +| #1736 | open | fix(control): bound synthetic UI events and protect input queue | ADOPT | - | Fork already bounds count/steps per request (bounded_arg); ported only a cap on the whole pending queue (4096; a lone release may pass) with a hostile-input test. | `3700d257c8` | 2026-11-29 @ 2d62488dd2 | `d423abe82` | | #1775 | open | LR-IMP-MOVE: Sync the copy's folder before removing the original (#1501) | SKIP | - | Already in Chromaforge: ccbe8b6e3 ported it (sync_dir, create_dir_durable in import_move.rs; sync before removal in rename.rs move_across_volumes). Upstream head still has unresolved blockers (per-photo sync cost, failing gate). | ``1ff734e9cc`` | 2026-11-05 @ 0b5e6c7a06 | - | | #1812 | open | LR-EDIT-DETAIL-DENOISE: RawNIND weights under CC BY 4.0, offered by default (#1760) | ADOPT | - | RawNIND weights dual-licensed CC BY 4.0; ported the licence metadata, provenance and tests. The `rawnind-model` default flip was withheld — upstream calls it a maintainer decision and so does the fork | `46f4596465` | 2026-11-16 @ a4676b1249 | d4f2f0d10 | +| #1828 | open | Denoise X-Trans raws through an RGGB re-mosaic | ADOPT | - | Fork's AI denoise refused X-Trans. Cherry-picked with conflicts resolved: re-mosaic tests compare with Method::Ppg, fork's repair_pixels kept. Bayer renders unchanged; RGGB round-trip PSNR 56-57 dB smooth / 33 dB edgy. Gap 11 narrowed. | `19c4c6d76b` | 2026-11-29 @ 2d62488dd2 | `e3b59f20c` | +| #1837 | open | macOS: open photos from Finder, the Dock and Open With | SKIP | - | Superseded by #1204's port: it needs the external fmv-macos-events crate for its unsafe code, which AGENTS.md doesn't allow; its quit-event handling is not ported. | `719bf0c952` | 2026-11-29 @ 2d62488dd2 | - | | #1907 | closed | LR-META-XMP: Write automatic XMP sidecars off the UI thread in the desktop app | LEARN | - | already in ledger (archive LEARN): background sidecar writer keeps saves off the UI thread; fork still writes inline (no `sidecar_writer`). Now closed unmerged upstream | ``78efb8f791`` | 2026-11-02 | - | | #1938 | closed | Files on an SMB share: imports, moves and sidecar backups use the fsync fallback too | SKIP | - | already in ledger (archive SKIP): duplicate, fork has it (fork #375, `crates/sysmem` fsync fallback). Closed as draft | ``4529335dd9`` | 2026-11-02 | - | | #1995 | open | Import: preserve embedded rating, flag and label from file metadata | SKIP | - | The Rating 65535 read fix (rejected, not five stars) is ported from craft-libs #967 (9b501b761); writing Rating stays out. Earlier: already in Chromaforge: e4daa22ff carries the first version (rating, flag, label from embedded metadata on import). The PR head (now APPROVED) was reworked to drop embedded develop settings of rendered files and merge partial sidecars, which contradicts adopted #3607 (embedded develop in a JPEG applies). | `52d9ca0ea4` | 2026-11-16 @ a4676b1249 | - | @@ -158,7 +167,7 @@ PR head or commit SHA. A pipe inside a cell is escaped with a backslash. | #2653 | open | Detail view: zoom to 1600 % (#2652) | SKIP | - | UI-only (state::MAX_ZOOM, detail panel, bottom bar): ui-egui is fork-owned (Modern layout); the fork picks its own zoom limits. | `22ecbd25a3` | 2026-11-16 @ a4676b1249 | - | | #2659 | open | LR-META-LOCATION: place names always download into the settings folder (#2575) | SKIP | - | already ported | ``9a2aa7c471`` | 2026-11-04 @ 03e03f382e | ec5296285 | | #2661 | merged | LR-EDIT-LENSBLUR: camera-like Lens Blur with AI subject focus and per-mask bokeh | LEARN | - | Read in full at the squash `1a301fc2d` and ported whole in fork PR #1500, which was closed unmerged: the fork's own depth-based Lens Blur (PR #1498: depth model or Subject fallback, focus picker, bokeh shapes) had landed first under the same `DevelopSettings.lens_blur`, `lensBlur.*` controls and `lens_blur.rs`, and its depth map replaces upstream's two-depth focus (subject / focus mask / fixed shapes, Transition, Find Subject). Taken in the fork's form, onto the depth renderer: Boost (highlight gain before the spread), Focus / Blur brush refinement (strokes overrule the depth) and the per-mask Lens Blur block (Selection / Outside, Blur Amount, Boost; without upstream's per-mask Transition). No catalog format bump | `eb23b178c6` | 2026-11-25 @ ea033fbe1c | `0e45c1889` | -| #2675 | open | LR-PROF-CAMERACOLOR: align lens-corrected camera JPEG training pairs | WATCH | upstream approval | Author merged main several times and then narrowed the PR (bd3ee7ea8d "narrow standalone color geometry scope"): the activity-totals UI commit fbb318a83a was reverted out, diff vs main is now 18 files in engine (camera_preview colour/proxy, camera_profiles, cmd/previews +344, lens_profiles +210, smart.rs lens_db header field + marker), merge/src/frame.rs (lens opcodes stripped after the colour callback) and a pipeline tests_light constant fix. Still bumps LOOK 13->14 and render cache 76->77, still unapproved, no before/after numbers. Re-read 2026-11-08: head unchanged, no approval or merge since; Recheck stands. 2026-11-17: new head adds DNG colour fits in stored sample space (8d45e43cf3); still needs fork numbers. 2026-11-25: head moved (re-read by the monitor; main merges or follow-ups), decision unchanged. | `344ac41e09` | 2026-11-25 @ ddc0eef377 | - | +| #2675 | merged | LR-PROF-CAMERACOLOR: align lens-corrected camera JPEG training pairs | PENDING | fork numbers | Merged 2026-11-27 (`c5eff6b2d6`); still a render change bumping LOOK/RENDER_CACHE (upstream 27/88, fork 29/94) with no before/after numbers. | `25a43773dc` | 2026-11-29 @ 2d62488dd2 | - | | #2676 | open | LR-EDIT-OPTICS-PROFILE: preserve unknown crop factors in lens profiles | ADOPT | - | Option crop factors were already carried (fork #536); ported the remaining tie-break: an exact score tie prefers the profile with a known calibration crop, with a test. | ``be6a90064f`` | 2026-11-08 @ b3b49987d4 | 0c9e63f91 | | #2707 | closed | LR-BEHAV-MULTISELECT: the model for choosing several sidebar rows with Cmd/Ctrl+click and Shift+click | SKIP | - | Closed with an empty diff, restacked as #3106, #3107, #3108 and #2757; model lives in `ui-egui`, which the fork rewrote (Classic sidebar) | ``ebe2477108`` | 2026-11-04 @ 03e03f382e | - | | #2733 | merged | LR-EDIT-OPTICS-PROFILE: Sigma 10-18 mm exception on the ILCE-6700 | SKIP | - | Already in the fork: ported with fork PR #529 (commit 3ef7db7ae, 'upstream PRs 2835, 2664, 2777, 2733'); LENS_EXCEPTIONS and Sigma 10-18 present in crates/raw/src/vendor/arw_lens_rm6.rs on origin/main. Upstream landed it via merge b4757824b (commits c1a1896d3, d1b272e49 docs). | ``b4757824b`` | 2026-11-05 @ 0b5e6c7a06 | - | @@ -443,7 +452,7 @@ PR head or commit SHA. A pipe inside a cell is escaped with a backslash. | #3400 | merged | Never crash: a Samsung encryption key past i64::MAX doesn't overflow keyed() | ADOPT | - | Already in the fork (`wrapping_mul(sign)` in `crates/raw/src/vendor/srw.rs`, with its typed-entry test); the ledger row was stale | ``7597810299`` | 2026-11-04 @ 03e03f382e | 6f4a69b9b | | #3402 | merged | RAW.colour: fit the per-file look on the vignetting-corrected sensor | ADOPT | - | Fit the per-file look on the vignetting-corrected sensor. LOOK_VERSION 20->21, RENDER_CACHE_VERSION 76->77; unmeasured on the fork (upstream X-S10 dE00 2.71->2.55). | ``cabc9a3d21b8`` | 2026-11-05 @ 0b5e6c7a06 | 5bc88f079 | | #3403 | merged | LRC-LIB-CATALOG-SWITCH: files waiting for a library wait for a running import instead of being dropped (#2779) | ADOPT | - | Ported by hand: LccApp.waiting_import keeps the files while an import or Synchronize Folder runs and retries each frame; one test. Not ported: the toast, the quit prompt and library-switch guards. | ``a2d3698333`` | 2026-11-04 @ 03e03f382e | `352a140b7` | -| #3407 | open | fix: Fade deep shadows to grey when Blacks lifts the toe | WATCH | upstream merge (and #3266 V3 numbering) | Unchanged head; approved but a new process version (fork V3-V7 taken, would be V8 in sidecars) and a reviewer found no change on 34 public Sony raws; wait for upstream numbering Re-read 2026-11-11: unchanged. | `d19658e60d5c54161862d6c2de5b7d1cc49dd66a` | 2026-11-11 @ c2e9c456c9 | - | +| #3407 | open | fix: Fade deep shadows to grey when Blacks lifts the toe | WATCH | upstream merge (and process-version numbering) | One comment-only commit (7492729c5e); review now CHANGES_REQUESTED; still a new process version without fork numbers. | `7492729c5e` | 2026-11-29 @ 2d62488dd2 | - | | #3408 | merged | Control: pointer and scroll gestures refuse numbers past any screen instead of queueing NaN positions | SKIP | - | Control gestures refusing huge numbers already ported. | ``8d256db7a0`` | 2026-11-04 @ 03e03f382e | 9a9aac96f | | #3409 | merged | Issue #3405: Auto Import waits for an import that starts during its listing | SKIP | - | merged upstream but upstream-only (CI/packaging/docs/i18n) or fork-owned paths only | `2910705fa2` | 2026-11-02 @ 5a09d07530 | - | | #3410 | merged | Issue #3406: Auto Import says when it can't read the watched folder | SKIP | - | merged upstream but upstream-only (CI/packaging/docs/i18n) or fork-owned paths only | `b9ba9d4640` | 2026-11-02 @ 5a09d07530 | - | @@ -943,7 +952,7 @@ PR head or commit SHA. A pipe inside a cell is escaped with a backslash. | #2645 | open | Zoom past 100% shows pixels, not a blur (#2643) | WATCH | upstream approval | Useful; owned ui-egui, a hand-port once vetted | `526fde2fa0b71326c2072af8d48a89b09883a4ae` | 2026-11-15 @ 80de5f8fae | - | | #2777 | merged | Fujifilm X-S20 lens corrections and matrices | SKIP | - | Already ported (3ef7db7ae) | `8ffe73cc3cef8019aa3571c639b17f98c09c1e87` | 2026-11-15 @ 80de5f8fae | - | | #2896 | merged | Preset Amount blends curves and profiles (#2669) | ADOPT | - | Core already in the fork (76c7abcdc: a new choice's strength fades in from 0, white balance on another scale taken whole; curve blending, the HDR blend base and the shared preview path came earlier). 2026-11-27: merged upstream (`95ada217da`); the remaining delta adopted: importing with a preset and the import default preset go through the same apply as `preset.apply` and the previews (a one-field white balance preset is prepared on the photo's scale, issue #2910), and Amount 0 without an import state returns before that preparation, so As Shot stays. Not taken: monotone-cubic evaluation in the curve blend (the fork blends piecewise-linear at the union of points; it changes the curves written at partial amounts, and there are no numbers). | `b2e8d74977` | 2026-11-27 @ 5973d956df | `d21affb32` | -| #4215 | open | Choose a raw's lens profile by hand (#1049) | WATCH | upstream approval | Large, unreviewed; real parity gain once vetted | `786330533ecf3d58cd7b1eba9de329298351e2cb` | 2026-11-15 @ 80de5f8fae | - | +| #4215 | open | Choose a raw's lens profile by hand (#1049) | LEARN | - | The fork has its own lens.choose / lens.db.photo (issue #307); porting would duplicate it. Borrow: the Lens field/column naming the chosen profile. | `202209aebf` | 2026-11-29 @ 2d62488dd2 | - | | #4216 | open | First edit lists an Import History step (#4203) | ADOPT | - | Ported early: the first edit lists an Import History step (Lightroom behaviour); history-group/headless tests adjusted | `e096283b47` | 2026-11-17 @ aa08a77060 | `04ddf14b7` | | #4222 | closed | codecs: shared GIF decoder | SKIP | - | craft-libs move (landed via #4231); nothing separable | `1666a8dd244863284cec63b92d1067593dcc3847` | 2026-11-15 @ 80de5f8fae | - | | #4223 | open | Validate album rule ids exactly | LEARN | - | Same f64 rounding in fork album_rule_id, only above 2^53; a 120-line exact parser not worth it now | `adb5da20e8619bceda669237692411b17f9a3de3` | 2026-11-15 @ 80de5f8fae | - | @@ -1025,14 +1034,14 @@ PR head or commit SHA. A pipe inside a cell is escaped with a backslash. | #2381 | open | #2284: date files and the session clock in the host's time zone | LEARN | numbers | New time-zone dependency and an import-dating default change with no numbers | `bf20027304` | 2026-11-16 @ a4676b1249 | - | | #4283 | open | feat(library): stack RAW + JPG pairs automatically | PENDING | upstream picks #4046 or #4283 | Was unready (WIP); touches catalog/local.rs, fork-owned UI and the frozen whats-new.md 2026-11-25: marked ready for review, head unchanged; decision unchanged (no review, fork-owned paths). | `f13d25f618` | 2026-11-25 @ ddc0eef377 | - | | #4284 | open | cli: collect every calibration raw format (#4061) | ADOPT | - | Ported early: shared CALIBRATION_EXTENSIONS (adds rwl, crw, mrw; no dng); calibrate_lightroom keeps its own list | `bdc4faa835` | 2026-11-17 @ aa08a77060 | `ba869ddac` | -| #4285 | open | develop: keep a preset's white balance on one scale across amounts (#3917) | PENDING | threads resolved, numbers | Two real unresolved CodeRabbit threads; render change at amounts below 100 % with no numbers 2026-11-17: head moved (main merges / follow-ups), decision unchanged. | `9635119092` | 2026-11-17 @ aa08a77060 | - | +| #4285 | closed | develop: keep a preset's white balance on one scale across amounts (#3917) | SKIP | - | Closed by its author as covered by main's preset interpolation; the fork's scale_patch already takes white balance on another scale whole (#2896, 76c7abcdc). | `9635119092` | 2026-11-29 @ 2d62488dd2 | - | | #4286 | open | engine: faces.add and faces.remove commands (#4118) | PENDING | threads resolved | Unresolved: near-zero rect makes an empty region; remove on an unsearched photo lets the next search re-add it without undo 2026-11-17: head moved; check whether the near-zero rect and re-add threads are fixed (S/M candidate). | `d3c2c1e6fa` | 2026-11-17 @ aa08a77060 | - | | #4287 | open | tests: wait for the drive's reads before counting them (#3823) | SKIP | - | Test-only fix to a test Chromaforge does not have | `98b9c196e9` | 2026-11-16 @ a4676b1249 | - | | #4293 | open | LRC-LIB-CATALOG-IMPORT: captions come from AgLibraryIPTC too (#4043) | ADOPT | - | Hand-ported: the AgLibraryIPTC caption wins over the cached XMP packet's; test ported, docs + notes | `cf4027be34` | 2026-11-17 @ aa08a77060 | `8ea42505e` | | #4321 | open | LR-IMP-ADD-DIALOG: library.import reports what its folder walk skipped (#4319) | ADOPT | - | Ported early: library.import reports unreadable/unsupported files its folder walk skipped | `1169f1e847` | 2026-11-17 @ aa08a77060 | `14b97c6e6` | | #4323 | merged | Use coverage-aware deadlines for asynchronous UI checks | LEARN | - | Merged; test-deadline plumbing in upstream ui-egui. Idea only: coverage-aware deadlines if fork UI tests flake | `3a616261e3` | 2026-11-17 @ aa08a77060 | - | | #4329 | open | LR-FILT-TYPE: photo types from metadata (selfie, panorama, long exposure, screenshot, drone) | PENDING | upstream merge | Large catalog-model and query feature, unmerged; base of #4345 | `911c3fcace` | 2026-11-16 @ a4676b1249 | - | -| #4338 | open | Issue #3050: report non-rendering XMP bookkeeping apart from adjustments | PENDING | #4272 lands | Stacked on unmerged #4272; ui-egui part needs a hand-port | `3511bce5fc` | 2026-11-16 @ a4676b1249 | - | +| #4338 | open | Issue #3050: report non-rendering XMP bookkeeping apart from adjustments | PENDING | #4272 lands | Rebased (adds a singleton field-cap test); still stacked on open #4272. | `c5adc1583e` | 2026-11-29 @ 2d62488dd2 | - | | #4342 | open | LR-IMP-FORMATS: mark photos that have recorded depth (has_depth) | PENDING | upstream merge | Catalog-format field, unmerged; base of the Portrait/depth stack | `c215724db3` | 2026-11-16 @ a4676b1249 | - | | #4343 | open | LR-IMP-FORMATS: read the aperture chosen on the phone from iPhone Portrait photos | PENDING | #4342 lands | Stacked on #4342 | `66988a3cc2` | 2026-11-16 @ a4676b1249 | - | | #4344 | closed | LR-IMP-FORMATS: a HEIC's own XMP is read, not its depth map's or gain map's | SKIP | replacement PR | Closed unmerged (stacked, CodeRabbit red); look again at the aux-image XMP bug if a replacement appears | `1d636a186c` | 2026-11-16 @ a4676b1249 | - | @@ -1074,11 +1083,35 @@ PR head or commit SHA. A pipe inside a cell is escaped with a backslash. | #2018 | merged | Workspace: rust-version 1.95 | SKIP | - | Empty diff when merged; the fork's workspace already declares `rust-version = "1.95"`. | `3f4ef77159` | 2026-11-27 @ 5973d956df | - | | #2194 | merged | MENU-BAR: every command has a place in the menus, and View drops from 63 rows | LEARN | - | Menu layout in upstream's menubar plus menu-path edits in engine command specs and 17 locales; the fork owns its menus (`menus.rs`, `lrc_menus.rs`). Idea: give every command a slot and keep the end-of-menu fallback empty with a test. | `4f2150f97f` | 2026-11-27 @ 5973d956df | - | | #2838 | merged | Lightroom import: keep compressed history-step and snapshot settings in the archive | SKIP | - | Already in the fork as its own change: fork #632 (d08f388ee) decodes compressed history steps and snapshots, with `tests_lightroom_history.rs` and `lightroom_fixture.rs`. | `93baba5a67` | 2026-11-27 @ 5973d956df | `d08f388ee` | +| #4444 | open | LR-VIEW-ZOOM: dragging a mask keeps the photo sharp (#1679) | ADOPT | - | region::SHARP_DRAG; the fork has three call sites in panels/detail.rs. Test brought over. | `3efa9c8cfd` | 2026-11-29 @ 2d62488dd2 | `4fc144152` | +| #4482 | open | Unbounded waits in preview, gpu and ui-egui tests get a time limit | ADOPT | - | Fork already had the preview and gpu halves; only three file_probe waits got the 60 s limit. | `7ad2873f56` | 2026-11-29 @ 2d62488dd2 | `9468923d8` | +| #4484 | open | LRC-PRINT-PAGE: the contact sheet's Paper box shows A4 / Letter, not a4 / letter | ADOPT | - | Hand-ported into panels/dialogs.rs with a test. | `e35ef9cf60` | 2026-11-29 @ 2d62488dd2 | `cb32ba309` | +| #4490 | open | body_corpus compares the X100VI mosaic with its camera JPEG unrotated | SKIP | - | Already so in the fork: body_corpus decodes the camera JPEG with zune_jpeg, which never applies orientation. | `7127eb77e8` | 2026-11-29 @ 2d62488dd2 | - | +| #4497 | merged | MCP: export's bitDepth has no integer enum, which Gemini refuses (#4496) | ADOPT | - | Integer enum removed, values in the description; upstream's strings-only enum test ported. | `c498a457dd` | 2026-11-29 @ 2d62488dd2 | `2291eae7b` | +| #4528 | open | #4527: preserve JPEG XL options in MCP export | ADOPT | - | The forwarded-key list lacked jxlLossless/jxlEffort/jxlProgressive; upstream test ported. | `29ed08e4b7` | 2026-11-29 @ 2d62488dd2 | `acc72a1a9` | +| #4535 | open | 4534: fix Rust 1.95 Clippy in camera-profile lookup | SKIP | - | The negated is_some_and line doesn't exist in the fork's camera_profiles.rs; clippy clean. | `58e8bbc7c1` | 2026-11-29 @ 2d62488dd2 | - | +| #4538 | open | `lightcraft-cli mcp FOLDER` keeps serving when the folder has no photos | ADOPT | - | Fork's apps/cli/src/lib.rs sent an empty path list to library.import and quit. Hand-ported with the e2e test (apps/cli/tests/mcp_empty_folder.rs). | `f36066e591` | 2026-11-29 @ 2d62488dd2 | `be29ce402` | +| #4565 | open | fix(import): normalize preset and import keywords | ADOPT | - | Hand-ported into the fork's import.rs apply_settings; upstream's import_keywords integration test ported. | `7513c92765` | 2026-11-29 @ 2d62488dd2 | `8421e3969` | +| #4568 | open | fix(keywords): reject malformed saved-set slots | ADOPT | - | Cherry-picked both commits; test renamed to lcc_. | `463e2c4fcd` | 2026-11-29 @ 2d62488dd2 | `0519c8df8` | +| #4572 | open | fix(print): report oversized cell pages without overflow | ADOPT | - | Fork had c.page + 1 on a u32 in print/layout.rs. Hand-ported with upstream's page_overflow_tests. | `6b61d0ef9a` | 2026-11-29 @ 2d62488dd2 | `71e926cec` | | #4608 | merged | deps: update candle to 0.11.1 to move zip past GHSA-m665-v7pm-7grj | ADOPT | - | The fork already avoids the critical zip 7 advisory: its vendored candle-core 0.9.2 uses zip 9 (`vendor/candle-core`). But the lockfile had zip 9.2.2, still under the two later zip advisories the PR names (GHSA-h5xf-qc2v-94w6, fixed 9.2.0; GHSA-fpwh-q2m5-vfm2, fixed 9.2.3). Taken: `cargo update -p zip` to 9.8.2 (adds constant_time_eq 0.6.2). The candle 0.11.1 bump itself is not taken; the vendored patch stays. | `76bcfaae45` | 2026-11-27 @ 5973d956df | `88a4038e0` | +| #4622 | open | Slideshow: skip photo effects when there is no photo | ADOPT | - | Applied cleanly with its test. | `6a381bddad` | 2026-11-29 @ 2d62488dd2 | `9ddf4c3d5` | +| #4627 | open | Reject malformed preset IDs before exporting | ADOPT | - | Hand-ported into preset_files.rs export(): an explicit ids must be an array of strings. Test in tests_export.rs. | `d07606c65b` | 2026-11-29 @ 2d62488dd2 | `c7fa4cad0` | +| #4628 | open | Preserve absolute filesystem roots in Local browse | ADOPT | - | Trimming turned C:\ and / into broken roots. Hand-ported import::browse_folder_string with unit tests, used in cmd/browse.rs and two ui-egui call sites. | `e13354cb52` | 2026-11-29 @ 2d62488dd2 | `c224702d1` | +| #4633 | open | fix(proof): preserve the selected ICC profile path | ADOPT | - | Cherry-picked: proof::load no longer trims the picked path. | `24f5683eb8` | 2026-11-29 @ 2d62488dd2 | `530afa632` | +| #4653 | open | fix(#4652, #4658): Select revealed photos in the Linux file manager | ADOPT | - | Hand-ported into apps/app/src/reveal.rs (zbus already a Linux dep): FileManager1.ShowItems with a 2 s timeout, xdg-open spawned without waiting (the freeze), Services::reveal_many. Not run on Linux. | `0b2744eddb` | 2026-11-29 @ 2d62488dd2 | `79f41fbdf` | +| #4663 | open | feat(#4662): Add LIGHTCRAFT_DISABLE_UPDATES opt-out for update checks | ADOPT | - | _DISABLE_UPDATES via lcc_brand::env: update.check refuses, start-up check skipped, Help > Check for Updates greyed with a reason (17 fork catalogs). Nix wrapper sets it (not evaluated). | `0ee1391957` | 2026-11-29 @ 2d62488dd2 | `da85582c9` | +| #4684 | open | Expand subfolder tokens for each exported photo | PENDING | fork token subfolders | Makes upstream's {token} subfolders expand per photo; the fork's export subfolder is one plain name without tokens (subfolder_problem). Token subfolders first. | `801c76bf21` | 2026-11-29 @ 2d62488dd2 | - | | #4695 | merged | ui-egui, catalog: name the camera above the Edit header | LEARN | - | Edit panel shows a cleaned-up camera name (maker words dropped, maker not said twice). The edit panel is fork-owned ui-egui; the name cleanup in `crates/catalog/src/model.rs` would need its own home in the fork. A feature to port by hand if wanted. | `339b0d72e4` | 2026-11-27 @ 5973d956df | - | +| #4716 | open | engine: move a shared stem XMP sidecar only with the photo that owns it (#4713) | PENDING | dedicated hand-port | About 590 lines assuming upstream's split rename/{moves,plan,sidecar}.rs; the fork still has one rename.rs, and it changes undo entries. Real raw+JPEG data bug: needs its own port. | `21dbfee808` | 2026-11-29 @ 2d62488dd2 | - | | #4720 | merged | UI: export watermark Position is a 3x3 grid | ADOPT | - | The fork's Edit Watermarks dialog had the same single row of nine arrows (`choices`). Hand-ported as a 3 x 3 grid in `panels/dialogs.rs`, same widget ids, checked in a headless screenshot. | `94b2e94744` | 2026-11-27 @ 5973d956df | `5b0ec87be` | | #4723 | merged | packaging(linux): support co-installable nightly packages | SKIP | - | Upstream's nightly packaging, signing and launcher (apps, workflows, assets); the fork has its own nightly channel and packaging. | `5a20f060c9` | 2026-11-27 @ 5973d956df | - | +| #4729 | open | LR-META-XMP: an older process version's untouched defaults are not an edit | ADOPT | - | Cherry-picked; an import-time read only, existing catalog renders unchanged. | `cae6cf087f` | 2026-11-29 @ 2d62488dd2 | `0a4024ad0` | +| #4730 | open | engine: report final slideshow PDF bytes (#4715) | ADOPT | - | Hand-ported: bytes read from file metadata after the fork's sync_file; upstream asserts added. | `6e99e5e8b3` | 2026-11-29 @ 2d62488dd2 | `d5b22ebc0` | +| #4737 | open | mcp: continue exports after missing originals (#4714) | ADOPT | - | Hand-ported in mcp/headless.rs (stop_on_error only for a single photo); docs/mcp.md and control-protocol.md updated. | `ede1546d23` | 2026-11-29 @ 2d62488dd2 | `9f57e59e6` | | #4740 | merged | Use the shared nightly launcher template | SKIP | - | Upstream nightly Linux launcher scripts only. | `10c12418ac` | 2026-11-27 @ 5973d956df | - | +| #4741 | open | engine: skip image probes for linked catalog videos | ADOPT | - | Adapted: added is_catalog_video (the fork had none), used in lightroom_job::original_paths; test uses .MOV. | `3fc7494697` | 2026-11-29 @ 2d62488dd2 | `ef74a81ed` | +| #4747 | open | engine: skip warnings for inactive legacy XMP fields | ADOPT | - | Final state of both commits hand-applied; the fork's develop_field_coverage test loses AutoWhiteVersion from its unmapped list. | `03d61a7f6d` | 2026-11-29 @ 2d62488dd2 | `964f12827` | | #4749 | merged | Switch on supervised nightlies on the nightly-signer branch | SKIP | - | Upstream nightly signing workflows and policy only. | `564e85a522` | 2026-11-27 @ 5973d956df | - | | #4752 | merged | Nightly: stop blocking a refused launch on macOS | SKIP | - | Fixes upstream's nightly launch-profile refusal dialog (#4723), which the fork does not have. | `e5aaa4cffe` | 2026-11-27 @ 5973d956df | - | | #4811 | merged | SAM 3: reduce DX12 attention pipeline startup time | SKIP | - | Smaller attention tiles in upstream's `crates/gpu` SAM 3 kernels; the fork has no SAM 3 GPU path (the #2533-#2537 stack is SKIP). | `d0a13f3587` | 2026-11-27 @ 5973d956df | - | @@ -1146,3 +1179,4 @@ PR head or commit SHA. A pipe inside a cell is escaped with a backslash. | round 11 (#2661 settled) | 2026-11-25 | `ea033fbe1c` | 1: the carried PENDING row #2661, re-read in full (squash commit, PR reviews and threads) | 1 part: Boost `0e45c1889` onto the fork's depth-based Lens Blur | #2661 now LEARN: its full port (fork PR #1500) duplicated fork PR #1498 and was closed; brush refinement and per-mask Lens Blur ported after it onto the depth renderer; #4349 (Lens Blur on iPhone Portrait depth) stays PENDING | upstream intake 2026-11-25 | | monitor 2026-11-27 | 2026-11-27 | `5973d956df` (craft-libs `0ebc5915b0`) | upstream: 8 of 148 waiting rows moved (6 merged, 2 heads moved by main merges only); craft-libs: 0 of 5 waiting rows moved, 11 PRs on tracked paths since 2026-11-25, 2 merged (#3536 next into main: test sizing, a craft-cms split the fork does not use; #3578 jpeg-encoder 0.7, already in the fork), the rest open drafts, refactors or features: SKIP unlisted | 1: #2896 remainder `d21affb32` | #2378 WATCH; #3141, #3943, #1958 PENDING though merged upstream; #2584 SKIP; #2822, #3429 PENDING | upstream intake 2026-11-27 | | monitor 2026-11-27 (unlogged merges) | 2026-11-27 | `5973d956df` | 13 PRs merged upstream since 2026-11-25 that had no ledger row (most from the 2026-11-26 backlog merge) | 3: #4816 fork fix `c73d05733`, #4608 zip lockfile bump `88a4038e0`, #4720 watermark grid `5b0ec87be` | LEARN #1900 #2194 #4695; SKIP #2018 #2838 (already in the fork) #4723 #4740 #4749 #4752 #4811 | upstream intake 2026-11-27 | +| round 12 (backlog triage) | 2026-11-29 | `2d62488dd2` (craft-libs `857784e6b1`) | upstream: 10 of 146 waiting rows moved; 275 PRs updated since 2026-11-25 with no ledger or archive row triaged in 5 batches (35 ADOPT NOW candidates, the rest PENDING/LEARN/SKIP, kept in the round report, not as rows); craft-libs: 0 of 5 waiting rows moved, 12 merged PRs on tracked paths all SKIP (#3900 joins the #534 rev-bump decision) | 26: #1828 #4538 #4628 #1638 #4565 #4741 #4730 #4627 #4622 #4572 #4568 #4633 #1204 #1736 #4747 #4729 #1261 #1704 #4653 #4663 #4482 #4444 #4484 #4737 #4528 #4497 | PENDING #4716 #4684 #1079 #1069 #2675; SKIP #1837 #4490 #4535 #4285; LEARN #4215; OpenFill: no such upstream PR found | upstream intake 2026-11-29 | From 028d2ad02ad9084a740c6819f10af4059f467310 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 15:47:12 +1100 Subject: [PATCH 032/112] upstream #1261: the GPU renders a positive Paint vignette as the CPU does The port changed finish.rs only, so a GPU preview kept the old lift while a CPU render blended toward white. finish.wgsl now has the same branch, and in HDR neither pulls highlights above SDR white down to it. Checked: lcc-gpu equivalence tests (paint + and -), lcc-pipeline tests. Manual: none, develop/effects.mdx already describes it Co-Authored-By: Claude Fable 5.2 --- crates/gpu/src/wgsl/finish.wgsl | 21 ++++++++++++++------- crates/pipeline/src/finish.rs | 12 +++++++++--- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 4f7f24b024..6c27aacbee 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -1230,17 +1230,24 @@ fn main(@builtin(global_invocation_id) gid: vec3) { let t = sstep(start, start + pf(F_VIG_WIDTH), dist); if (t > 0.0) { let lum = clamp(lum2020(d), 0.0, 1.0); - if (amount < 0.0) { + let style = pu(F_VIG_STYLE); + if (style == 2u) { + // Paint: a flat overlay toward black (negative) or white (positive), as the CPU's + // finish.rs; in HDR it never pulls highlights down to SDR white + let w = abs(amount) * t; + if (amount < 0.0) { + d = d * (1.0 - w); + } else if (hdr) { + d = max(d, d * (1.0 - w) + vec3(w)); + } else { + d = d * (1.0 - w) + vec3(w); + } + } else if (amount < 0.0) { var f = 1.0 + amount * t; - let style = pu(F_VIG_STYLE); if (style == 1u) { f += (1.0 - f) * pf(F_VIG_HL) * sstep(0.4, 1.0, lum); } - if (style == 2u) { - d = d * (1.0 - (-amount) * t) + 0.0; - } else { - d = d * f; - } + d = d * f; } else if (hdr) { // lighten towards SDR white; never pull HDR highlights down to it d = d + max(vec3(1.0) - d, vec3(0.0)) * amount * t * 0.85; diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index c06a957623..2212c77c9a 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -1097,10 +1097,16 @@ pub(crate) fn finish_with( if v.style == VignetteStyle::PaintOverlay { // Paint is a flat overlay toward black (negative) or white (positive); Color and // Highlight Priority stay a multiply or a lift, so the style tabs differ once Amount - // leaves 0. Adapted from upstream #1261. + // leaves 0. Adapted from upstream #1261. (finish.wgsl does the same.) let w = v.amount.abs() * t; - let toward = if v.amount < 0.0 { 0.0 } else { 1.0 }; - d = d.map(|c| c * (1.0 - w) + toward * w); + if v.amount < 0.0 { + d = d.map(|c| c * (1.0 - w)); + } else if hdr { + // towards SDR white; never pull HDR highlights down to it + d = d.map(|c| c.max(c * (1.0 - w) + w)); + } else { + d = d.map(|c| c * (1.0 - w) + w); + } } else if v.amount < 0.0 { let mut f = 1.0 + v.amount * t; if v.style == VignetteStyle::HighlightPriority { From 0e9bfdf7c6d196b46bcfbfdde50e7473df3a69bc Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 15:47:12 +1100 Subject: [PATCH 033/112] upstream #1638: overlapping roots never lose a folder Three faults in the port: a folder whose canonical path can't be had (some network and virtual drives) was left out without a word, now it is walked under its own spelling; a subfolder an earlier root only passed by (an import without subfolders) counted as walked, so naming it as a root of its own imported nothing; and a single root paid a canonicalize per folder for nothing to compare with. Checked: walk test shared_roots_walk_a_folder_once_but_not_one_they_only_passed, overlapping_roots tests. Manual: none, no user-visible change Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/import.rs | 3 +++ crates/engine/src/walk.rs | 33 ++++++++++++++++++++++++++++----- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index ebe10ce03a..8e9e811cea 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -764,7 +764,10 @@ fn expand_report_noting( } keep }; + // one root can't overlap another: it is walked without asking for canonical paths let w = match note.as_mut() { + Some(note) if paths.len() < 2 => crate::walk::files_in_noting(p, skip, walk_limits, keep, &mut **note), + None if paths.len() < 2 => crate::walk::files_in(p, skip, walk_limits, keep), Some(note) => crate::walk::files_in_with_seen(p, skip, walk_limits, keep, Some(&mut **note), &mut seen_dirs), None => crate::walk::files_in_with_seen(p, skip, walk_limits, keep, None, &mut seen_dirs), }; diff --git a/crates/engine/src/walk.rs b/crates/engine/src/walk.rs index 86ac888282..e791b2d9d5 100644 --- a/crates/engine/src/walk.rs +++ b/crates/engine/src/walk.rs @@ -213,8 +213,16 @@ fn walk( if skip.is_some_and(|s| path == s) || skip_canonical.as_ref().is_some_and(|s| std::fs::canonicalize(&path).is_ok_and(|p| p.starts_with(s))) { continue; } + if depth >= limits.max_depth { + out.truncated = true; + continue; + } + // after the depth check: a folder too deep to be read here was not walked, so a later root + // that names it still is if let Some(seen) = shared.as_deref_mut() { - let Ok(real) = std::fs::canonicalize(&path) else { continue }; + // a folder whose canonical path can't be had (some network and virtual drives) is + // walked under its own spelling rather than left out + let real = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone()); if seen.len() >= MAX_ENTRIES && !seen.contains(&real) { out.truncated = true; break; @@ -223,10 +231,6 @@ fn walk( continue; } } - if depth >= limits.max_depth { - out.truncated = true; - continue; - } let Ok(rd) = std::fs::read_dir(&path) else { out.unreadable = out.unreadable.saturating_add(1); continue; @@ -552,4 +556,23 @@ mod tests { assert!(w.files.iter().any(|p| p.ends_with("a/b/p.jpg")), "{w:?}"); let _ = std::fs::remove_dir_all(&d); } + + /// Roots sharing `seen`: a folder is walked once, but one that an earlier root only passed by + /// (too deep for it: an import without subfolders) is still walked when a later root names it. + #[test] + fn shared_roots_walk_a_folder_once_but_not_one_they_only_passed() { + let d = tmp("seen"); + std::fs::create_dir_all(d.join("sub")).unwrap(); + std::fs::write(d.join("top.jpg"), b"x").unwrap(); + std::fs::write(d.join("sub/inner.jpg"), b"x").unwrap(); + let flat = Limits { max_depth: 1, ..Limits::default() }; + let mut seen = HashSet::new(); + let top = files_in_with_seen(&d, None, flat, |_| true, None, &mut seen); + assert_eq!(top.files, [d.join("top.jpg")]); + let sub = files_in_with_seen(&d.join("sub"), None, flat, |_| true, None, &mut seen); + assert_eq!(sub.files, [d.join("sub/inner.jpg")], "the subfolder named as a root of its own"); + let again = files_in_with_seen(&d.join("sub"), None, flat, |_| true, None, &mut seen); + assert!(again.files.is_empty(), "walked once: {again:?}"); + let _ = std::fs::remove_dir_all(&d); + } } From 02835c2d8aadd953fc02fb501991c0d3ef2e33cd Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 15:47:12 +1100 Subject: [PATCH 034/112] Windows: clippy passes on the Unix-only test helpers; two doc comments back in place safe_file's progress test read a sync count only its Unix assertion uses; import_move's Hold helpers and io_sched's pin_raised serve Unix-only tests. All five failed `clippy --all-targets -D warnings` on Windows. The menu hint and the mask-drag test of this round had each taken the doc comment of the item below them. Manual: none, no user-visible change Co-Authored-By: Claude Fable 5.2 --- crates/catalog/src/safe_file.rs | 1 + crates/engine/src/import_move.rs | 6 ++++++ crates/engine/src/io_sched/shared.rs | 1 + crates/ui-egui/src/menubar.rs | 4 ++-- crates/ui-egui/src/region.rs | 2 +- 5 files changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/catalog/src/safe_file.rs b/crates/catalog/src/safe_file.rs index dcadb4fde2..300803a176 100644 --- a/crates/catalog/src/safe_file.rs +++ b/crates/catalog/src/safe_file.rs @@ -937,6 +937,7 @@ mod tests { let d = temp(&format!("progress-{len}")); let data: Vec = (0..len).map(|i| (i % 251) as u8).collect(); let heard = Heard::default(); + #[cfg(unix)] let syncs = syncs_on_this_thread(); let got = write_new_unique_progress(&mut std::iter::once(d.join("a.dng")), &data, &heard).unwrap(); assert_eq!(fs::read(&got).unwrap(), data); diff --git a/crates/engine/src/import_move.rs b/crates/engine/src/import_move.rs index c4ed1d2b76..3fd35a3399 100644 --- a/crates/engine/src/import_move.rs +++ b/crates/engine/src/import_move.rs @@ -94,6 +94,8 @@ pub(crate) fn copy_threads() -> Vec { /// What a copy into a held folder does (tests only, [`hold_copies_into`]). #[cfg(test)] +// (the tests that use it are Unix-only) +#[cfg_attr(not(unix), allow(dead_code))] #[derive(Clone)] pub(crate) enum Hold { /// Wait, once its bytes are written and before the flush, until the gate opens. @@ -110,12 +112,16 @@ static HOLDS: std::sync::Mutex> = std::sync::Mutex::new(Vec /// Copies into `dir` (any thread) hold as `hold` says until [`release_copies_into`] (tests only): /// a fake hung or failing destination for real copies. #[cfg(test)] +// (the tests that use it are Unix-only) +#[cfg_attr(not(unix), allow(dead_code))] pub(crate) fn hold_copies_into(dir: &Path, hold: Hold) { HOLDS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((dir.to_path_buf(), hold)); } /// Copies into `dir` go on: a waiting copy resumes, later ones run as usual (tests only). #[cfg(test)] +// (the tests that use it are Unix-only) +#[cfg_attr(not(unix), allow(dead_code))] pub(crate) fn release_copies_into(dir: &Path) { let mut holds = HOLDS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); for (_, h) in holds.iter().filter(|(d, _)| d == dir) { diff --git a/crates/engine/src/io_sched/shared.rs b/crates/engine/src/io_sched/shared.rs index 2c097407e8..600240003e 100644 --- a/crates/engine/src/io_sched/shared.rs +++ b/crates/engine/src/io_sched/shared.rs @@ -159,6 +159,7 @@ impl Shared { /// Make volume `key`'s raise `n` whatever the controller publishes (tests). #[cfg(test)] + #[cfg_attr(not(unix), allow(dead_code))] // its tests are Unix-only pub(crate) fn pin_raised(&self, key: VolumeKey, n: usize) { self.pinned.lock().unwrap_or_else(PoisonError::into_inner).insert(key, n); } diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rs index 16ab45da17..0e147e58df 100644 --- a/crates/ui-egui/src/menubar.rs +++ b/crates/ui-egui/src/menubar.rs @@ -130,11 +130,11 @@ pub fn native_menu_structure(bar: &[(String, Vec)], keymap: &crate::sh s } -/// The Library module's menus in order (the macOS app menu is added by the host); [`menus`] gives -/// the module on screen's. /// Hover text of Help ▸ Check for Updates… when `_DISABLE_UPDATES` turned it off. const UPDATES_DISABLED_HINT: &str = "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates."; +/// The Library module's menus in order (the macOS app menu is added by the host); [`menus`] gives +/// the module on screen's. pub const MENUS: &[&str] = &["File", "Edit", "Library", "Photo", "Metadata", "View", "Window", "Help"]; /// Order inside submenus whose items come from the registry: (menu, submenu, ids and `---`). diff --git a/crates/ui-egui/src/region.rs b/crates/ui-egui/src/region.rs index 3b8e3b3711..49744953b2 100644 --- a/crates/ui-egui/src/region.rs +++ b/crates/ui-egui/src/region.rs @@ -1109,7 +1109,6 @@ mod tests { assert_eq!(d.scale(drag, false, None, 0.0), Some(1.0)); } - /// One whole drag of `drag` at full size whose drafts all take `ms` to show, ending at `now`. // Given a mask edit on the photo (a gradient's handle or pin dragged), its drafts are full size // even on the CPU, after slow drags, and when they are far over budget: the photo stays sharp // (upstream #4444) @@ -1132,6 +1131,7 @@ mod tests { assert_eq!(d.scale(Some((PhotoId(1), "Exposure")), false, None, 10.0), Some(CPU_DRAFT_SCALE)); } + /// One whole drag of `drag` at full size whose drafts all take `ms` to show, ending at `now`. fn timed_drag(d: &mut DragScale, drag: Option<(lcc_catalog::PhotoId, &str)>, ms: f64, now: f64) -> Option { let scale = d.scale(drag, true, None, now); for key in 1..=6 { From b3d1f7fb7d88e353ffe43ae6f02c76497d98a6a5 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sun, 29 Nov 2026 16:53:31 +1100 Subject: [PATCH 035/112] FX-50: a backup made in a second a prune freed is not pruned as the oldest Two libraries sharing a backup folder, three backups each within one second: pruning the first library's oldest freed the plain `