From d466da3d57153aec0e73f9a76e9aef765f5b4a49 Mon Sep 17 00:00:00 2001 From: Fabio Lissi Date: Tue, 13 Oct 2026 10:45:26 -0500 Subject: [PATCH 1/2] Camera Raw: Calibration panel, Auto, raw sidecars and live Camera Raw Defaults (FILE-215-11) Three pieces of G14 that needed no new data or dependencies. Calibration: Camera Raw's panel (Shadows tint, Red/Green/Blue Primary hue and saturation) as a develop stage in linear light. A pixel's hue turns by the weighted Hue of the primaries it is made of (triangular weights at 0, 120 and 240 degrees; +/-100 is +/-30 degrees, towards the next primary) and its saturation scales by their weighted Saturation; the luminance is kept, so neutrals are untouched. The shadow tint is magenta or green weighted by darkness, luminance kept, white untouched. The seven crs: keys load and save with the settings file, and filter.cameraRaw takes shadowTint, calibrationHue and calibrationSat. Auto: the Light panel's button (and "auto": true on the control channel) sets Exposure, Contrast, Highlights, Shadows, Whites and Blacks from the image's luminance histogram; the sliders show what it chose. The Apply auto tone preference opens a raw with it. Sidecars: a raw opened from a path reads IMG_0001.xmp beside it into the open-time dialog, naming in the status bar what the loader skipped (the absolute kelvin white balance has no counterpart), and Open writes the sidecar back when the settings aren't the defaults or one exists; never beside a DNG, off with the new rawDefaults.writeXmpSidecars preference. With "Open in Camera Raw" off, the sidecar still develops the file. Camera Raw Defaults: the six preferences the dialog hid as dead now act when a raw opens, with or without the dialog: colour space (a conversion from the develop's ProPhoto; Adobe RGB by default, as Photoshop's workflow), bit depth, resolution (300 ppi from 72), Sharpen For (folded into the Camera Raw step as 25/1.0, 35/1.2 or 40/1.0), Open as Smart Object and Apply auto tone; the dialog's reply lists what it applied, and opening still leaves the document unmodified. Tests: calibration maths and Auto (algo), the preset's RedHue now applied (io), calibration round trip, Auto and its preference, sidecar read / write / DNG / preference / no-dialog, and the defaults on open (ui-egui); the hidden-preference test lists the Camera Raw rows as live. Nine strings in every catalog. Scorecard FILE-215-11 missing -> partial with the evidence (lossy DNG from #5112 included); gaps G14 updated, with the CR3 assessment: the CRX codec has no public specification, only LGPL implementations, so a clean-room decoder is not possible. --- crates/algo/src/camera_raw.rs | 201 +++++++++++++++ crates/engine/src/lens_cmds.rs | 2 +- crates/engine/src/prefs.rs | 36 ++- crates/io/src/camera_raw_xmp.rs | 16 +- crates/ui-egui/src/camera_raw_ui.rs | 363 +++++++++++++++++++++++++++- crates/ui-egui/src/i18n/cs.tsv | 10 + crates/ui-egui/src/i18n/de.tsv | 10 + crates/ui-egui/src/i18n/el.tsv | 10 + crates/ui-egui/src/i18n/es.tsv | 10 + crates/ui-egui/src/i18n/fr.tsv | 10 + crates/ui-egui/src/i18n/hu.tsv | 10 + crates/ui-egui/src/i18n/id.tsv | 10 + crates/ui-egui/src/i18n/it.tsv | 10 + crates/ui-egui/src/i18n/ja.tsv | 10 + crates/ui-egui/src/i18n/ko.tsv | 10 + crates/ui-egui/src/i18n/nl.tsv | 10 + crates/ui-egui/src/i18n/pl.tsv | 10 + crates/ui-egui/src/i18n/pt-br.tsv | 10 + crates/ui-egui/src/i18n/ru.tsv | 10 + crates/ui-egui/src/i18n/sr.tsv | 10 + crates/ui-egui/src/i18n/tr.tsv | 10 + crates/ui-egui/src/i18n/uk.tsv | 10 + crates/ui-egui/src/i18n/vi.tsv | 10 + crates/ui-egui/src/i18n/zh-hans.tsv | 10 + crates/ui-egui/src/i18n/zh-hant.tsv | 10 + crates/ui-egui/src/jobs_ui.rs | 1 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/prefs_ui.rs | 7 +- docs/control-protocol.md | 12 +- docs/gaps.md | 15 +- docs/scorecard.md | 10 +- scorecard/file_compat.toml | 4 +- 32 files changed, 837 insertions(+), 33 deletions(-) diff --git a/crates/algo/src/camera_raw.rs b/crates/algo/src/camera_raw.rs index f855b08bfec..faab3731ee3 100644 --- a/crates/algo/src/camera_raw.rs +++ b/crates/algo/src/camera_raw.rs @@ -172,6 +172,13 @@ pub struct CameraRaw { /// The document's transfer curve: 0 for sRGB's, else the gamma of a power-law space (1.8 /// for ProPhoto). Set from the document's profile; Whites and Blacks act on light. pub encoding_gamma: f32, + // Calibration (Camera Raw's Calibration panel) + /// Shadows › Tint: −100 (green) … 100 (magenta), strongest in the darkest tones. + pub shadow_tint: f32, + /// Red, Green and Blue Primary › Hue: −100 … 100, the primary turned towards its neighbours. + pub calibration_hue: [f32; 3], + /// Red, Green and Blue Primary › Saturation: −100 (grey) … 100 (purer). + pub calibration_sat: [f32; 3], } impl Default for CameraRaw { @@ -228,6 +235,9 @@ impl Default for CameraRaw { seed: 0, pixel_scale: 1.0, encoding_gamma: 0.0, + shadow_tint: 0.0, + calibration_hue: [0.0; 3], + calibration_sat: [0.0; 3], } } } @@ -235,6 +245,90 @@ impl Default for CameraRaw { /// Hue band centres of the Color Mixer (degrees). pub const HSL_BANDS: [f32; 8] = [0.0, 30.0, 60.0, 120.0, 180.0, 240.0, 270.0, 300.0]; +/// How far a primary turns at Hue ±100 (degrees), as the Color Mixer's hue sliders do. +const CALIBRATION_TURN: f32 = 30.0; + +/// How much of each primary (red, green, blue) a hue is made of: triangular weights around +/// 0°, 120° and 240° that sum to one, so a colour between two primaries follows both. +pub fn calibration_weights(hue: f32) -> [f32; 3] { + let h = hue.rem_euclid(360.0); + let mut w = [0.0f32; 3]; + for (i, centre) in [0.0f32, 120.0, 240.0].iter().enumerate() { + let d = (h - centre).abs().min(360.0 - (h - centre).abs()); + w[i] = (1.0 - d / 120.0).max(0.0); + } + let sum: f32 = w.iter().sum(); + if sum > 1e-6 { w.map(|v| v / sum) } else { [1.0, 0.0, 0.0] } +} + +/// The Calibration panel's primaries on one linear-light pixel: its hue turns by the weighted +/// Hue of the primaries it is made of (±100 is ±30°, positive towards the next primary) and its +/// saturation scales by their weighted Saturation (−100 greys it); the luminance is kept, so +/// neutrals are untouched. +fn calibrate(c: [f32; 3], hue: [f32; 3], sat: [f32; 3]) -> [f32; 3] { + let [h, s, v] = rgb_to_hsv(c.map(|x| x.max(0.0))); + if s <= 1e-5 || v <= 1e-6 { + return c; + } + let w = calibration_weights(h); + let (mut dh, mut ds) = (0.0f32, 0.0f32); + for i in 0..3 { + dh += w[i] * hue[i].clamp(-100.0, 100.0); + ds += w[i] * sat[i].clamp(-100.0, 100.0); + } + let nh = h + dh / 100.0 * CALIBRATION_TURN; + let ns = (s * (1.0 + ds / 100.0)).clamp(0.0, 1.0); + let out = hsv_to_rgb(nh, ns, v); + let (l0, l1) = (luma(c), luma(out)); + if l1 > 1e-6 { out.map(|x| x * l0 / l1) } else { out } +} + +/// Shadows › Tint on one linear-light pixel: `tint` −1 (green) … 1 (magenta), weighted by how +/// dark the pixel is; the luminance is kept. +fn shadow_tint(c: [f32; 3], tint: f32) -> [f32; 3] { + let l = luma(c).max(0.0); + // Linear 0.18 is middle grey: full strength below it, fading out towards white. + let weight = (1.0 - (l / 0.18).sqrt().min(1.0)).powi(2) * 0.5 + (1.0 - l.min(1.0)).powi(4) * 0.5; + let k = tint * 0.12 * weight * (l + 0.02); + let o = [c[0] + k, c[1] - k, c[2] + k].map(|v| v.max(0.0)); + let l2 = luma(o); + if l2 > 1e-6 { o.map(|v| v * l / l2) } else { o } +} + +/// Camera Raw's Auto for the Light panel: Exposure, Contrast, Highlights, Shadows, Whites and +/// Blacks from the image's luminance histogram (`px` in the document's encoding). A well +/// exposed image gets near-zero settings; a dark one more exposure and lifted shadows; one +/// with a crushed or blown end gets Blacks or Whites back from the edge. The other panels are +/// left alone, as Camera Raw's Auto leaves them. +pub fn auto_tone(px: &[[f32; 4]], p: &mut CameraRaw) { + if px.is_empty() { + return; + } + let mut lum: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]]).clamp(0.0, 1.0)).collect(); + lum.sort_by(|a, b| a.total_cmp(b)); + let at = |f: f32| lum[((lum.len() - 1) as f32 * f).round() as usize]; + let (black, shadow, median, light, white) = (at(0.001), at(0.1), at(0.5), at(0.9), at(0.999)); + // Exposure: the median towards middle grey (sRGB 0.46), damped so flat scenes aren't + // forced to it. + let median_lin = srgb_to_linear(median).max(1e-4); + p.exposure = (0.6 * (0.18f32 / median_lin).log2()).clamp(-2.0, 2.0); + // Blacks and Whites bring the ends to the edges without clipping more than Camera Raw does. + p.blacks = ((0.04 - black) * 400.0).clamp(-40.0, 40.0); + p.whites = ((0.96 - white) * 300.0).clamp(-40.0, 40.0); + // Shadows up when the darker tenth is crushed, highlights down when the brighter tenth is + // near white. + p.shadows = ((0.25 - shadow) * 200.0).clamp(0.0, 50.0); + p.highlights = ((light - 0.85) * -300.0).clamp(-50.0, 0.0); + // A little contrast for a flat histogram. + let spread = (light - shadow).max(0.0); + p.contrast = ((0.6 - spread) * 60.0).clamp(0.0, 25.0); + // Shown as Camera Raw shows them: Exposure to a hundredth of a stop, the others whole. + p.exposure = (p.exposure * 100.0).round() / 100.0; + for v in [&mut p.blacks, &mut p.whites, &mut p.shadows, &mut p.highlights, &mut p.contrast] { + *v = v.round(); + } +} + fn luma(c: [f32; 3]) -> f32 { 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2] } @@ -540,6 +634,10 @@ impl CameraRaw { fn grade_neutral(&self) -> bool { self.grade_shadows.neutral() && self.grade_midtones.neutral() && self.grade_highlights.neutral() && self.grade_global.neutral() } + /// The Calibration panel at rest. + fn calibration_neutral(&self) -> bool { + self.shadow_tint == 0.0 && self.calibration_hue.iter().chain(&self.calibration_sat).all(|v| *v == 0.0) + } fn curves_neutral(&self) -> bool { [self.curve_highlights, self.curve_lights, self.curve_darks, self.curve_shadows].iter().all(|v| *v == 0.0) && [&self.point_curve, &self.point_curve_red, &self.point_curve_green, &self.point_curve_blue].iter().all(|c| is_linear(c)) @@ -547,6 +645,7 @@ impl CameraRaw { /// True when every control is neutral (the filter is an identity). pub fn is_identity(&self) -> bool { self.wb_neutral() + && self.calibration_neutral() && self.tone_neutral() && self.dehaze == 0.0 && self.vibrance == 0.0 @@ -598,6 +697,24 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, float: bo } }); } + // 1b. Calibration: the primaries turned and purer or greyer, and the shadows tinted, in + // linear light (the camera's primaries are what Camera Raw's panel calibrates). + if !p.calibration_neutral() { + let primaries = p.calibration_hue.iter().chain(&p.calibration_sat).any(|v| *v != 0.0); + let tint = p.shadow_tint.clamp(-100.0, 100.0) / 100.0; + par_rows(px, w, 1, |_, row| { + for q in row.iter_mut() { + let c = [srgb_to_linear(q[0]), srgb_to_linear(q[1]), srgb_to_linear(q[2])]; + let mut o = if primaries { calibrate(c, p.calibration_hue, p.calibration_sat) } else { c }; + if tint != 0.0 { + o = shadow_tint(o, tint); + } + for k in 0..3 { + q[k] = linear_to_srgb(o[k].max(0.0)); + } + } + }); + } // 2. Dehaze. if p.dehaze != 0.0 { dehaze(px, w, h, p.dehaze / 100.0); @@ -1150,6 +1267,90 @@ mod tests { assert!(v[0][0] < 0.35 && (v[(h / 2) * w + w / 2][0] - 0.5).abs() < 0.01, "{:?}", v[0]); } + #[test] + fn calibration_turns_primaries_keeps_neutrals_and_tints_shadows() { + let w = calibration_weights(0.0); + assert!((w[0] - 1.0).abs() < 1e-6, "pure red is all red primary: {w:?}"); + let w = calibration_weights(60.0); + assert!((w[0] - 0.5).abs() < 1e-6 && (w[1] - 0.5).abs() < 1e-6, "yellow is half red, half green: {w:?}"); + let w = calibration_weights(300.0); + assert!((w[2] - 0.5).abs() < 1e-6 && (w[0] - 0.5).abs() < 1e-6, "magenta wraps round: {w:?}"); + let (none, zero) = ([0.0f32; 3], [0.0f32; 3]); + let grey = calibrate([0.3, 0.3, 0.3], [100.0, -100.0, 50.0], [100.0, -100.0, 100.0]); + assert!(grey.iter().all(|v| (v - 0.3).abs() < 1e-5), "greys are untouched: {grey:?}"); + // Red turned towards green: it gains green, keeps its luminance. + let red = calibrate([0.5, 0.0, 0.0], [100.0, 0.0, 0.0], zero); + assert!(red[1] > 0.05 && (red[1] / red[0] - 0.5).abs() < 0.02 && red[2] < 1e-6, "red turns 30° towards green (orange): {red:?}"); + assert!((luma(red) - luma([0.5, 0.0, 0.0])).abs() < 1e-4, "luminance kept: {red:?}"); + // Blue at saturation −100 is grey; green at −50 is paler. + let blue = calibrate([0.0, 0.0, 0.8], none, [0.0, 0.0, -100.0]); + assert!((blue[0] - blue[1]).abs() < 1e-5 && (blue[1] - blue[2]).abs() < 1e-5, "blue at −100 saturation is grey: {blue:?}"); + let green = calibrate([0.2, 0.8, 0.2], none, [0.0, -50.0, 0.0]); + assert!(green[0] > 0.2 && green[1] < 0.8, "green at −50 is paler: {green:?}"); + // A primary's sliders leave the other primaries alone. + let unchanged = calibrate([0.0, 0.0, 0.8], [100.0, 100.0, 0.0], [100.0, 100.0, 0.0]); + assert!(unchanged.iter().zip([0.0, 0.0, 0.8]).all(|(a, b)| (a - b).abs() < 1e-5), "{unchanged:?}"); + // Shadows tint: magenta lifts red and blue over green in a dark pixel, keeps luminance, + // and leaves white alone. + let dark = shadow_tint([0.02, 0.02, 0.02], 1.0); + assert!(dark[0] > dark[1] && dark[2] > dark[1], "{dark:?}"); + assert!((luma(dark) - 0.02).abs() < 1e-4, "luminance kept: {dark:?}"); + let green = shadow_tint([0.02, 0.02, 0.02], -1.0); + assert!(green[1] > green[0], "{green:?}"); + let white = shadow_tint([1.0, 1.0, 1.0], 1.0); + assert!(white.iter().all(|v| (v - 1.0).abs() < 1e-3), "white is not tinted: {white:?}"); + // Through develop: neutral settings are an identity, a tint changes dark pixels only. + let mut p = CameraRaw::default(); + assert!(p.is_identity()); + p.shadow_tint = 100.0; + assert!(!p.is_identity()); + let mut px = vec![[0.1, 0.1, 0.1, 1.0], [0.95, 0.95, 0.95, 1.0]]; + develop(&mut px, 2, 1, &p, false); + assert!(px[0][0] > px[0][1], "dark grey turns magenta: {:?}", px[0]); + assert!((px[1][0] - px[1][1]).abs() < 0.01, "near-white stays neutral: {:?}", px[1]); + p = CameraRaw::default(); + p.calibration_hue[2] = 100.0; + let mut px = vec![[0.0, 0.0, 0.8, 1.0]]; + develop(&mut px, 1, 1, &p, false); + assert!(px[0][0] > 0.05, "blue turned towards red: {:?}", px[0]); + } + + #[test] + fn auto_tone_brightens_dark_and_darkens_bright_images() { + let mut p = CameraRaw::default(); + auto_tone(&[], &mut p); + assert_eq!(p, CameraRaw::default(), "no pixels: nothing changes"); + let dark: Vec<[f32; 4]> = (0..4096) + .map(|i| { + let v = 0.05 + (i % 64) as f32 / 64.0 * 0.15; + [v, v, v, 1.0] + }) + .collect(); + auto_tone(&dark, &mut p); + assert!(p.exposure > 0.5, "a dark image gets exposure: {}", p.exposure); + assert!(p.shadows > 0.0, "and lifted shadows: {}", p.shadows); + let mut p = CameraRaw::default(); + let bright: Vec<[f32; 4]> = (0..4096) + .map(|i| { + let v = 0.8 + (i % 64) as f32 / 64.0 * 0.19; + [v, v, v, 1.0] + }) + .collect(); + auto_tone(&bright, &mut p); + assert!(p.exposure < -0.5, "a bright image loses exposure: {}", p.exposure); + assert!(p.highlights < 0.0, "and its highlights come down: {}", p.highlights); + let mut p = CameraRaw::default(); + let good: Vec<[f32; 4]> = (0..4096) + .map(|i| { + let v = 0.04 + (i % 64) as f32 / 63.0 * 0.92; + [v, v, v, 1.0] + }) + .collect(); + auto_tone(&good, &mut p); + assert!(p.exposure.abs() < 0.3 && p.blacks.abs() < 10.0 && p.whites.abs() < 10.0, "a full-range image is left nearly alone: {p:?}"); + assert!(p.saturation == 0.0 && p.hsl_neutral(), "other panels untouched"); + } + #[test] fn float_documents_keep_overrange() { let mut a = vec![[2.0f32, 1.5, 0.5, 1.0]; 16]; diff --git a/crates/engine/src/lens_cmds.rs b/crates/engine/src/lens_cmds.rs index 379ca2402aa..17742bd091e 100644 --- a/crates/engine/src/lens_cmds.rs +++ b/crates/engine/src/lens_cmds.rs @@ -463,7 +463,7 @@ pub fn specs() -> Vec { label: "Camera Raw Filter…", menu: &["Filter"], shortcut: Some("Cmd+Shift+A"), - params: r##"{"temperature":-100..100=0,"tint":-100..100=0,"exposure":-5..5=0,"contrast":-100..100=0,"highlights":-100..100=0,"shadows":-100..100=0,"whites":-100..100=0,"blacks":-100..100=0,"texture":-100..100=0,"clarity":-100..100=0,"dehaze":-100..100=0,"vibrance":-100..100=0,"saturation":-100..100=0,"curveHighlights":-100..100=0,"curveLights":-100..100=0,"curveDarks":-100..100=0,"curveShadows":-100..100=0,"curveSplits":[25,50,75],"pointCurve":[[in,out]],"pointCurveRed":[[in,out]],"pointCurveGreen":[[in,out]],"pointCurveBlue":[[in,out]],"hslHue":[8],"hslSat":[8],"hslLum":[8],"gradeShadows":{"hue":deg,"sat":0..100,"lum":-100..100},"gradeMidtones":{},"gradeHighlights":{},"gradeGlobal":{},"gradeBlending":0..100=50,"gradeBalance":-100..100=0,"sharpenAmount":0..150=0,"sharpenRadius":0.5..3=1,"sharpenDetail":0..100=25,"sharpenMasking":0..100=0,"noiseLuminance":0..100=0,"noiseLuminanceDetail":0..100=50,"noiseColor":0..100=0,"noiseColorDetail":0..100=50,"grainAmount":0..100=0,"grainSize":0..100=25,"grainRoughness":0..100=50,"vignetteAmount":-100..100=0,"vignetteMidpoint":0..100=50,"vignetteRoundness":-100..100=0,"vignetteFeather":0..100=50,"vignetteHighlights":0..100=0,"vignetteStyle":"highlightPriority|colorPriority|paintOverlay","seed":u32=0}"##, + params: r##"{"temperature":-100..100=0,"tint":-100..100=0,"exposure":-5..5=0,"contrast":-100..100=0,"highlights":-100..100=0,"shadows":-100..100=0,"whites":-100..100=0,"blacks":-100..100=0,"texture":-100..100=0,"clarity":-100..100=0,"dehaze":-100..100=0,"vibrance":-100..100=0,"saturation":-100..100=0,"curveHighlights":-100..100=0,"curveLights":-100..100=0,"curveDarks":-100..100=0,"curveShadows":-100..100=0,"curveSplits":[25,50,75],"pointCurve":[[in,out]],"pointCurveRed":[[in,out]],"pointCurveGreen":[[in,out]],"pointCurveBlue":[[in,out]],"hslHue":[8],"hslSat":[8],"hslLum":[8],"gradeShadows":{"hue":deg,"sat":0..100,"lum":-100..100},"gradeMidtones":{},"gradeHighlights":{},"gradeGlobal":{},"gradeBlending":0..100=50,"gradeBalance":-100..100=0,"shadowTint":-100..100=0,"calibrationHue":[red,green,blue] -100..100,"calibrationSat":[red,green,blue] -100..100 (the Calibration panel: Shadows tint and the primaries' hue and saturation),"sharpenAmount":0..150=0,"sharpenRadius":0.5..3=1,"sharpenDetail":0..100=25,"sharpenMasking":0..100=0,"noiseLuminance":0..100=0,"noiseLuminanceDetail":0..100=50,"noiseColor":0..100=0,"noiseColorDetail":0..100=50,"grainAmount":0..100=0,"grainSize":0..100=25,"grainRoughness":0..100=50,"vignetteAmount":-100..100=0,"vignetteMidpoint":0..100=50,"vignetteRoundness":-100..100=0,"vignetteFeather":0..100=50,"vignetteHighlights":0..100=0,"vignetteStyle":"highlightPriority|colorPriority|paintOverlay","seed":u32=0}"##, enabled: raw_enabled, run: camera_raw_cmd, journal: true, diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 378f71c18eb..1d0a7c36961 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -914,6 +914,35 @@ pub struct RawDefaults { /// Photoshop does; off develops it with the defaults straight away. Automation opens never /// show the dialog. pub open_in_camera_raw: bool, + /// Keep a raw file's develop settings in a sidecar (`IMG_0001.xmp` beside `IMG_0001.CR2`), + /// as Camera Raw's "Save image settings in: Sidecar .xmp files"; the sidecar is read again + /// when the file is next opened. Off reads sidecars but never writes one. + pub write_xmp_sidecars: bool, +} + +impl RawColorSpace { + /// The built-in profile `edit.convertToProfile` knows this space as. + pub fn profile_id(self) -> &'static str { + match self { + RawColorSpace::Srgb => "srgb", + RawColorSpace::AdobeRgb => "adobe-rgb-compat", + RawColorSpace::ProPhoto => "prophoto-compat", + RawColorSpace::DisplayP3 => "display-p3", + } + } +} + +impl RawSharpen { + /// Camera Raw's output sharpening for this medium as the Detail panel's (amount, radius): + /// none, Screen (light, fine), Matte paper (stronger, wider: ink spreads), Glossy paper. + pub fn preset(self) -> Option<(f32, f32)> { + match self { + RawSharpen::None => None, + RawSharpen::Screen => Some((25.0, 1.0)), + RawSharpen::Matte => Some((35.0, 1.2)), + RawSharpen::Glossy => Some((40.0, 1.0)), + } + } } impl Default for RawDefaults { @@ -926,6 +955,7 @@ impl Default for RawDefaults { open_as_smart_object: false, apply_auto_tone: false, open_in_camera_raw: true, + write_xmp_sidecars: true, } } } @@ -1067,12 +1097,6 @@ pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[ "type.recentFonts", "enhancedControls.scrubbySliderAcceleration", "enhancedControls.touchGestures", - "rawDefaults.colorSpace", - "rawDefaults.bitDepth", - "rawDefaults.resolution", - "rawDefaults.sharpenFor", - "rawDefaults.openAsSmartObject", - "rawDefaults.applyAutoTone", // Agent access is governed by the launch flags (`--control`, the automation roots), not // by these yet. "integrations.allowAgentControl", diff --git a/crates/io/src/camera_raw_xmp.rs b/crates/io/src/camera_raw_xmp.rs index 159e298a06b..80ec9e7ef0f 100644 --- a/crates/io/src/camera_raw_xmp.rs +++ b/crates/io/src/camera_raw_xmp.rs @@ -3,8 +3,9 @@ //! `x:xmpmeta/rdf:RDF/rdf:Description`, as attributes or as child elements. //! //! Loading applies only the settings the file holds, over the current ones, as Camera Raw's -//! Load Settings does; settings PhotoCraft has no control for (lens corrections, calibration, -//! geometry, defringe, …) are ignored and named in the report. Saving writes every supported +//! Load Settings does; settings PhotoCraft has no control for (lens corrections, geometry, +//! defringe, …) are ignored and named in the report. The same reader fills the dialog from a +//! raw file's sidecar (`IMG_0001.xmp` beside `IMG_0001.CR2`), and the writer keeps it. Saving writes every supported //! control, so loading the file in Photoshop reproduces the dialog. //! //! White balance: a Camera Raw Filter on a rendered image uses the relative @@ -100,6 +101,14 @@ const SCALARS: &[(&str, Field, f32, f32)] = &[ ("PostCropVignetteRoundness", |p| &mut p.vignette_roundness, -100.0, 100.0), ("PostCropVignetteFeather", |p| &mut p.vignette_feather, 0.0, 100.0), ("PostCropVignetteHighlightContrast", |p| &mut p.vignette_highlights, 0.0, 100.0), + // Calibration + ("ShadowTint", |p| &mut p.shadow_tint, -100.0, 100.0), + ("RedHue", |p| &mut p.calibration_hue[0], -100.0, 100.0), + ("RedSaturation", |p| &mut p.calibration_sat[0], -100.0, 100.0), + ("GreenHue", |p| &mut p.calibration_hue[1], -100.0, 100.0), + ("GreenSaturation", |p| &mut p.calibration_sat[1], -100.0, 100.0), + ("BlueHue", |p| &mut p.calibration_hue[2], -100.0, 100.0), + ("BlueSaturation", |p| &mut p.calibration_sat[2], -100.0, 100.0), ]; type Curve = fn(&mut CameraRaw) -> &mut Vec<[f32; 2]>; @@ -357,7 +366,8 @@ mod tests { assert_eq!(p.point_curve_red, vec![[0.0, 0.0], [128.0, 140.0], [255.0, 255.0]]); assert_eq!(p.dehaze, 12.0); // Lens vignetting, calibration and geometry have no counterpart. - assert_eq!(r.ignored, vec!["VignetteAmount".to_string(), "RedHue".to_string()]); + assert_eq!(r.ignored, vec!["VignetteAmount".to_string()], "the Calibration panel's keys load now"); + assert_eq!(p.calibration_hue[0], -5.0); } #[test] diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/camera_raw_ui.rs index 59ab86092d0..dd898b1c025 100644 --- a/crates/ui-egui/src/camera_raw_ui.rs +++ b/crates/ui-egui/src/camera_raw_ui.rs @@ -231,7 +231,32 @@ fn open_raw(app: &mut PhotocraftApp, ctx: &egui::Context, raw: RawOpen) -> Resul let index = document_index(app, raw.document).ok_or("the raw document was closed")?; app.session.set_active(index); let (layer, surf, _) = crate::distort_ui::active_pixels(app)?; - open_pixels(app, ctx, layer, surf, CameraRaw::default(), Coverage::None, Target::OpenRaw)?; + // The file's sidecar (`IMG_0001.xmp` beside it) fills the dialog, as Camera Raw's does; the + // status bar names what it could not apply. + let mut params = CameraRaw::default(); + let mut from_sidecar = false; + if let Some((loaded, report, file)) = raw.path.as_deref().and_then(read_sidecar) { + params = loaded; + from_sidecar = true; + app.ui.status = if report.ignored.is_empty() { + crate::i18n::fmt(tl!("Settings from {name}"), &[("name", &file)]) + } else { + crate::i18n::fmt( + tl!("Settings from {name}; {count} not supported: {names}"), + &[("name", &file), ("count", &report.ignored.len().to_string()), ("names", &report.ignored.join(", "))], + ) + }; + app.ui.status_error = false; + } + open_pixels(app, ctx, layer, surf, params, Coverage::None, Target::OpenRaw)?; + // Camera Raw Defaults › Apply auto tone: a file without its own settings opens with Auto. + if !from_sidecar + && app.session.prefs().raw_defaults.apply_auto_tone + && let Some(d) = app.camera_raw.as_mut() + { + photocraft_algo::camera_raw::auto_tone(&d.proxy, &mut d.params); + d.dirty = true; + } let curve = match (&raw.bytes, &raw.path) { (Some(b), _) => Some(photocraft_io::raw::tone_curve(b)), #[cfg(not(target_arch = "wasm32"))] @@ -292,6 +317,7 @@ fn raw_stage(p: &CameraRaw) -> photocraft_io::raw::Tone { /// (tests, the web) it runs inline. fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen) -> Result { let index = document_index(app, raw.document).ok_or("the raw document was closed")?; + write_sidecar(app, raw, params); let tuning = photocraft_io::raw::RawTuning { temperature: params.temperature, tint: params.tint, @@ -398,10 +424,14 @@ fn finish_redevelop(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen, /// The other settings as one Camera Raw step on document `index`, then the document is marked /// unmodified (developing is part of opening). The step runs like any filter (in the /// background in the desktop app); the document is marked unmodified when it lands. -fn finish_open_raw(app: &mut PhotocraftApp, index: usize, rest: CameraRaw, redeveloped: Option, raw: Option<&RawOpen>) -> Result { +fn finish_open_raw(app: &mut PhotocraftApp, index: usize, mut rest: CameraRaw, redeveloped: Option, raw: Option<&RawOpen>) -> Result { app.session.set_active(index); app.sync_views(); let mut result = json!({"document": index, "redeveloped": redeveloped.unwrap_or(false)}); + let defaults = apply_raw_defaults(app, index, &mut rest)?; + if !defaults.is_empty() { + result["defaults"] = json!(defaults); + } if !rest.is_identity() { let layer = app.session.active().and_then(|st| st.active_layer).ok_or("no layer to develop")?; let mut p = non_defaults(&rest); @@ -418,6 +448,151 @@ fn finish_open_raw(app: &mut PhotocraftApp, index: usize, rest: CameraRaw, redev Ok(result) } +/// The sidecar beside a raw file: `IMG_0001.xmp` for `IMG_0001.CR2`, as Camera Raw names it. +pub fn sidecar_path(path: &str) -> String { + match path.rsplit_once('.') { + Some((stem, ext)) if !ext.contains(['/', '\\']) => format!("{stem}.xmp"), + _ => format!("{path}.xmp"), + } +} + +/// A DNG carries its settings inside the file in Camera Raw; a sidecar is read for one too, +/// but never written beside it. +fn is_dng(path: &str) -> bool { + path.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("dng")) +} + +/// The settings of the sidecar beside `path`, when there is one that parses: the settings, what +/// the loader skipped, and the sidecar's file name. A sidecar that doesn't parse is ignored (the +/// raw still opens) and reported in the log. +#[cfg(not(target_arch = "wasm32"))] +fn read_sidecar(path: &str) -> Option<(CameraRaw, photocraft_io::camera_raw_xmp::LoadReport, String)> { + let sidecar = sidecar_path(path); + let bytes = std::fs::read(&sidecar).ok()?; + if bytes.len() > photocraft_io::camera_raw_xmp::MAX_XMP_BYTES { + log::warn!("{sidecar}: sidecar larger than {} bytes, ignored", photocraft_io::camera_raw_xmp::MAX_XMP_BYTES); + return None; + } + let mut params = CameraRaw::default(); + match photocraft_io::camera_raw_xmp::load(&mut params, &bytes) { + Ok(report) => Some((params, report, crate::file_open::display_name(&sidecar))), + Err(e) => { + log::warn!("{sidecar}: sidecar ignored: {e}"); + None + } + } +} +#[cfg(target_arch = "wasm32")] +fn read_sidecar(_: &str) -> Option<(CameraRaw, photocraft_io::camera_raw_xmp::LoadReport, String)> { + None +} + +/// Keep the develop settings beside the raw file (Camera Raw Defaults › Write xmp sidecars): +/// written when the settings aren't the defaults or a sidecar already exists, so a file reopens +/// as it was developed. Not for DNGs, and never fatal: a folder that can't be written to is +/// reported in the status bar. +fn write_sidecar(app: &mut PhotocraftApp, raw: &RawOpen, params: &CameraRaw) { + if !app.session.prefs().raw_defaults.write_xmp_sidecars { + return; + } + let Some(path) = raw.path.as_deref().filter(|p| !is_dng(p)) else { return }; + let sidecar = sidecar_path(path); + #[cfg(not(target_arch = "wasm32"))] + let exists = std::path::Path::new(&sidecar).exists(); + #[cfg(target_arch = "wasm32")] + let exists = false; + if params.is_identity() && !exists { + return; + } + let bytes = photocraft_io::camera_raw_xmp::save(params).into_bytes(); + let Some(write) = app.services.write.as_mut() else { return }; + if let Err(e) = write(&sidecar, &bytes) { + app.ui.status = crate::i18n::fmt(tl!("Could not write {name}: {error}"), &[("name", &crate::file_open::display_name(&sidecar)), ("error", &e)]); + app.ui.status_error = true; + } +} + +/// Camera Raw Defaults (Preferences): the colour space, bit depth and resolution the developed +/// document opens in, output sharpening (folded into the Camera Raw step `rest`, as the +/// workflow's Sharpen For is), and Open as Smart Object. Returns what it applied. +fn apply_raw_defaults(app: &mut PhotocraftApp, index: usize, rest: &mut CameraRaw) -> Result, String> { + use photocraft_engine::prefs::{RawColorSpace, RawDepth}; + let d = app.session.prefs().raw_defaults.clone(); + app.session.set_active(index); + let mut applied = Vec::new(); + let profile = d.color_space.profile_id(); + // Raws develop into ProPhoto-compatible RGB (`photocraft_io::raw`); the other spaces are a + // conversion. + if profile != RawColorSpace::ProPhoto.profile_id() { + app.session.execute("edit.convertToProfile", json!({"profile": profile, "intent": "relative"})).map_err(|e| e.to_string())?; + applied.push("colorSpace"); + } + if d.bit_depth == RawDepth::Eight { + app.session.execute("image.mode.bits8", json!({})).map_err(|e| e.to_string())?; + applied.push("bitDepth"); + } + let dpi = app.session.active().map(|st| st.doc.resolution_dpi).unwrap_or(72.0); + if d.resolution.is_finite() && d.resolution > 0.0 && (f64::from(dpi) - d.resolution).abs() > 1e-6 { + app.session.execute("image.imageSize", json!({"resolution": d.resolution})).map_err(|e| e.to_string())?; + applied.push("resolution"); + } + if let Some((amount, radius)) = d.sharpen_for.preset() + && rest.sharpen_amount == 0.0 + { + rest.sharpen_amount = amount; + rest.sharpen_radius = radius; + applied.push("sharpenFor"); + } + if d.open_as_smart_object { + app.session.execute("layer.smartObjects.convertToSmartObject", json!({})).map_err(|e| e.to_string())?; + applied.push("openAsSmartObject"); + } + Ok(applied) +} + +/// A raw that opened without the dialog (Camera Raw Defaults › Open in Camera Raw off): its +/// sidecar's settings develop it as the dialog's Open would, and the Camera Raw Defaults apply. +/// `warnings` are the import's; only a developed raw qualifies. +pub fn opened_without_dialog(app: &mut PhotocraftApp, index: usize, name: &str, path: Option<&str>, warnings: &[String]) { + if !warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)) { + return; + } + let Some(document) = app.session.documents().get(index).map(|st| st.doc.id) else { return }; + let raw = RawOpen { document, name: name.to_string(), path: path.map(str::to_string), bytes: None }; + let mut params = CameraRaw::default(); + if let Some((loaded, _, _)) = path.and_then(read_sidecar) { + params = loaded; + } else if app.session.prefs().raw_defaults.apply_auto_tone + && let Some(px) = app.session.active().and_then(|st| st.doc.layer(st.active_layer?)).and_then(|l| l.surface()).map(|s| sample_pixels(s, 512)) + { + photocraft_algo::camera_raw::auto_tone(&px, &mut params); + } + let r = if params.is_identity() { finish_open_raw(app, index, params, None, Some(&raw)) } else { commit_open_raw(app, ¶ms, &raw) }; + if let Err(e) = r { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// Every k-th pixel of a surface's content, k chosen so the longer side has about `max_side` +/// samples: enough for a histogram (Auto tone) without reading a whole raw. +fn sample_pixels(surf: &photocraft_raster::Surface, max_side: usize) -> Vec<[f32; 4]> { + let area = surf.content_bounds(); + let (w, h) = (area.x1.saturating_sub(area.x0).max(0) as usize, area.y1.saturating_sub(area.y0).max(0) as usize); + if w == 0 || h == 0 { + return Vec::new(); + } + let k = w.max(h).div_ceil(max_side.max(1)).max(1); + let mut out = Vec::with_capacity(w.div_ceil(k) * h.div_ceil(k)); + let mut row = vec![[0.0f32; 4]; w]; + for y in (0..h).step_by(k) { + let yy = area.y0.saturating_add(y as i32); + surf.read_rgba_into(Rect::new(area.x0, yy, area.x1, yy.saturating_add(1)), &mut row); + out.extend(row.iter().step_by(k).copied()); + } + out +} + fn mark_unmodified(app: &mut PhotocraftApp, index: usize) { let active = app.session.active_index(); app.session.set_active(index); @@ -676,8 +851,8 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val for (key, value) in fields { match key.as_str() { "set" | "scope" | "view" => {} - "before" | "commit" | "cancel" | "saveSettings" | "loadSettings" if value.is_boolean() => {} - "before" | "commit" | "cancel" | "saveSettings" | "loadSettings" => return Some(Err(format!("Camera Raw {key} must be a boolean"))), + "before" | "commit" | "cancel" | "saveSettings" | "loadSettings" | "auto" if value.is_boolean() => {} + "before" | "commit" | "cancel" | "saveSettings" | "loadSettings" | "auto" => return Some(Err(format!("Camera Raw {key} must be a boolean"))), _ => return Some(Err(format!("unknown Camera Raw ui property {key}"))), } } @@ -712,6 +887,10 @@ fn menu_update(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &Value) -> Opti // occurs until every part of the request has passed validation. let d = app.camera_raw.as_ref()?; let mut next_params = d.params.clone(); + // Auto (the Light panel's button): the tone sliders from the image's histogram. + if ui.get("auto").and_then(Value::as_bool) == Some(true) { + photocraft_algo::camera_raw::auto_tone(&d.proxy, &mut next_params); + } if let Some(set) = ui.get("set") { if !set.is_object() { return Some(Err("bad Camera Raw settings: expected an object".into())); @@ -1073,9 +1252,16 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) { egui::ScrollArea::vertical().id_salt("camera-raw-props").show(&mut props, |ui| { ui.spacing_mut().item_spacing.y = 4.0; let p = &mut d.params; + let proxy = &d.proxy; let alt = &mut d.scope.alt_tone; let (ts, tn) = (temp_stops(), tint_stops()); section(ui, "Light", true, |ui| { + // Auto: Camera Raw's one-click tone from the histogram; the sliders show what it + // chose, so each can be adjusted afterwards. + if ui.button(tl!("Auto")).on_hover_text(tl!("Set the tone sliders from the image")).clicked() { + photocraft_algo::camera_raw::auto_tone(proxy, p); + dirty = true; + } tone_row(ui, &mut dirty, alt, ToneZone::Exposure, &mut p.exposure); row(ui, &mut dirty, "Contrast", &mut p.contrast, -100.0..=100.0, None); tone_row(ui, &mut dirty, alt, ToneZone::Highlights, &mut p.highlights); @@ -1170,6 +1356,19 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) { row(ui, &mut dirty, "Color", &mut p.noise_color, 0.0..=100.0, None); row(ui, &mut dirty, "Color Detail", &mut p.noise_color_detail, 0.0..=100.0, None); }); + // Camera Raw's Calibration panel: a tint for the shadows and each primary's hue and + // saturation (Process Version is implied: 2012 and later). + section(ui, "Calibration", false, |ui| { + widgets::section_label(ui, tl!("Shadows")); + row(ui, &mut dirty, "Tint", &mut p.shadow_tint, -100.0..=100.0, Some(&tn)); + for (i, name) in ["Red Primary", "Green Primary", "Blue Primary"].iter().enumerate() { + widgets::section_label(ui, crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", name)); + ui.push_id(name, |ui| { + row(ui, &mut dirty, "Hue", &mut p.calibration_hue[i], -100.0..=100.0, None); + row(ui, &mut dirty, "Saturation", &mut p.calibration_sat[i], -100.0..=100.0, None); + }); + } + }); }); super::camera_raw_scope_ui::floating(ctx, d, scope, right); super::camera_raw_scope_ui::shortcuts(ctx, scope); @@ -1420,7 +1619,11 @@ mod tests { let (w, h) = (48, 32); let mut spec = DngSpec::cfa(w, h, mosaic(&scene(w, h), w, [0, 1, 1, 2], 0, 30000)); spec.as_shot_neutral = Some([0.5, 1.0, 0.7]); - (PhotocraftApp::new(photocraft_engine::Session::new(), services), spec.build()) + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + // The pixel comparisons below read the developed ProPhoto values: no conversion on open + // (Camera Raw Defaults › Color space is Adobe RGB otherwise). + app.run("prefs.set", json!({"path": "rawDefaults.colorSpace", "value": "proPhoto"})).unwrap(); + (app, spec.build()) } fn mean_red(app: &PhotocraftApp) -> f32 { @@ -1547,7 +1750,8 @@ mod tests { let raw = app.pending_raw_open.take().unwrap(); open_raw(&mut app, &ctx, raw).unwrap(); let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert_eq!(r, json!({"document": 0, "redeveloped": false})); + assert_eq!((r["document"].as_u64(), r["redeveloped"].as_bool(), r.get("filter")), (Some(0), Some(false), None), "{r}"); + assert_eq!(r["defaults"], json!(["resolution"]), "Camera Raw Defaults: 300 ppi, from the develop's 72: {r}"); // Preference off: raws open straight away. app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); app.open_bytes("c.dng", &dng).unwrap(); @@ -1556,6 +1760,151 @@ mod tests { assert!(open_raw(&mut app, &ctx, RawOpen { document: photocraft_doc::DocId(u64::MAX), name: "x".into(), path: None, bytes: None }).is_err()); } + #[test] + fn calibration_changes_the_preview_and_round_trips_through_xmp() { + let (mut app, dng) = raw_app(); + let ctx = egui::Context::default(); + app.open_bytes("IMG_0005.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + let before = app.camera_raw.as_ref().unwrap().processed.clone(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"shadowTint": 100, "calibrationHue": [100, 0, 0], "calibrationSat": [0, 0, -100]}}})) + .unwrap() + .unwrap(); + let d = app.camera_raw.as_mut().unwrap(); + d.render(&ctx); + assert!( + d.processed.iter().zip(&before).any(|(a, b)| (a[0] - b[0]).abs() > 0.01 || (a[1] - b[1]).abs() > 0.01), + "the Calibration panel changes the preview" + ); + let xmp = photocraft_io::camera_raw_xmp::save(&d.params); + assert!(xmp.contains("crs:ShadowTint=\"+100\"") && xmp.contains("crs:RedHue=\"+100\"") && xmp.contains("crs:BlueSaturation=\"-100\""), "{xmp}"); + let mut back = CameraRaw::default(); + photocraft_io::camera_raw_xmp::load(&mut back, xmp.as_bytes()).unwrap(); + assert_eq!((back.shadow_tint, back.calibration_hue, back.calibration_sat), (100.0, [100.0, 0.0, 0.0], [0.0, 0.0, -100.0])); + assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"auto": "yes"}})).unwrap().is_err(), "auto must be a boolean"); + } + + #[test] + fn auto_sets_the_light_sliders_from_the_image() { + let (mut app, dng) = raw_app(); + let ctx = egui::Context::default(); + app.open_bytes("IMG_0006.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + assert!(app.camera_raw.as_ref().unwrap().params.is_identity()); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"auto": true}})).unwrap().unwrap(); + let p = app.camera_raw.as_ref().unwrap().params.clone(); + assert!(!p.is_identity(), "Auto chose something: {p:?}"); + assert!(p.saturation == 0.0 && p.hsl_hue == [0.0; 8], "only the Light panel: {p:?}"); + // The preference does the same when a raw opens without a sidecar. + app.run("prefs.set", json!({"path": "rawDefaults.applyAutoTone", "value": true})).unwrap(); + app.open_bytes("IMG_0007.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + assert_eq!(app.camera_raw.as_ref().unwrap().params, p, "Apply auto tone opens the dialog with Auto's settings"); + } + + #[test] + fn a_sidecar_fills_the_dialog_and_open_writes_it_back() { + use std::sync::{Arc, Mutex}; + let (mut app, dng) = raw_app(); + let dir = std::env::temp_dir().join(format!("photocraft-sidecar-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let raw_path = dir.join("IMG_0008.cr2").to_string_lossy().into_owned(); + std::fs::write(&raw_path, &dng).unwrap(); + assert_eq!(sidecar_path(&raw_path), dir.join("IMG_0008.xmp").to_string_lossy()); + assert_eq!(sidecar_path("/a/b.c/noext"), "/a/b.c/noext.xmp"); + std::fs::write( + sidecar_path(&raw_path), + "", + ) + .unwrap(); + type Written = Arc)>>>; + let written: Written = Arc::default(); + let sink = written.clone(); + app.services.write = Some(Box::new(move |p: &str, b: &[u8]| { + sink.lock().unwrap().push((p.to_string(), b.to_vec())); + Ok(()) + })); + let ctx = egui::Context::default(); + app.open_bytes("IMG_0008.cr2", &dng).unwrap(); + let mut raw = app.pending_raw_open.take().unwrap(); + raw.path = Some(raw_path.clone()); + open_raw(&mut app, &ctx, raw).unwrap(); + let d = app.camera_raw.as_ref().unwrap(); + assert_eq!((d.params.exposure, d.params.shadow_tint), (1.5, 20.0), "the sidecar fills the dialog"); + assert!( + app.ui.status.contains("IMG_0008.xmp") && app.ui.status.contains("Temperature"), + "the absolute white balance is reported as not supported: {}", + app.ui.status + ); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}}})).unwrap().unwrap(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + let w = written.lock().unwrap().clone(); + assert_eq!(w.len(), 1, "Open writes the sidecar once: {:?}", w.iter().map(|(p, _)| p).collect::>()); + assert_eq!(w[0].0, sidecar_path(&raw_path)); + let text = String::from_utf8(w[0].1.clone()).unwrap(); + assert!(text.contains("crs:Exposure2012=\"+1.50\"") && text.contains("crs:Contrast2012=\"+15\"") && text.contains("crs:ShadowTint=\"+20\""), "{text}"); + // A DNG keeps its settings inside: no sidecar beside it. And the preference turns writing off. + written.lock().unwrap().clear(); + let dng_path = dir.join("IMG_0009.dng").to_string_lossy().into_owned(); + std::fs::write(&dng_path, &dng).unwrap(); + app.open_bytes("IMG_0009.dng", &dng).unwrap(); + let mut raw = app.pending_raw_open.take().unwrap(); + raw.path = Some(dng_path); + open_raw(&mut app, &ctx, raw).unwrap(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}, "commit": true}})).unwrap().unwrap(); + assert!(written.lock().unwrap().is_empty(), "no sidecar for a DNG"); + app.run("prefs.set", json!({"path": "rawDefaults.writeXmpSidecars", "value": false})).unwrap(); + app.open_bytes("IMG_0008.cr2", &dng).unwrap(); + let mut raw = app.pending_raw_open.take().unwrap(); + raw.path = Some(raw_path.clone()); + open_raw(&mut app, &ctx, raw).unwrap(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 30}, "commit": true}})).unwrap().unwrap(); + assert!(written.lock().unwrap().is_empty(), "the preference stops the write"); + // Without the dialog, the sidecar still develops the file. + app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); + let before = app.session.documents().len(); + app.open_file(&raw_path, &dng).unwrap(); + assert!(app.pending_raw_open.is_none()); + assert_eq!(app.session.documents().len(), before + 1); + let st = app.session.active().unwrap(); + assert_eq!(st.saved_revision, st.revision, "opening with a sidecar leaves the document unmodified"); + assert!(mean_red(&app) > 0.0); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn camera_raw_defaults_apply_when_a_raw_opens() { + let (mut app, dng) = raw_app(); + app.run("prefs.set", json!({"values": {"rawDefaults.openInCameraRaw": false, "rawDefaults.colorSpace": "srgb", "rawDefaults.bitDepth": "8", "rawDefaults.resolution": 240.0, "rawDefaults.sharpenFor": "screen", "rawDefaults.openAsSmartObject": true}})).unwrap(); + app.open_bytes("IMG_0010.dng", &dng).unwrap(); + assert!(app.pending_raw_open.is_none()); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.depth, photocraft_color::SampleType::U8, "Bit depth 8"); + assert_eq!(st.doc.resolution_dpi, 240.0, "Resolution"); + let profile = st.doc.icc_profile.as_deref().and_then(|p| photocraft_cms::Profile::parse(p).ok()).map(|p| p.description).unwrap_or_default(); + assert!(profile.to_lowercase().contains("srgb"), "Color space: {profile}"); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert!(matches!(layer.content, photocraft_doc::LayerContent::Smart(_)), "Open as Smart Object"); + assert_eq!(st.saved_revision, st.revision, "the defaults are part of opening: unmodified"); + // The dialog's Open applies them too, and reports what it applied. + app.run("prefs.set", json!({"values": {"rawDefaults.openInCameraRaw": true, "rawDefaults.openAsSmartObject": false, "rawDefaults.bitDepth": "16"}})) + .unwrap(); + let ctx = egui::Context::default(); + app.open_bytes("IMG_0011.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(r["defaults"], json!(["colorSpace", "resolution", "sharpenFor"]), "{r}"); + assert!(r.get("filter").is_some(), "Sharpen For is a Camera Raw step: {r}"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.depth, photocraft_color::SampleType::U16); + assert_eq!(st.saved_revision, st.revision); + } + #[test] fn save_and_load_settings_round_trip_through_xmp_files() { use crate::file_dialog::FileDialogAnswer; @@ -1564,7 +1913,7 @@ mod tests { let written: Written = Arc::default(); let w = written.clone(); let foreign = br#" - + "#; let answers = vec![ Some(FileDialogAnswer::SaveTo("/out/Look.xmp".into())), diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index cea55a1694d..b1aa44a4c66 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3734,3 +3734,13 @@ navigator Zoom Zvětšení @plural {n} action|{n} actions {n} akce|{n} akce|{n} akcí Auto Add/Delete Automaticky přidat/odstranit ICO is limited to 256 × 256 pixels ICO je omezen na 256 × 256 pixelů + Calibration Kalibrace + Red Primary Červená základní + Green Primary Zelená základní + Blue Primary Modrá základní + Write xmp sidecars Zapisovat přidružené soubory XMP + Set the tone sliders from the image Nastavit posuvníky tónů podle obrazu + Settings from {name} Nastavení z {name} + Settings from {name}; {count} not supported: {names} Nastavení z {name}; {count} nepodporováno: {names} + Could not write {name}: {error} Nelze zapsat {name}: {error} + Shadow Tint Odstín stínů diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index b23510e12e5..e7c43129b89 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2768,3 +2768,13 @@ curves Smooth Glätten @plural {n} action|{n} actions {n} Aktion|{n} Aktionen Auto Add/Delete Autom. hinzuf./löschen ICO is limited to 256 × 256 pixels ICO ist auf 256 × 256 Pixel begrenzt + Calibration Kalibrierung + Red Primary Rot-Primärfarbe + Green Primary Grün-Primärfarbe + Blue Primary Blau-Primärfarbe + Write xmp sidecars XMP-Filialdateien schreiben + Set the tone sliders from the image Tonwert-Regler aus dem Bild setzen + Settings from {name} Einstellungen aus {name} + Settings from {name}; {count} not supported: {names} Einstellungen aus {name}; {count} nicht unterstützt: {names} + Could not write {name}: {error} {name} konnte nicht geschrieben werden: {error} + Shadow Tint Schattentönung diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1dd9ba36522..3eec523a211 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3823,3 +3823,13 @@ curves Smooth Εξομάλυνση @plural {n} action|{n} actions {n} ενέργεια|{n} ενέργειες Auto Add/Delete Αυτόματη προσθήκη/διαγραφή ICO is limited to 256 × 256 pixels Το ICO περιορίζεται σε 256 × 256 εικονοστοιχεία + Calibration Βαθμονόμηση + Red Primary Κόκκινο πρωτεύον + Green Primary Πράσινο πρωτεύον + Blue Primary Μπλε πρωτεύον + Write xmp sidecars Εγγραφή συνοδευτικών αρχείων XMP + Set the tone sliders from the image Ορισμός των ρυθμιστικών τόνων από την εικόνα + Settings from {name} Ρυθμίσεις από {name} + Settings from {name}; {count} not supported: {names} Ρυθμίσεις από {name}· {count} δεν υποστηρίζονται: {names} + Could not write {name}: {error} Αδυναμία εγγραφής του {name}: {error} + Shadow Tint Χροιά σκιών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5d1ff71146a..64884faa467 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2809,3 +2809,13 @@ curves Smooth Suavizar @plural {n} action|{n} actions {n} acción|{n} acciones Auto Add/Delete Añadir/eliminar automáticamente ICO is limited to 256 × 256 pixels ICO está limitado a 256 × 256 píxeles + Calibration Calibración + Red Primary Primario rojo + Green Primary Primario verde + Blue Primary Primario azul + Write xmp sidecars Escribir archivos XMP auxiliares + Set the tone sliders from the image Ajustar los controles de tono a partir de la imagen + Settings from {name} Ajustes de {name} + Settings from {name}; {count} not supported: {names} Ajustes de {name}; {count} no compatibles: {names} + Could not write {name}: {error} No se pudo escribir {name}: {error} + Shadow Tint Tinte de sombras diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6974616118f..e0803628ab4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3127,3 +3127,13 @@ curves Smooth Lisser @plural {n} action|{n} actions {n} action|{n} actions Auto Add/Delete Ajout/suppr. auto ICO is limited to 256 × 256 pixels Le format ICO est limité à 256 × 256 pixels + Calibration Étalonnage + Red Primary Primaire rouge + Green Primary Primaire verte + Blue Primary Primaire bleue + Write xmp sidecars Écrire les fichiers annexes XMP + Set the tone sliders from the image Régler les curseurs de tonalité d’après l’image + Settings from {name} Réglages de {name} + Settings from {name}; {count} not supported: {names} Réglages de {name} ; {count} non pris en charge : {names} + Could not write {name}: {error} Impossible d’écrire {name} : {error} + Shadow Tint Teinte des ombres diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9aa29a7cb68..d7487f47bae 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4047,3 +4047,13 @@ cameraRaw Yellow Sárga Color Indicates: A szín jelzése: Ink Characteristics Festék jellemzői Solidity: Fedőképesség: + Calibration Kalibrálás + Red Primary Vörös alapszín + Green Primary Zöld alapszín + Blue Primary Kék alapszín + Write xmp sidecars XMP kísérőfájlok írása + Set the tone sliders from the image Tónuscsúszkák beállítása a kép alapján + Settings from {name} Beállítások innen: {name} + Settings from {name}; {count} not supported: {names} Beállítások innen: {name}; {count} nem támogatott: {names} + Could not write {name}: {error} Nem sikerült írni: {name}: {error} + Shadow Tint Árnyék színezet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8182765c4ac..e6f1dec68d9 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3114,3 +3114,13 @@ curves Smooth Haluskan @plural {n} action|{n} actions {n} tindakan Auto Add/Delete Tambah/Hapus Otomatis ICO is limited to 256 × 256 pixels ICO dibatasi hingga 256 × 256 piksel + Calibration Kalibrasi + Red Primary Primer merah + Green Primary Primer hijau + Blue Primary Primer biru + Write xmp sidecars Tulis berkas pendamping XMP + Set the tone sliders from the image Atur penggeser nada dari gambar + Settings from {name} Pengaturan dari {name} + Settings from {name}; {count} not supported: {names} Pengaturan dari {name}; {count} tidak didukung: {names} + Could not write {name}: {error} Tidak dapat menulis {name}: {error} + Shadow Tint Rona bayangan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08d8adcc14f..fa86da7bfc9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4090,3 +4090,13 @@ navigator Zoom Zoom @plural {n} action|{n} actions {n} azione|{n} azioni Auto Add/Delete Aggiungi/elimina automaticamente ICO is limited to 256 × 256 pixels ICO è limitato a 256 × 256 pixel + Calibration Calibrazione + Red Primary Primario rosso + Green Primary Primario verde + Blue Primary Primario blu + Write xmp sidecars Scrivi file sidecar XMP + Set the tone sliders from the image Imposta i cursori dei toni dall’immagine + Settings from {name} Impostazioni da {name} + Settings from {name}; {count} not supported: {names} Impostazioni da {name}; {count} non supportate: {names} + Could not write {name}: {error} Impossibile scrivere {name}: {error} + Shadow Tint Tinta ombre diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 8e878c2c219..920756580e3 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3803,3 +3803,13 @@ curves Smooth スムーズ Reset All Locked Settings ロックされた設定をすべて初期化 Copy Texture to Other Tools テクスチャを他のツールにコピー ICO is limited to 256 × 256 pixels ICO は 256 × 256 ピクセルまでです + Calibration キャリブレーション + Red Primary レッド原色 + Green Primary グリーン原色 + Blue Primary ブルー原色 + Write xmp sidecars XMP サイドカーファイルを書き込む + Set the tone sliders from the image 画像からトーンスライダーを設定 + Settings from {name} {name} の設定 + Settings from {name}; {count} not supported: {names} {name} の設定; {count} 件は未対応: {names} + Could not write {name}: {error} {name} を書き込めません: {error} + Shadow Tint シャドウの色かぶり補正 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b7fe66cbb5b..260eb2b9eae 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3299,3 +3299,13 @@ curves Smooth 매끄럽게 @plural {n} action|{n} actions 액션 {n}개 Auto Add/Delete 자동 추가/삭제 ICO is limited to 256 × 256 pixels ICO는 256 × 256픽셀로 제한됩니다 + Calibration 보정 + Red Primary 빨강 원색 + Green Primary 녹색 원색 + Blue Primary 파랑 원색 + Write xmp sidecars XMP 사이드카 파일 쓰기 + Set the tone sliders from the image 이미지에서 톤 슬라이더 설정 + Settings from {name} {name}의 설정 + Settings from {name}; {count} not supported: {names} {name}의 설정; {count}개 미지원: {names} + Could not write {name}: {error} {name}을(를) 쓸 수 없음: {error} + Shadow Tint 그림자 색조 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 9ffc6e89b80..776d3600d03 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3885,3 +3885,13 @@ curves Smooth Vloeiend maken @plural {n} action|{n} actions {n} handeling|{n} handelingen Auto Add/Delete Automatisch toevoegen/verwijderen ICO is limited to 256 × 256 pixels ICO is beperkt tot 256 × 256 pixels + Calibration Kalibratie + Red Primary Primair rood + Green Primary Primair groen + Blue Primary Primair blauw + Write xmp sidecars XMP-sidecarbestanden schrijven + Set the tone sliders from the image Toonschuifregelaars instellen op basis van de afbeelding + Settings from {name} Instellingen uit {name} + Settings from {name}; {count} not supported: {names} Instellingen uit {name}; {count} niet ondersteund: {names} + Could not write {name}: {error} Kan {name} niet schrijven: {error} + Shadow Tint Schaduwtint diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 4601e90270b..be7942739c3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3723,3 +3723,13 @@ curves Smooth Wygładź @plural {n} action|{n} actions {n} operacja|{n} operacje|{n} operacji Auto Add/Delete Automatyczne dodawanie/usuwanie ICO is limited to 256 × 256 pixels ICO jest ograniczony do 256 × 256 pikseli + Calibration Kalibracja + Red Primary Czerwień podstawowa + Green Primary Zieleń podstawowa + Blue Primary Niebieski podstawowy + Write xmp sidecars Zapisuj pliki poboczne XMP + Set the tone sliders from the image Ustaw suwaki tonów na podstawie obrazu + Settings from {name} Ustawienia z {name} + Settings from {name}; {count} not supported: {names} Ustawienia z {name}; nieobsługiwane: {count}: {names} + Could not write {name}: {error} Nie można zapisać {name}: {error} + Shadow Tint Tinta cieni diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 21ce2174637..aa9610d556d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3915,3 +3915,13 @@ layerLabel No Color Sem cor @plural {n} action|{n} actions {n} ação|{n} ações Auto Add/Delete Adicionar/excluir automaticamente ICO is limited to 256 × 256 pixels ICO é limitado a 256 × 256 pixels + Calibration Calibração + Red Primary Primária vermelha + Green Primary Primária verde + Blue Primary Primária azul + Write xmp sidecars Gravar arquivos auxiliares XMP + Set the tone sliders from the image Definir os controles de tom a partir da imagem + Settings from {name} Configurações de {name} + Settings from {name}; {count} not supported: {names} Configurações de {name}; {count} sem suporte: {names} + Could not write {name}: {error} Não foi possível gravar {name}: {error} + Shadow Tint Matiz das sombras diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca950c2e05a..5d0e98f662d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3071,3 +3071,13 @@ curves Smooth Сгладить @plural {n} action|{n} actions {n} операция|{n} операции|{n} операций Auto Add/Delete Автодобавление/удаление ICO is limited to 256 × 256 pixels ICO ограничен размером 256 × 256 пикселей + Calibration Калибровка + Red Primary Красный основной + Green Primary Зелёный основной + Blue Primary Синий основной + Write xmp sidecars Записывать сопутствующие файлы XMP + Set the tone sliders from the image Установить ползунки тона по изображению + Settings from {name} Настройки из {name} + Settings from {name}; {count} not supported: {names} Настройки из {name}; не поддерживается: {count}: {names} + Could not write {name}: {error} Не удалось записать {name}: {error} + Shadow Tint Оттенок теней diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 7a85f8d58fa..60b17404b29 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4201,3 +4201,13 @@ shape Appearance Izgled Color Indicates: Boja označava: Ink Characteristics Karakteristike mastila Solidity: Punoća: + Calibration Kalibracija + Red Primary Crvena primarna + Green Primary Zelena primarna + Blue Primary Plava primarna + Write xmp sidecars Upisuj prateće XMP datoteke + Set the tone sliders from the image Postavi klizače tona prema slici + Settings from {name} Podešavanja iz {name} + Settings from {name}; {count} not supported: {names} Podešavanja iz {name}; {count} nije podržano: {names} + Could not write {name}: {error} Nije moguće upisati {name}: {error} + Shadow Tint Nijansa senki diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 12383b694b4..338170e890c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3858,3 +3858,13 @@ cameraData Lens Lens Color Indicates: Rengin Gösterdiği: Ink Characteristics Mürekkep Özellikleri Solidity: Doluluk: + Calibration Kalibrasyon + Red Primary Kırmızı ana renk + Green Primary Yeşil ana renk + Blue Primary Mavi ana renk + Write xmp sidecars XMP yan dosyalarını yaz + Set the tone sliders from the image Ton kaydırıcılarını görüntüden ayarla + Settings from {name} {name} ayarları + Settings from {name}; {count} not supported: {names} {name} ayarları; {count} desteklenmiyor: {names} + Could not write {name}: {error} {name} yazılamadı: {error} + Shadow Tint Gölge tonu diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a9bae9eb278..b1977e72a3d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3824,3 +3824,13 @@ curves Smooth Згладити @plural {n} action|{n} actions {n} операція|{n} операції|{n} операцій Auto Add/Delete Автододавання/видалення ICO is limited to 256 × 256 pixels ICO обмежено розміром 256 × 256 пікселів + Calibration Калібрування + Red Primary Червоний основний + Green Primary Зелений основний + Blue Primary Синій основний + Write xmp sidecars Записувати супутні файли XMP + Set the tone sliders from the image Встановити повзунки тону за зображенням + Settings from {name} Налаштування з {name} + Settings from {name}; {count} not supported: {names} Налаштування з {name}; не підтримується: {count}: {names} + Could not write {name}: {error} Не вдалося записати {name}: {error} + Shadow Tint Відтінок тіней diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index fc652eff83a..c3391e59a19 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3611,3 +3611,13 @@ curves Smooth Làm mượt Choose a gradient file (.grd). Chọn tệp chuyển sắc (.grd). Auto Add/Delete Tự động thêm/xóa ICO is limited to 256 × 256 pixels ICO giới hạn ở 256 × 256 pixel + Calibration Hiệu chuẩn + Red Primary Màu đỏ cơ bản + Green Primary Màu lục cơ bản + Blue Primary Màu lam cơ bản + Write xmp sidecars Ghi tệp phụ XMP + Set the tone sliders from the image Đặt các thanh trượt tông từ ảnh + Settings from {name} Thiết lập từ {name} + Settings from {name}; {count} not supported: {names} Thiết lập từ {name}; {count} không được hỗ trợ: {names} + Could not write {name}: {error} Không thể ghi {name}: {error} + Shadow Tint Sắc độ bóng tối diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index fb6083985ce..c16510782aa 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2734,3 +2734,13 @@ curves Smooth 平滑 @plural {n} action|{n} actions {n} 个动作 Auto Add/Delete 自动添加/删除 ICO is limited to 256 × 256 pixels ICO 最大为 256 × 256 像素 + Calibration 校准 + Red Primary 红原色 + Green Primary 绿原色 + Blue Primary 蓝原色 + Write xmp sidecars 写入 XMP 附属文件 + Set the tone sliders from the image 根据图像设置色调滑块 + Settings from {name} 来自 {name} 的设置 + Settings from {name}; {count} not supported: {names} 来自 {name} 的设置;{count} 项不支持:{names} + Could not write {name}: {error} 无法写入 {name}:{error} + Shadow Tint 阴影色调 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 760e390812c..a96a16c821a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2719,3 +2719,13 @@ curves Smooth 平滑 @plural {n} action|{n} actions {n} 個動作 Auto Add/Delete 自動增加/刪除 ICO is limited to 256 × 256 pixels ICO 最大為 256 × 256 像素 + Calibration 校準 + Red Primary 紅原色 + Green Primary 綠原色 + Blue Primary 藍原色 + Write xmp sidecars 寫入 XMP 附屬檔案 + Set the tone sliders from the image 根據影像設定色調滑桿 + Settings from {name} 來自 {name} 的設定 + Settings from {name}; {count} not supported: {names} 來自 {name} 的設定;{count} 項不支援:{names} + Could not write {name}: {error} 無法寫入 {name}:{error} + Shadow Tint 陰影色調 diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index 99479f4e321..babfcce497c 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -549,6 +549,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu notices::io_warnings(app, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &crate::camera_raw_ui::without_develop_note(&warnings)); } else { notices::io_warnings(app, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &warnings); + crate::camera_raw_ui::opened_without_dialog(app, index, name, path, &warnings); } // Script events bound to "Open Document". photocraft_engine::automate_cmds::document_opened(&mut app.session); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6bffa8133fe..a45a28ab307 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1229,6 +1229,9 @@ impl PhotocraftApp { notices::io_warnings(self, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &camera_raw_ui::without_develop_note(&warnings)); } else { notices::io_warnings(self, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &warnings); + if let Some(index) = self.session.active_index() { + camera_raw_ui::opened_without_dialog(self, index, name, None, &warnings); + } } // Script events bound to "Open Document". photocraft_engine::automate_cmds::document_opened(&mut self.session); diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index cf0ff51969c..8d5d15b7831 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -2761,10 +2761,11 @@ mod tests { assert!(has_visible_fields(&values, "enhancedControls")); assert!(!prefs::is_hidden("enhancedControls.rotateViewWithTrackpad")); assert!(!prefs::is_hidden("enhancedControls.zoomWithTrackpadPinch")); - // Camera Raw Defaults shows only "Open in Camera Raw" so far. + // Camera Raw Defaults are all live: the dialog's Open applies them (camera_raw_ui). assert!(has_visible_fields(&values, "rawDefaults")); - assert!(!prefs::is_hidden("rawDefaults.openInCameraRaw")); - assert!(prefs::is_hidden("rawDefaults.applyAutoTone")); + for k in ["openInCameraRaw", "applyAutoTone", "colorSpace", "bitDepth", "resolution", "sharpenFor", "openAsSmartObject", "writeXmpSidecars"] { + assert!(!prefs::is_hidden(&format!("rawDefaults.{k}")), "{k}"); + } assert!(!prefs::is_hidden("general.autoShowHomeScreen")); assert!(!prefs::is_hidden("interface.uiScale")); assert!(!prefs::is_hidden("interface.uiFontSize")); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index e571e94f8b3..9e2a3b14b22 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -419,15 +419,23 @@ viewports, so the dialog is drawn over the main window and appears in the image. RGB/Grayscale layer. `params: {"smartFilter": {"layer": id, "index": i}}` opens it on an existing Camera Raw smart filter instead (as double-clicking the filter in the Layers panel does): the stored settings over the pixels below that filter, previewed through the filter mask; commit -then runs `layer.smartFilter.setParams` with every setting. `params.ui` accepts `set` (filter settings), `before`, `scope`, `view`, `commit` and +then runs `layer.smartFilter.setParams` with every setting. `params.ui` accepts `set` (filter settings), `before`, `scope`, `view`, `auto` (true: the Light +sliders from the image's histogram, the panel's Auto button), `saveSettings`, `loadSettings`, `commit` and `cancel`. All parts of one request are validated before any is applied; a rejected request leaves the settings, view state, preferences and document unchanged (and closes a dialog it -opened). Unknown `ui` or settings properties, non-boolean `before` / `commit` / `cancel`, and +opened). Unknown `ui` or settings properties, non-boolean `before` / `auto` / `commit` / `cancel`, and `commit` together with `cancel` are errors. Point curves (`pointCurve`, `pointCurveRed`, `pointCurveGreen`, `pointCurveBlue`) are empty or 2–16 finite points in 0–255 with inputs at least one level apart. Commit dispatches one `filter.cameraRaw` engine command; a failed commit keeps the dialog open for correction. Nothing else writes document history. +A raw file opened from a path reads its sidecar (`IMG_0001.xmp` beside `IMG_0001.CR2`, Camera +Raw's `crs:` settings) into the open-time dialog, and Open writes it back (Preferences › Camera +Raw Defaults › Write xmp sidecars; never beside a DNG). Open also applies the other Camera Raw +Defaults (colour space, bit depth, resolution, Sharpen For as a Camera Raw step, Open as Smart +Object, Apply auto tone), reported as `defaults` in the commit's reply; with "Open in Camera Raw" +off the sidecar and the defaults apply without the dialog. + **Opening a raw file.** An interactive open (File › Open, Open Recent, drag and drop, the command line) of a camera raw developed from its sensor data shows this dialog first, titled "Camera Raw (name)", with **Open** and **Cancel**, as Photoshop opens raws in Adobe Camera Raw. diff --git a/docs/gaps.md b/docs/gaps.md index f7929c276d9..6174868ee21 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -116,9 +116,15 @@ what an agent can't finish alone. (AGENTS.md forbids JS in the app). ### G14. Camera Raw depth -- **Missing:** CR3 (detected, unsupported), compressed RAF, lossy DNG (FILE-215-11), .xmp - sidecars, masking and calibration in the Camera Raw dialog, per-camera colour for non-DNG - cameras, lens profiles. +- **Missing:** CR3 sensor data (the embedded preview opens; the CRX codec has no public + specification, only LGPL implementations, so a clean-room decoder is not possible), compressed + RAF, highlight recovery modes (FILE-215-11), masking in the Camera Raw dialog, per-camera + colour for non-DNG cameras, lens profiles. +- **Done 2026-10-13:** lossy DNG decodes (#5112); `.xmp` sidecars beside raw files fill the + open-time dialog and Open writes them back; the Camera Raw Defaults preferences (colour space, + bit depth, resolution, Sharpen For, Open as Smart Object, Apply auto tone, sidecars) all take + effect on open; the dialog has the Calibration panel (Shadows tint, primaries' hue and + saturation) and an Auto button, both in the `.xmp` settings and the `filter.cameraRaw` params. - **Evidence:** `crates/raw/src/lib.rs:228` (CR3), scorecard FILE-215-11/12, #50. - **Progress (2026-10-11):** on the embedded-JPEG rendering work in #2135, Camera Raw tuning retains the fitted look and applies user gains afterwards. Three D5100 NEFs @@ -255,6 +261,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | G14: lossy DNG (#5112), `.xmp` sidecars, Camera Raw Defaults wired, Calibration panel and Auto; CR3 sensor decode ruled out under the clean-room rule | | 2026-10-13 | minor | G4: minimum inputs in Shape Dynamics and Transfer follow their Control (#3825, partial); no readiness percentage or estimate changed | | 2026-10-12 | minor | G5: Free Transform options bar H/V skew fields done | | 2026-10-12 | minor | G11: `.atn` import maps 112 events (Select and Mask, Spatter, Ripple, Crystallize, Pattern Fill, mask targeting, Step Backward, points, Bitmap) | diff --git a/docs/scorecard.md b/docs/scorecard.md index af13a3f2657..0b7b98f40a3 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -7,9 +7,9 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | Area | Done | Partial | Missing | Key numbers | |---|---:|---:|---:|---| | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | -| [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 | +| [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 | | [Tools](#tools) | 28 | 14 | 1 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 156 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 20 of 157 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | @@ -108,7 +108,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | FILE-215-8 | Large and BigTIFF import with banded decode across all IFDs | done | [#215](https://github.com/storytold/photocraft/issues/215) | codecs tiff_ifd.rs (bounds-checked IFD chain + SubIFD walk, classic and BigTIFF, cycle-safe; tiff_info / decode_tiff_page), tiff.rs banded parallel strip/tile decode, planar 1 and 2, BigTIFF write (tiff_bigtiff or > 4 GiB); io import_tiff_page; 30 MP RGB8 Deflate 345 -> 32 ms; no page picker in the UI yet | | FILE-215-9 | SVG opens and places as shape layers or a vector Smart Object | done | [#215](https://github.com/storytold/photocraft/issues/215) | io svg.rs: paths, groups, text outlines as shape layers (gradients approximated; clip/mask/filter/pattern/image subtrees rasterised); smart_cmds.rs renders an SVG source at its placement scale | | FILE-215-10 | Multi-page PDF save, PDF presentation, layer comps to PDF, vector/text output, PDF import | missing | [#215](https://github.com/storytold/photocraft/issues/215) | Only print_cmds.rs:133 print_pdf (raster print page) | -| FILE-215-11 | RAW: lossy DNG, highlight modes, .xmp sidecars, RAW prefs wired, per-camera corpus | missing | [#215](https://github.com/storytold/photocraft/issues/215) | raw sensor.rs:210 lossy DNG unsupported; raw_defaults unread; no xmp | +| FILE-215-11 | RAW: lossy DNG, highlight modes, .xmp sidecars, RAW prefs wired, per-camera corpus | partial | [#215](https://github.com/storytold/photocraft/issues/215) | 2026-10-13: lossy DNG (34892) decodes stored 8-bit samples with padded edge tiles (raw sensor.rs lossy_jpeg, #5112); a raw's sidecar IMG.xmp fills the open-time dialog and Open writes it back (camera_raw_ui.rs read_sidecar/write_sidecar, pref rawDefaults.writeXmpSidecars); every Camera Raw Defaults preference is read (colour space, bit depth, resolution, Sharpen For, Open as Smart Object, Apply auto tone: apply_raw_defaults); Calibration panel (shadow tint, primaries hue/saturation) in the dialog, the filter and the crs: keys. Still missing: highlight recovery modes, the absolute (kelvin) white balance of raw sidecars, a per-camera corpus | | FILE-215-12 | Camera Raw dialog shows a histogram; settings persist as a PSD Smart Filter | partial | [#215](https://github.com/storytold/photocraft/issues/215) | Interactive RGB/Lab scopes. PSD WB/Light/Presence, curves, HSL, grading, sharpening/noise detail, grain and numeric vignette controls mapped with descriptor preservation. Active manual Optics and unverified vignette style keep the updated ACR 18.4 fixture opaque; PSD/.pcraft saves preserve it. HDR, remaining settings and Photoshop acceptance still open | | FILE-215-13 | Video layer frames persist in .pcraft; PSD video layers mapped | partial | [#215](https://github.com/storytold/photocraft/issues/215) | format convert.rs:89 + tests/roundtrip.rs:282 persist frames; no PSD video mapping | | FILE-215-14 | User swatch model with ACO/ASE import and export | done | [#215](https://github.com/storytold/photocraft/issues/215) | engine presets/swatches.rs (RGB/HSB/CMYK/Lab/Gray + verbatim colour books, persisted in prefs) + swatch_cmds.rs (swatches.*); psd aco.rs (v1/v2) and ase.rs (groups, spot/global) read+write; ui swatches_ui.rs, Color Picker Add to Swatches | @@ -176,9 +176,9 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 26 of 156** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 20 of 157** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. -Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. +Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `integrations.allow_agent_control`, `integrations.control_port`. | Id | Target | Status | Issue | Note | |---|---|---|---|---| diff --git a/scorecard/file_compat.toml b/scorecard/file_compat.toml index 40b242ea536..561ed491031 100644 --- a/scorecard/file_compat.toml +++ b/scorecard/file_compat.toml @@ -78,9 +78,9 @@ note = "Only print_cmds.rs:133 print_pdf (raster print page)" [[item]] id = "FILE-215-11" target = "RAW: lossy DNG, highlight modes, .xmp sidecars, RAW prefs wired, per-camera corpus" -status = "missing" +status = "partial" issue = 215 -note = "raw sensor.rs:210 lossy DNG unsupported; raw_defaults unread; no xmp" +note = "2026-10-13: lossy DNG (34892) decodes stored 8-bit samples with padded edge tiles (raw sensor.rs lossy_jpeg, #5112); a raw's sidecar IMG.xmp fills the open-time dialog and Open writes it back (camera_raw_ui.rs read_sidecar/write_sidecar, pref rawDefaults.writeXmpSidecars); every Camera Raw Defaults preference is read (colour space, bit depth, resolution, Sharpen For, Open as Smart Object, Apply auto tone: apply_raw_defaults); Calibration panel (shadow tint, primaries hue/saturation) in the dialog, the filter and the crs: keys. Still missing: highlight recovery modes, the absolute (kelvin) white balance of raw sidecars, a per-camera corpus" [[item]] id = "FILE-215-12" From fab7d9739e36792a29eab25c6cf3816f975492aa Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 12:04:32 +0100 Subject: [PATCH 2/2] Integration: keep foreign raw sidecars, develop before the workflow conversion (#5128) Open wrote PhotoCraft's crs: subset over any existing sidecar, on by default: a Lightroom or Bridge IMG_0001.xmp lost its crop, masks, rating and keywords, even when the raw was only opened with Open in Camera Raw off (FredApps' review). Now a sidecar is only written when the settings changed, never over one whose x:xmptk isn't PhotoCraft's (a notice says it was kept, camera_raw_xmp::is_photocraft_xmp), and never for a control or MCP request, which has no authority to write beside the user's files. A write error goes to a notice instead of a status line the develop overwrote at once. The Camera Raw Defaults' colour space, 8-bit and smart-object steps ran before the Camera Raw step, so with the default Adobe RGB every raw opened with the dialog's settings applied to other pixels than it previewed. They now follow the step (also when a background re-develop lands), as Camera Raw converts to the workflow space last. Main already sets the raw resolution at import (#7811), so the PR's Image Size step is dropped. Two raws opened back to back with raw-stage edits: the second one's background re-develop replaced the first one's pending entry, so the first never got its Camera Raw step, conversions or unmodified mark. Pending re-develops are now a list keyed by job. Sidecars are read only from regular files of at most MAX_XMP_BYTES (a pipe or a huge file named IMG.xmp no longer blocks or fills memory), and a conversion that fails after the Camera Raw step is reported instead of leaving the dialog open for a second Open that would apply the step twice. Tests: a_foreign_sidecar_is_never_overwritten, a_rating_only_sidecar_is_left_alone, opening_without_the_dialog_does_not_rewrite_the_sidecar, a_control_request_never_writes_the_sidecar, a_sidecar_write_error_stays_reported, the_camera_raw_step_runs_before_the_workflow_conversion (inline and background), two_raws_opened_back_to_back_both_finish_their_open, sidecars_are_read_from_small_regular_files_only, is_photocraft_xmp_reads_the_toolkit_marker; the existing sidecar round trip now uses a PhotoCraft-written fixture. Co-authored-by: Fabio Lissi <3223836+FabioLissi@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/io/src/camera_raw_xmp.rs | 39 ++ .../ui-egui/src/camera_raw_identity_tests.rs | 10 +- crates/ui-egui/src/camera_raw_ui.rs | 501 +++++++++++++++--- crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sr.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/lib.rs | 7 +- docs/control-protocol.md | 13 +- docs/scorecard.md | 10 +- 26 files changed, 504 insertions(+), 96 deletions(-) diff --git a/crates/io/src/camera_raw_xmp.rs b/crates/io/src/camera_raw_xmp.rs index 80ec9e7ef0f..a2e63322d04 100644 --- a/crates/io/src/camera_raw_xmp.rs +++ b/crates/io/src/camera_raw_xmp.rs @@ -274,6 +274,25 @@ fn escape(s: &str) -> String { s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) } +/// The XMP toolkit [`save`] names on `x:xmpmeta`. +const TOOLKIT: &str = "PhotoCraft"; +const META_NS: &str = "adobe:ns:meta/"; + +/// Did [`save`] write this file? True when its `x:xmpmeta` names PhotoCraft as the toolkit +/// (`x:xmptk`). Lightroom, Bridge and Camera Raw put their own toolkit there when they write a +/// file, so a sidecar another application touched since reads false. Never panics. +pub fn is_photocraft_xmp(bytes: &[u8]) -> bool { + if bytes.len() > MAX_XMP_BYTES { + return false; + } + let Ok(text) = std::str::from_utf8(bytes) else { return false }; + let Ok(doc) = roxmltree::Document::parse(text.trim_start_matches('\u{feff}')) else { return false }; + doc.descendants() + .find(|n| n.is_element() && n.tag_name().namespace() == Some(META_NS) && n.tag_name().name() == "xmpmeta") + .and_then(|n| n.attribute((META_NS, "xmptk"))) + == Some(TOOLKIT) +} + /// Write `params` as a Camera Raw settings file Photoshop's Load Settings… reads. pub fn save(params: &CameraRaw) -> String { let mut p = params.clone(); @@ -430,4 +449,24 @@ mod tests { assert_eq!(p, before); assert_eq!(r.ignored, vec!["Contrast2012".to_string(), "ToneCurvePV2012".to_string()]); } + + #[test] + fn is_photocraft_xmp_reads_the_toolkit_marker() { + let own = save(&CameraRaw { contrast: 15.0, ..CameraRaw::default() }); + assert!(is_photocraft_xmp(own.as_bytes())); + let wrapped = format!("\u{feff}\n{own}"); + assert!(is_photocraft_xmp(wrapped.as_bytes()), "an xpacket wrapper and a byte order mark"); + assert!(!is_photocraft_xmp(FIXTURE), "Camera Raw's own toolkit"); + for other in [ + &b""[..], + b"", + b"", + b"", + b"", + b"\xff\xfe", + ] { + assert!(!is_photocraft_xmp(other), "{}", String::from_utf8_lossy(other)); + } + } } diff --git a/crates/ui-egui/src/camera_raw_identity_tests.rs b/crates/ui-egui/src/camera_raw_identity_tests.rs index 17c4967ba6f..a0f57884e98 100644 --- a/crates/ui-egui/src/camera_raw_identity_tests.rs +++ b/crates/ui-egui/src/camera_raw_identity_tests.rs @@ -63,14 +63,14 @@ fn identity_app() -> (PhotocraftApp, RawOpen, Control) { fn completed_redevelop(app: &mut PhotocraftApp, raw: &RawOpen) -> (CameraRaw, Value, photocraft_doc::DocId) { app.background_jobs = true; let params = CameraRaw { exposure: 1.0, contrast: 20.0, ..Default::default() }; - let started = commit_open_raw(app, ¶ms, raw).unwrap(); + let started = commit_open_raw(app, ¶ms, raw, None).unwrap(); let job = photocraft_engine::jobs::JobId(started["job"].as_u64().expect("the sensor re-develop runs as a real job")); let mut result = app.session.wait_job(job).unwrap(); let replacement = app.session.documents()[result["document"].as_u64().unwrap() as usize].doc.id; // The producer has a separate contract test. Supply the observed identity here to isolate // the UI consumer's handling even when run against the old result schema. result["docId"] = json!(replacement.0); - app.raw_redevelop = None; + app.raw_redevelop.clear(); app.background_jobs = false; (params, result, replacement) } @@ -96,7 +96,7 @@ fn completion_identity_applies_remaining_settings_after_tab_reordering() { let index = result["document"].as_u64().unwrap() as usize; app.session.move_document(index, 0).unwrap(); assert_eq!(app.session.documents()[index].doc.id, control.doc.id, "another completion may move this tab before the RAW callback"); - finish_redevelop(&mut app, ¶ms, &raw, &result).unwrap(); + finish_redevelop(&mut app, ¶ms, &raw, &result, &Default::default()).unwrap(); control.assert_untouched(&app); let state = app.session.active().unwrap(); assert_eq!(state.doc.id, replacement); @@ -113,7 +113,7 @@ fn completion_identity_rejects_a_closed_replacement_without_filtering_the_active let index = app.session.documents().iter().position(|state| state.doc.id == replacement).unwrap(); app.session.close(index).unwrap(); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); - assert!(finish_redevelop(&mut app, ¶ms, &raw, &result).is_err(), "a closed replacement must not fall back to the active document"); + assert!(finish_redevelop(&mut app, ¶ms, &raw, &result, &Default::default()).is_err(), "a closed replacement must not fall back to the active document"); control.assert_untouched(&app); assert_eq!(app.session.documents().len(), 1); } @@ -133,7 +133,7 @@ fn completion_identity_rejects_missing_and_invalid_ids_before_any_side_effect() app.session.set_active(0); let views = app.view_docs.clone(); let notices = app.ui.notices.len(); - assert!(finish_redevelop(&mut app, ¶ms, &raw, &result).is_err(), "invalid identity was accepted: {result}"); + assert!(finish_redevelop(&mut app, ¶ms, &raw, &result, &Default::default()).is_err(), "invalid identity was accepted: {result}"); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); assert_eq!(app.view_docs, views, "identity validation precedes view remapping"); diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/camera_raw_ui.rs index b61eb87a928..12a703161f6 100644 --- a/crates/ui-egui/src/camera_raw_ui.rs +++ b/crates/ui-egui/src/camera_raw_ui.rs @@ -465,8 +465,10 @@ pub struct Redevelop { params: CameraRaw, raw: RawOpen, /// The job is the final Camera Raw step (`filter.cameraRaw`), not the re-develop: when it - /// lands the document is marked unmodified. + /// lands the Camera Raw Defaults' conversions follow and the document is marked unmodified. filter_step: bool, + /// The Camera Raw Defaults the open started with, for the conversions after the filter step. + defaults: photocraft_engine::prefs::RawDefaults, } /// The sliders a raw open applies while developing, before the tone curve (as Camera Raw does). @@ -480,9 +482,9 @@ fn raw_stage(p: &CameraRaw) -> photocraft_io::raw::Tone { /// on) it runs as a job like the open itself: the reply is `{"job", "pending": true}`, the /// document is locked meanwhile, and [`on_redevelop_event`] finishes when it lands. Elsewhere /// (tests, the web) it runs inline. -fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen) -> Result { +fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen, loaded: Option<&CameraRaw>) -> Result { let index = document_index(app, raw.document).ok_or("the raw document was closed")?; - write_sidecar(app, raw, params); + write_sidecar(app, raw, params, loaded); let tuning = photocraft_io::raw::RawTuning { temperature: params.temperature, tint: params.tint, @@ -504,7 +506,8 @@ fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen) - _ => None, }; let Some(source) = source.filter(|_| tuning != as_opened) else { - return finish_open_raw(app, index, params.clone(), None, Some(raw)); + let defaults = app.session.prefs().raw_defaults.clone(); + return finish_open_raw(app, index, params.clone(), None, raw, &defaults); }; app.session.set_active(index); let (name, doc_id) = (raw.name.clone(), raw.document); @@ -532,9 +535,13 @@ fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen) - photocraft_engine::jobs::Started::Done(v) }; match started { - photocraft_engine::jobs::Started::Done(v) => finish_redevelop(app, params, raw, &v), + photocraft_engine::jobs::Started::Done(v) => { + let defaults = app.session.prefs().raw_defaults.clone(); + finish_redevelop(app, params, raw, &v, &defaults) + } photocraft_engine::jobs::Started::Job(job) => { - app.raw_redevelop = Some(Redevelop { job, params: params.clone(), raw: raw.clone(), filter_step: false }); + let defaults = app.session.prefs().raw_defaults.clone(); + app.raw_redevelop.push(Redevelop { job, params: params.clone(), raw: raw.clone(), filter_step: false, defaults }); app.ui.status = label; app.ui.status_error = false; Ok(json!({"job": job.0, "pending": true})) @@ -571,7 +578,13 @@ fn replace_raw_document( /// After the re-develop: keep the old document's view (zoom, scroll) on the new one, report /// the import's notes, then apply the remaining settings. -fn finish_redevelop(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen, v: &Value) -> Result { +fn finish_redevelop( + app: &mut PhotocraftApp, + params: &CameraRaw, + raw: &RawOpen, + v: &Value, + defaults: &photocraft_engine::prefs::RawDefaults, +) -> Result { // A preceding completion (for example Save and Close) may have shifted the tab indices. // Validate identity before remapping views, filtering or marking any document unmodified. let replacement = v.get("docId").and_then(Value::as_u64).map(photocraft_doc::DocId).ok_or("the re-develop returned no document identity")?; @@ -593,19 +606,30 @@ fn finish_redevelop(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen, rest.temperature = 0.0; rest.tint = 0.0; } - finish_open_raw(app, index, rest, Some(true), Some(raw)) + finish_open_raw(app, index, rest, Some(true), raw, defaults) } -/// The other settings as one Camera Raw step on document `index`, then the document is marked -/// unmodified (developing is part of opening). The step runs like any filter (in the -/// background in the desktop app); the document is marked unmodified when it lands. -fn finish_open_raw(app: &mut PhotocraftApp, index: usize, mut rest: CameraRaw, redeveloped: Option, raw: Option<&RawOpen>) -> Result { +/// The other settings as one Camera Raw step on document `index`, then the Camera Raw Defaults' +/// conversions, then the document is marked unmodified (developing is part of opening). The +/// step runs like any filter (in the background in the desktop app); the conversions follow and +/// the document is marked unmodified when it lands. The step works on the developed ProPhoto +/// pixels the dialog previewed, and the conversion to the workflow space comes last, as in +/// Camera Raw. +fn finish_open_raw( + app: &mut PhotocraftApp, + index: usize, + mut rest: CameraRaw, + redeveloped: Option, + raw: &RawOpen, + d: &photocraft_engine::prefs::RawDefaults, +) -> Result { app.session.set_active(index); app.sync_views(); let mut result = json!({"document": index, "redeveloped": redeveloped.unwrap_or(false)}); - let defaults = apply_raw_defaults(app, index, &mut rest)?; - if !defaults.is_empty() { - result["defaults"] = json!(defaults); + let mut applied = output_sharpening(d, &mut rest); + applied.extend(raw_conversions(d)); + if !applied.is_empty() { + result["defaults"] = json!(applied); } if !rest.is_identity() { let layer = app.session.active().and_then(|st| st.active_layer).ok_or("no layer to develop")?; @@ -613,12 +637,21 @@ fn finish_open_raw(app: &mut PhotocraftApp, index: usize, mut rest: CameraRaw, r p["layer"] = json!(layer.0); let r = app.run("filter.cameraRaw", p)?; if r.get("pending").and_then(Value::as_bool) == Some(true) - && let (Some(job), Some(raw)) = (r.get("job").and_then(Value::as_u64), raw) + && let Some(job) = r.get("job").and_then(Value::as_u64) { - app.raw_redevelop = Some(Redevelop { job: photocraft_engine::jobs::JobId(job), params: rest.clone(), raw: raw.clone(), filter_step: true }); + let job = photocraft_engine::jobs::JobId(job); + app.raw_redevelop.push(Redevelop { job, params: rest.clone(), raw: raw.clone(), filter_step: true, defaults: d.clone() }); + result["filter"] = r; + mark_unmodified(app, index); + return Ok(result); } result["filter"] = r; } + // The Camera Raw step has landed: a failed conversion is reported, and the open still + // completes (a second Open would apply the step twice). + if let Err(e) = apply_raw_conversions(app, index, d) { + crate::notices::error(app, format!("{}: {e}", raw.name)); + } mark_unmodified(app, index); Ok(result) } @@ -643,11 +676,10 @@ fn is_dng(path: &str) -> bool { #[cfg(not(target_arch = "wasm32"))] fn read_sidecar(path: &str) -> Option<(CameraRaw, photocraft_io::camera_raw_xmp::LoadReport, String)> { let sidecar = sidecar_path(path); - let bytes = std::fs::read(&sidecar).ok()?; - if bytes.len() > photocraft_io::camera_raw_xmp::MAX_XMP_BYTES { - log::warn!("{sidecar}: sidecar larger than {} bytes, ignored", photocraft_io::camera_raw_xmp::MAX_XMP_BYTES); + let Some(bytes) = read_bounded(&sidecar) else { + log::warn!("{sidecar}: not a readable sidecar of at most {} bytes, ignored", photocraft_io::camera_raw_xmp::MAX_XMP_BYTES); return None; - } + }; let mut params = CameraRaw::default(); match photocraft_io::camera_raw_xmp::load(&mut params, &bytes) { Ok(report) => Some((params, report, crate::file_open::display_name(&sidecar))), @@ -663,66 +695,113 @@ fn read_sidecar(_: &str) -> Option<(CameraRaw, photocraft_io::camera_raw_xmp::Lo } /// Keep the develop settings beside the raw file (Camera Raw Defaults › Write xmp sidecars): -/// written when the settings aren't the defaults or a sidecar already exists, so a file reopens -/// as it was developed. Not for DNGs, and never fatal: a folder that can't be written to is -/// reported in the status bar. -fn write_sidecar(app: &mut PhotocraftApp, raw: &RawOpen, params: &CameraRaw) { - if !app.session.prefs().raw_defaults.write_xmp_sidecars { +/// written when the settings aren't the defaults or PhotoCraft's own sidecar is there, so a +/// file reopens as it was developed. `loaded` are the settings the open started from: nothing +/// is written when they didn't change. Not for DNGs, never over a sidecar another application +/// wrote (Lightroom's and Bridge's hold crops, masks, ratings and keywords PhotoCraft can't keep), +/// never for a control or MCP request (it has no authority to write beside the user's files), and +/// never fatal: a folder that can't be written to is reported in a notice. +fn write_sidecar(app: &mut PhotocraftApp, raw: &RawOpen, params: &CameraRaw, loaded: Option<&CameraRaw>) { + if !app.session.prefs().raw_defaults.write_xmp_sidecars || loaded == Some(params) { + return; + } + if app.automation_input || app.session.authorize.is_some() { + log::info!("{}: sidecar not written for an automation request", raw.name); return; } let Some(path) = raw.path.as_deref().filter(|p| !is_dng(p)) else { return }; let sidecar = sidecar_path(path); - #[cfg(not(target_arch = "wasm32"))] - let exists = std::path::Path::new(&sidecar).exists(); - #[cfg(target_arch = "wasm32")] - let exists = false; - if params.is_identity() && !exists { - return; + let name = crate::file_open::display_name(&sidecar); + match existing_sidecar_is_ours(&sidecar) { + Some(false) => { + let kept = crate::i18n::fmt(tl!("Kept {name}: written by another application"), &[("name", &name)]); + crate::notices::post(app, kept, Vec::new(), false, None); + return; + } + None if params.is_identity() => return, + _ => {} } let bytes = photocraft_io::camera_raw_xmp::save(params).into_bytes(); let Some(write) = app.services.write.as_mut() else { return }; if let Err(e) = write(&sidecar, &bytes) { - app.ui.status = crate::i18n::fmt(tl!("Could not write {name}: {error}"), &[("name", &crate::file_open::display_name(&sidecar)), ("error", &e)]); - app.ui.status_error = true; + crate::notices::error(app, crate::i18n::fmt(tl!("Could not write {name}: {error}"), &[("name", &name), ("error", &e)])); } } -/// Camera Raw Defaults (Preferences): the colour space, bit depth and resolution the developed -/// document opens in, output sharpening (folded into the Camera Raw step `rest`, as the -/// workflow's Sharpen For is), and Open as Smart Object. Returns what it applied. -fn apply_raw_defaults(app: &mut PhotocraftApp, index: usize, rest: &mut CameraRaw) -> Result, String> { +/// `None` when there is no sidecar at `sidecar`, else whether PhotoCraft wrote it. One that +/// can't be read or is too large to be ours counts as another application's. +#[cfg(not(target_arch = "wasm32"))] +fn existing_sidecar_is_ours(sidecar: &str) -> Option { + std::fs::symlink_metadata(sidecar).ok()?; + Some(read_bounded(sidecar).is_some_and(|b| photocraft_io::camera_raw_xmp::is_photocraft_xmp(&b))) +} + +/// The bytes of the regular file at `path` when it holds at most +/// [`photocraft_io::camera_raw_xmp::MAX_XMP_BYTES`]; `None` for anything else (missing, a folder, +/// a pipe or device that might never end, larger). Never reads more than the cap plus one byte. +#[cfg(not(target_arch = "wasm32"))] +fn read_bounded(path: &str) -> Option> { + use std::io::Read; + let cap = photocraft_io::camera_raw_xmp::MAX_XMP_BYTES; + // Checked before opening: opening a pipe for reading waits for a writer. + if !std::fs::metadata(path).ok()?.is_file() { + return None; + } + let file = std::fs::File::open(path).ok()?; + let mut bytes = Vec::new(); + file.take(cap as u64 + 1).read_to_end(&mut bytes).ok()?; + (bytes.len() <= cap).then_some(bytes) +} +#[cfg(target_arch = "wasm32")] +fn existing_sidecar_is_ours(_: &str) -> Option { + None +} + +/// Camera Raw Defaults › Sharpen For: output sharpening, folded into the Camera Raw step `rest` +/// as the workflow's Sharpen For is. Returns what it applied. +fn output_sharpening(d: &photocraft_engine::prefs::RawDefaults, rest: &mut CameraRaw) -> Vec<&'static str> { + match d.sharpen_for.preset() { + Some((amount, radius)) if rest.sharpen_amount == 0.0 => { + rest.sharpen_amount = amount; + rest.sharpen_radius = radius; + vec!["sharpenFor"] + } + _ => Vec::new(), + } +} + +/// The Camera Raw Defaults [`apply_raw_conversions`] applies. Resolution is not among them: the +/// open itself sets it (`file_cmds::raw_defaults`), and a re-develop keeps it. +fn raw_conversions(d: &photocraft_engine::prefs::RawDefaults) -> Vec<&'static str> { use photocraft_engine::prefs::{RawColorSpace, RawDepth}; - let d = app.session.prefs().raw_defaults.clone(); - app.session.set_active(index); - let mut applied = Vec::new(); - let profile = d.color_space.profile_id(); + let mut out = Vec::new(); // Raws develop into ProPhoto-compatible RGB (`photocraft_io::raw`); the other spaces are a // conversion. - if profile != RawColorSpace::ProPhoto.profile_id() { - app.session.execute("edit.convertToProfile", json!({"profile": profile, "intent": "relative"})).map_err(|e| e.to_string())?; - applied.push("colorSpace"); + if d.color_space != RawColorSpace::ProPhoto { + out.push("colorSpace"); } if d.bit_depth == RawDepth::Eight { - app.session.execute("image.mode.bits8", json!({})).map_err(|e| e.to_string())?; - applied.push("bitDepth"); - } - let dpi = app.session.active().map(|st| st.doc.resolution_dpi).unwrap_or(72.0); - if d.resolution.is_finite() && d.resolution > 0.0 && (f64::from(dpi) - d.resolution).abs() > 1e-6 { - app.session.execute("image.imageSize", json!({"resolution": d.resolution})).map_err(|e| e.to_string())?; - applied.push("resolution"); - } - if let Some((amount, radius)) = d.sharpen_for.preset() - && rest.sharpen_amount == 0.0 - { - rest.sharpen_amount = amount; - rest.sharpen_radius = radius; - applied.push("sharpenFor"); + out.push("bitDepth"); } if d.open_as_smart_object { - app.session.execute("layer.smartObjects.convertToSmartObject", json!({})).map_err(|e| e.to_string())?; - applied.push("openAsSmartObject"); + out.push("openAsSmartObject"); } - Ok(applied) + out +} + +/// Camera Raw Defaults (Preferences) after the Camera Raw step: the colour space and bit depth +/// the developed document opens in, and Open as Smart Object. +fn apply_raw_conversions(app: &mut PhotocraftApp, index: usize, d: &photocraft_engine::prefs::RawDefaults) -> Result<(), String> { + app.session.set_active(index); + for step in raw_conversions(d) { + let (id, params) = match step { + "colorSpace" => ("edit.convertToProfile", json!({"profile": d.color_space.profile_id(), "intent": "relative"})), + "bitDepth" => ("image.mode.bits8", json!({})), + _ => ("layer.smartObjects.convertToSmartObject", json!({})), + }; + app.session.execute(id, params).map_err(|e| e.to_string())?; + } + Ok(()) } /// A raw that opened without the dialog (Camera Raw Defaults › Open in Camera Raw off): its @@ -736,14 +815,20 @@ pub fn opened_without_dialog(app: &mut PhotocraftApp, index: usize, name: &str, let method = photocraft_io::raw::developed_demosaic(warnings).unwrap_or_else(|| app.session.prefs().raw_defaults.demosaic.method()); let raw = RawOpen { document, name: name.to_string(), path: path.map(str::to_string), bytes: None, developed_with: method, demosaic: method }; let mut params = CameraRaw::default(); - if let Some((loaded, _, _)) = path.and_then(read_sidecar) { - params = loaded; + let sidecar = path.and_then(read_sidecar).map(|(loaded, _, _)| loaded); + if let Some(loaded) = &sidecar { + params = loaded.clone(); } else if app.session.prefs().raw_defaults.apply_auto_tone && let Some(px) = app.session.active().and_then(|st| st.doc.layer(st.active_layer?)).and_then(|l| l.surface()).map(|s| sample_pixels(s, 512)) { photocraft_algo::camera_raw::auto_tone(&px, &mut params); } - let r = if params.is_identity() { finish_open_raw(app, index, params, None, Some(&raw)) } else { commit_open_raw(app, ¶ms, &raw) }; + let r = if params.is_identity() { + let defaults = app.session.prefs().raw_defaults.clone(); + finish_open_raw(app, index, params, None, &raw, &defaults) + } else { + commit_open_raw(app, ¶ms, &raw, sidecar.as_ref()) + }; if let Err(e) = r { app.ui.status = e; app.ui.status_error = true; @@ -784,18 +869,29 @@ fn mark_unmodified(app: &mut PhotocraftApp, index: usize) { /// A finished background re-develop ([`REDEVELOP_JOB`]) or open-time Camera Raw step. `true` /// when the event was one of those (handled here). pub fn on_redevelop_event(app: &mut PhotocraftApp, e: &photocraft_engine::jobs::JobEvent) -> bool { - let Some(pending) = app.raw_redevelop.take_if(|r| r.job == e.id) else { return false }; + let Some(at) = app.raw_redevelop.iter().position(|r| r.job == e.id) else { return false }; + let pending = app.raw_redevelop.remove(at); if pending.filter_step { - if matches!(e.outcome, photocraft_engine::jobs::JobOutcome::Done(_)) - && let Some(index) = e.document.and_then(|id| document_index(app, id)) - { - mark_unmodified(app, index); + // The Camera Raw Defaults' conversions follow the Camera Raw step, whatever its outcome: + // the document still opens in the workflow's colour space and depth. + if let Some(index) = e.document.and_then(|id| document_index(app, id)) { + let active = app.session.active_index(); + if let Err(err) = apply_raw_conversions(app, index, &pending.defaults) { + crate::notices::error(app, format!("{}: {err}", pending.raw.name)); + } + if let Some(i) = active { + app.session.set_active(i); + } + if matches!(e.outcome, photocraft_engine::jobs::JobOutcome::Done(_)) { + mark_unmodified(app, index); + } + app.sync_views(); } // The usual filter reporting still applies. return false; } match &e.outcome { - photocraft_engine::jobs::JobOutcome::Done(v) => match finish_redevelop(app, &pending.params, &pending.raw, v) { + photocraft_engine::jobs::JobOutcome::Done(v) => match finish_redevelop(app, &pending.params, &pending.raw, v, &pending.defaults) { Ok(_) => { app.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", &pending.raw.name)]); app.ui.status_error = false; @@ -1277,8 +1373,8 @@ fn commit(app: &mut PhotocraftApp) -> Result { } Target::OpenRaw => { let raw = d.raw_open.clone().ok_or("no raw file is being opened")?; - let params = d.params.clone(); - commit_open_raw(app, ¶ms, &raw)? + let (params, original) = (d.params.clone(), d.original.clone()); + commit_open_raw(app, ¶ms, &raw, Some(&original))? } }; app.camera_raw = None; @@ -2203,12 +2299,12 @@ mod tests { assert!(app.camera_raw.is_none()); for _ in 0..3000 { crate::jobs_ui::tick(&mut app, &ctx); - if app.raw_redevelop.is_none() && !app.session.has_jobs() { + if app.raw_redevelop.is_empty() && !app.session.has_jobs() { break; } std::thread::sleep(std::time::Duration::from_millis(5)); } - assert!(app.raw_redevelop.is_none() && !app.session.has_jobs(), "the jobs never finished"); + assert!(app.raw_redevelop.is_empty() && !app.session.has_jobs(), "the jobs never finished"); let docs = app.session.documents(); assert_eq!(docs.len(), 3); assert_eq!((docs[0].doc.size.width, docs[2].doc.size.width), (10, 12), "the other tabs keep their places"); @@ -2255,7 +2351,7 @@ mod tests { open_raw(&mut app, &ctx, raw).unwrap(); let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); assert_eq!((r["document"].as_u64(), r["redeveloped"].as_bool(), r.get("filter")), (Some(0), Some(false), None), "{r}"); - assert_eq!(r["defaults"], json!(["resolution"]), "Camera Raw Defaults: 300 ppi, from the develop's 72: {r}"); + assert_eq!(r.get("defaults"), None, "ProPhoto, 16-bit: no Camera Raw Default to apply: {r}"); // Preference off: raws open straight away. app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); app.open_bytes("c.dng", &dng).unwrap(); @@ -2336,7 +2432,7 @@ mod tests { assert_eq!(sidecar_path("/a/b.c/noext"), "/a/b.c/noext.xmp"); std::fs::write( sidecar_path(&raw_path), - "", + "", ) .unwrap(); type Written = Arc)>>>; @@ -2416,13 +2512,262 @@ mod tests { let raw = app.pending_raw_open.take().unwrap(); open_raw(&mut app, &ctx, raw).unwrap(); let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert_eq!(r["defaults"], json!(["colorSpace", "resolution", "sharpenFor"]), "{r}"); + assert_eq!(r["defaults"], json!(["sharpenFor", "colorSpace"]), "{r}"); assert!(r.get("filter").is_some(), "Sharpen For is a Camera Raw step: {r}"); let st = app.session.active().unwrap(); assert_eq!(st.doc.depth, photocraft_color::SampleType::U16); assert_eq!(st.saved_revision, st.revision); } + type Written = std::sync::Arc)>>>; + + /// A sidecar as Lightroom Classic leaves one beside a raw: its own toolkit, a crop, a rating + /// and a keyword next to the develop settings (values synthetic). + const LIGHTROOM_SIDECAR: &str = r#" + + + harbour + + + +"#; + + /// `raw_app` whose `write` service records what it is asked to write, and a raw file in a fresh + /// folder with `sidecar` beside it when given. Returns the app, the raw's bytes, the folder, + /// the raw's path and the recorded writes. + fn raw_with_sidecar(tag: &str, sidecar: Option<&str>) -> (PhotocraftApp, Vec, std::path::PathBuf, String, Written) { + let (mut app, dng) = raw_app(); + let dir = std::env::temp_dir().join(format!("photocraft-sidecar-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let raw_path = dir.join("IMG_0100.cr2").to_string_lossy().into_owned(); + std::fs::write(&raw_path, &dng).unwrap(); + if let Some(text) = sidecar { + std::fs::write(sidecar_path(&raw_path), text).unwrap(); + } + let written: Written = Default::default(); + let sink = written.clone(); + app.services.write = Some(Box::new(move |p: &str, b: &[u8]| { + sink.lock().unwrap().push((p.to_string(), b.to_vec())); + Ok(()) + })); + (app, dng, dir, raw_path, written) + } + + /// Opens the raw at `raw_path` in the open-time dialog, as File › Open does. + fn open_dialog_at(app: &mut PhotocraftApp, ctx: &egui::Context, dng: &[u8], raw_path: &str) { + app.open_bytes("IMG_0100.cr2", dng).unwrap(); + let mut raw = app.pending_raw_open.take().unwrap(); + raw.path = Some(raw_path.to_string()); + open_raw(app, ctx, raw).unwrap(); + } + + /// The notices about the sidecar (the open's own import notes aside). + fn notice_titles(app: &PhotocraftApp) -> Vec { + app.ui.notices.iter().map(|n| n.title.clone()).filter(|t| t.contains(".xmp")).collect() + } + + /// A Lightroom or Bridge sidecar holds settings PhotoCraft can't keep (crop, masks, rating, + /// keywords): Open uses its develop settings but never writes over it, and says so. + #[test] + fn a_foreign_sidecar_is_never_overwritten() { + let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("foreign", Some(LIGHTROOM_SIDECAR)); + let ctx = egui::Context::default(); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + assert_eq!(app.camera_raw.as_ref().unwrap().params.exposure, 1.0, "the sidecar's settings fill the dialog"); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}}})).unwrap().unwrap(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert!(written.lock().unwrap().is_empty(), "nothing written over Lightroom's sidecar"); + assert_eq!(std::fs::read_to_string(sidecar_path(&raw_path)).unwrap(), LIGHTROOM_SIDECAR); + let titles = notice_titles(&app); + assert!(titles.iter().any(|t| t.contains("IMG_0100.xmp") && t.contains("another application")), "{titles:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Bridge writes a sidecar with only a rating (no Camera Raw settings): it is not PhotoCraft's + /// to replace, with or without a change in the dialog. + #[test] + fn a_rating_only_sidecar_is_left_alone() { + let bridge = r#""#; + let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("rating", Some(bridge)); + let ctx = egui::Context::default(); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert!(written.lock().unwrap().is_empty(), "Open with no change writes nothing"); + assert!(notice_titles(&app).is_empty(), "and has nothing to report: {:?}", notice_titles(&app)); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 10}, "commit": true}})).unwrap().unwrap(); + assert!(written.lock().unwrap().is_empty(), "nor with a change"); + assert_eq!(std::fs::read_to_string(sidecar_path(&raw_path)).unwrap(), bridge); + let _ = std::fs::remove_dir_all(&dir); + } + + /// With Open in Camera Raw off, opening a raw develops it with its sidecar and writes nothing + /// back: nothing changed. + #[test] + fn opening_without_the_dialog_does_not_rewrite_the_sidecar() { + let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("nodialog", Some(LIGHTROOM_SIDECAR)); + app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); + app.open_file(&raw_path, &dng).unwrap(); + assert!(app.pending_raw_open.is_none()); + assert_eq!(app.session.documents().len(), 1); + assert!(written.lock().unwrap().is_empty(), "just opening never writes the sidecar"); + assert_eq!(std::fs::read_to_string(sidecar_path(&raw_path)).unwrap(), LIGHTROOM_SIDECAR); + assert!(notice_titles(&app).is_empty(), "{:?}", notice_titles(&app)); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A control or MCP request has no authority to write beside the user's files: its commit + /// develops the raw but writes no sidecar. The same Open from the dialog does. + #[test] + fn a_control_request_never_writes_the_sidecar() { + fn allow(_: &str, _: &Value) -> photocraft_engine::Result<()> { + Ok(()) + } + let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("control", None); + app.services.automation_authorize = Some(allow); + let ctx = egui::Context::default(); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + let commit = json!({"id": "filter.cameraRaw", "params": {"ui": {"set": {"contrast": 15}, "commit": true}}}); + let (req, _rx) = crate::control::ControlRequest::new("ui.menu.invoke", commit); + let crate::control::Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &req) else { panic!("expected a reply") }; + assert_eq!(reply["ok"], true, "{reply}"); + assert!(app.camera_raw.is_none(), "committed"); + assert!(written.lock().unwrap().is_empty(), "no sidecar from a control request"); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}, "commit": true}})).unwrap().unwrap(); + assert_eq!(written.lock().unwrap().len(), 1, "the user's own Open writes it"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A sidecar that can't be written is reported in a notice that outlasts the status line the + /// develop and the Camera Raw step write after it. + #[test] + fn a_sidecar_write_error_stays_reported() { + let (mut app, dng, dir, raw_path, _) = raw_with_sidecar("readonly", None); + app.services.write = Some(Box::new(|_: &str, _: &[u8]| Err("read-only volume".to_string()))); + let ctx = egui::Context::default(); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 0.5, "contrast": 15}, "commit": true}})).unwrap().unwrap(); + let errors: Vec<_> = app.ui.notices.iter().filter(|n| n.error).map(|n| n.title.clone()).collect(); + assert!(errors.iter().any(|t| t.contains("IMG_0100.xmp") && t.contains("read-only volume")), "{errors:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + + fn open_with_settings(app: &mut PhotocraftApp, ctx: &egui::Context, dng: &[u8], name: &str) { + app.open_bytes(name, dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(app, ctx, raw).unwrap(); + menu(app, ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 0.5, "contrast": 60, "saturation": 40, "vibrance": 30}}})).unwrap().unwrap(); + } + + fn profile_name(app: &PhotocraftApp) -> String { + let st = app.session.active().unwrap(); + st.doc.icc_profile.as_deref().and_then(|p| photocraft_cms::Profile::parse(p).ok()).map(|p| p.description).unwrap_or_default() + } + + /// Camera Raw renders in its own space and converts to the workflow space last, so Open gives + /// what the dialog previewed on the developed ProPhoto pixels: with the default Adobe RGB the + /// result is the Camera Raw step on the ProPhoto develop, then the conversion. Inline and with + /// the re-develop as a background job. + #[test] + fn the_camera_raw_step_runs_before_the_workflow_conversion() { + let ctx = egui::Context::default(); + let (mut app, dng) = raw_app(); + open_with_settings(&mut app, &ctx, &dng, "a.dng"); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + app.run("edit.convertToProfile", json!({"profile": "adobe-rgb-compat", "intent": "relative"})).unwrap(); + let want = pixels(&app); + let close = |a: &[f32], b: &[f32]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5); + for background in [false, true] { + let (mut app, dng) = raw_app(); + app.run("prefs.set", json!({"path": "rawDefaults.colorSpace", "value": "adobeRgb"})).unwrap(); + open_with_settings(&mut app, &ctx, &dng, "b.dng"); + app.background_jobs = background; + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + if background { + assert_eq!(r["pending"], true, "the re-develop runs as a job: {r}"); + } else { + assert_eq!(r["defaults"], json!(["colorSpace"]), "{r}"); + } + for _ in 0..3000 { + crate::jobs_ui::tick(&mut app, &ctx); + if app.raw_redevelop.is_empty() && !app.session.has_jobs() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(app.raw_redevelop.is_empty() && !app.session.has_jobs(), "the jobs never finished"); + assert!(profile_name(&app).to_lowercase().contains("adobe"), "background {background}: {}", profile_name(&app)); + assert!(close(&pixels(&app), &want), "background {background}: the step ran on other pixels than the preview"); + let st = app.session.active().unwrap(); + assert_eq!(st.saved_revision, st.revision, "background {background}: unmodified"); + } + } + + /// Two raws opened one after the other while the first one's re-develop still runs in the + /// background: each lands with its Camera Raw step and conversions and is left unmodified. + #[test] + fn two_raws_opened_back_to_back_both_finish_their_open() { + let ctx = egui::Context::default(); + let (mut app, dng) = raw_app(); + app.run("prefs.set", json!({"path": "rawDefaults.colorSpace", "value": "adobeRgb"})).unwrap(); + open_with_settings(&mut app, &ctx, &dng, "a.dng"); + app.background_jobs = true; + let a = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(a["pending"], true, "the re-develop runs as a job: {a}"); + app.background_jobs = false; + open_with_settings(&mut app, &ctx, &dng, "b.dng"); + app.background_jobs = true; + let b = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(b["pending"], true, "{b}"); + for _ in 0..3000 { + crate::jobs_ui::tick(&mut app, &ctx); + if app.raw_redevelop.is_empty() && !app.session.has_jobs() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(app.raw_redevelop.is_empty() && !app.session.has_jobs(), "the jobs never finished"); + assert_eq!(app.session.documents().len(), 2); + for i in 0..2 { + app.session.set_active(i); + assert!(profile_name(&app).to_lowercase().contains("adobe"), "document {i}: {}", profile_name(&app)); + let st = app.session.active().unwrap(); + assert_eq!(st.saved_revision, st.revision, "document {i} unmodified"); + } + } + + /// A sidecar is read only from a regular file of at most `MAX_XMP_BYTES`: a folder, or a file + /// one byte larger, is not read (a pipe or device named like one would never end). + #[test] + fn sidecars_are_read_from_small_regular_files_only() { + let dir = std::env::temp_dir().join(format!("photocraft-sidecar-bounded-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("folder.xmp")).unwrap(); + let cap = photocraft_io::camera_raw_xmp::MAX_XMP_BYTES; + let (fits, larger) = (dir.join("fits.xmp"), dir.join("larger.xmp")); + std::fs::write(&fits, vec![b' '; cap]).unwrap(); + std::fs::write(&larger, vec![b' '; cap + 1]).unwrap(); + let s = |p: std::path::PathBuf| p.to_string_lossy().into_owned(); + assert_eq!(read_bounded(&s(fits)).map(|b| b.len()), Some(cap)); + assert_eq!(read_bounded(&s(larger.clone())), None); + assert_eq!(read_bounded(&s(dir.join("folder.xmp"))), None); + assert_eq!(read_bounded(&s(dir.join("missing.xmp"))), None); + assert_eq!(existing_sidecar_is_ours(&s(dir.join("folder.xmp"))), Some(false), "something is there: never written over"); + assert_eq!(existing_sidecar_is_ours(&s(larger)), Some(false)); + assert_eq!(existing_sidecar_is_ours(&s(dir.join("missing.xmp"))), None); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn save_and_load_settings_round_trip_through_xmp_files() { use crate::file_dialog::FileDialogAnswer; diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index e80c5234bca..300cb20e8ae 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3860,6 +3860,7 @@ navigator Zoom Zvětšení Settings from {name} Nastavení z {name} Settings from {name}; {count} not supported: {names} Nastavení z {name}; {count} nepodporováno: {names} Could not write {name}: {error} Nelze zapsat {name}: {error} + Kept {name}: written by another application Soubor {name} ponechán: zapsala ho jiná aplikace Shadow Tint Odstín stínů # PhotoCraft release checks. Check for Updates… Zkontrolovat aktualizace… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 861a7793a2b..6ac2f998ec4 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3263,6 +3263,7 @@ curves Smooth Glätten Settings from {name} Einstellungen aus {name} Settings from {name}; {count} not supported: {names} Einstellungen aus {name}; {count} nicht unterstützt: {names} Could not write {name}: {error} {name} konnte nicht geschrieben werden: {error} + Kept {name}: written by another application {name} beibehalten: von einer anderen Anwendung geschrieben Shadow Tint Schattentönung # PhotoCraft release checks. Check for Updates… Nach Updates suchen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 0ad843e223c..c04c30366d0 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3946,6 +3946,7 @@ curves Smooth Εξομάλυνση Settings from {name} Ρυθμίσεις από {name} Settings from {name}; {count} not supported: {names} Ρυθμίσεις από {name}· {count} δεν υποστηρίζονται: {names} Could not write {name}: {error} Αδυναμία εγγραφής του {name}: {error} + Kept {name}: written by another application Το {name} διατηρήθηκε: γράφτηκε από άλλη εφαρμογή Shadow Tint Χροιά σκιών # PhotoCraft release checks. Check for Updates… Έλεγχος ενημερώσεων… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 1456f4341d0..7e32e6a6e81 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4209,6 +4209,7 @@ navigator Zoom Zoom Settings from {name} Ajustes de {name} Settings from {name}; {count} not supported: {names} Ajustes de {name}; {count} no compatibles: {names} Could not write {name}: {error} No se pudo escribir {name}: {error} + Kept {name}: written by another application Se conservó {name}: lo escribió otra aplicación Shadow Tint Tinte de sombras # PhotoCraft release checks. Check for Updates… Buscar actualizaciones… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0b29db78e5d..4f83701a498 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3256,6 +3256,7 @@ curves Smooth Lisser Settings from {name} Réglages de {name} Settings from {name}; {count} not supported: {names} Réglages de {name} ; {count} non pris en charge : {names} Could not write {name}: {error} Impossible d’écrire {name} : {error} + Kept {name}: written by another application {name} conservé : écrit par une autre application Shadow Tint Teinte des ombres # PhotoCraft release checks. Check for Updates… Rechercher des mises à jour… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 2d5bc917f3b..1de4fe989a7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4142,6 +4142,7 @@ cameraRaw Yellow Sárga Settings from {name} Beállítások innen: {name} Settings from {name}; {count} not supported: {names} Beállítások innen: {name}; {count} nem támogatott: {names} Could not write {name}: {error} Nem sikerült írni: {name}: {error} + Kept {name}: written by another application {name} megtartva: egy másik alkalmazás írta Shadow Tint Árnyék színezet Redrawing Újrarajzolás # Bevel & Emboss shading controls. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index dc9a131866d..07890313a34 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3259,6 +3259,7 @@ curves Smooth Haluskan Settings from {name} Pengaturan dari {name} Settings from {name}; {count} not supported: {names} Pengaturan dari {name}; {count} tidak didukung: {names} Could not write {name}: {error} Tidak dapat menulis {name}: {error} + Kept {name}: written by another application {name} dipertahankan: ditulis oleh aplikasi lain Shadow Tint Rona bayangan # PhotoCraft release checks. Check for Updates… Periksa Pembaruan… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index e3df1bfa643..9b84bb90fce 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4212,6 +4212,7 @@ navigator Zoom Zoom Settings from {name} Impostazioni da {name} Settings from {name}; {count} not supported: {names} Impostazioni da {name}; {count} non supportate: {names} Could not write {name}: {error} Impossibile scrivere {name}: {error} + Kept {name}: written by another application {name} mantenuto: scritto da un’altra applicazione Shadow Tint Tinta ombre # PhotoCraft release checks. Check for Updates… Cerca aggiornamenti… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 17f53e5cb9a..a463ed41104 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3927,6 +3927,7 @@ curves Smooth スムーズ Settings from {name} {name} の設定 Settings from {name}; {count} not supported: {names} {name} の設定; {count} 件は未対応: {names} Could not write {name}: {error} {name} を書き込めません: {error} + Kept {name}: written by another application {name} はそのままにしました: 別のアプリケーションが書き込んだファイルです Shadow Tint シャドウの色かぶり補正 # PhotoCraft release checks. Check for Updates… アップデートを確認… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 475ddbac378..0c5c9e8ab9a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3450,6 +3450,7 @@ curves Smooth 매끄럽게 Settings from {name} {name}의 설정 Settings from {name}; {count} not supported: {names} {name}의 설정; {count}개 미지원: {names} Could not write {name}: {error} {name}을(를) 쓸 수 없음: {error} + Kept {name}: written by another application {name}을(를) 유지함: 다른 응용 프로그램이 작성한 파일 Shadow Tint 그림자 색조 # PhotoCraft release checks. Check for Updates… 업데이트 확인… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c49f31d994a..7352ac4ed33 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4008,6 +4008,7 @@ curves Smooth Vloeiend maken Settings from {name} Instellingen uit {name} Settings from {name}; {count} not supported: {names} Instellingen uit {name}; {count} niet ondersteund: {names} Could not write {name}: {error} Kan {name} niet schrijven: {error} + Kept {name}: written by another application {name} behouden: geschreven door een andere toepassing Shadow Tint Schaduwtint # PhotoCraft release checks. Check for Updates… Controleren op updates… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 65b580cba6d..b6f83d91207 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3863,6 +3863,7 @@ curves Smooth Wygładź Settings from {name} Ustawienia z {name} Settings from {name}; {count} not supported: {names} Ustawienia z {name}; nieobsługiwane: {count}: {names} Could not write {name}: {error} Nie można zapisać {name}: {error} + Kept {name}: written by another application Zachowano {name}: zapisany przez inną aplikację Shadow Tint Tinta cieni # PhotoCraft release checks. Check for Updates… Sprawdź aktualizacje… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5ac879b17b9..397b2e128f3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4038,6 +4038,7 @@ layerLabel No Color Sem cor Settings from {name} Configurações de {name} Settings from {name}; {count} not supported: {names} Configurações de {name}; {count} sem suporte: {names} Could not write {name}: {error} Não foi possível gravar {name}: {error} + Kept {name}: written by another application {name} mantido: gravado por outro aplicativo Shadow Tint Matiz das sombras # PhotoCraft release checks. Check for Updates… Verificar atualizações… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 7ab0ad03282..6d04850b751 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3202,6 +3202,7 @@ curves Smooth Сгладить Settings from {name} Настройки из {name} Settings from {name}; {count} not supported: {names} Настройки из {name}; не поддерживается: {count}: {names} Could not write {name}: {error} Не удалось записать {name}: {error} + Kept {name}: written by another application {name} сохранён без изменений: записан другим приложением Shadow Tint Оттенок теней # History panel › History Brush source (#2966) Paints from the History panel's source state Рисует из исходного состояния панели «История» diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 0b8573b581f..3d05faff2fe 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4276,6 +4276,7 @@ shape Appearance Izgled Settings from {name} Podešavanja iz {name} Settings from {name}; {count} not supported: {names} Podešavanja iz {name}; {count} nije podržano: {names} Could not write {name}: {error} Nije moguće upisati {name}: {error} + Kept {name}: written by another application {name} je zadržan: upisala ga je druga aplikacija Shadow Tint Nijansa senki Redrawing Ponovno iscrtavanje diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b19401446c0..83bb24fdc9e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3954,6 +3954,7 @@ cameraData Lens Lens Settings from {name} {name} ayarları Settings from {name}; {count} not supported: {names} {name} ayarları; {count} desteklenmiyor: {names} Could not write {name}: {error} {name} yazılamadı: {error} + Kept {name}: written by another application {name} korundu: başka bir uygulama tarafından yazılmış Shadow Tint Gölge tonu Redrawing Yeniden çiziliyor # Bevel & Emboss shading controls. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 85963f44b8f..1c44e91b9fb 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3948,6 +3948,7 @@ curves Smooth Згладити Settings from {name} Налаштування з {name} Settings from {name}; {count} not supported: {names} Налаштування з {name}; не підтримується: {count}: {names} Could not write {name}: {error} Не вдалося записати {name}: {error} + Kept {name}: written by another application {name} залишено без змін: записаний іншою програмою Shadow Tint Відтінок тіней # PhotoCraft release checks. Check for Updates… Перевірити оновлення… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a975ac1077a..6209d75dd77 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3711,6 +3711,7 @@ curves Smooth Làm mượt Settings from {name} Thiết lập từ {name} Settings from {name}; {count} not supported: {names} Thiết lập từ {name}; {count} không được hỗ trợ: {names} Could not write {name}: {error} Không thể ghi {name}: {error} + Kept {name}: written by another application Đã giữ {name}: do ứng dụng khác ghi Shadow Tint Sắc độ bóng tối Check for Updates… Kiểm tra bản cập nhật… PhotoCraft Updates Bản cập nhật PhotoCraft diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b2ecc9d78a0..043b69281f5 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2897,6 +2897,7 @@ curves Smooth 平滑 Settings from {name} 来自 {name} 的设置 Settings from {name}; {count} not supported: {names} 来自 {name} 的设置;{count} 项不支持:{names} Could not write {name}: {error} 无法写入 {name}:{error} + Kept {name}: written by another application 已保留 {name}:由其他应用程序写入 Shadow Tint 阴影色调 # PhotoCraft release checks. Check for Updates… 检查更新… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index efb7a679e40..987afb66c52 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2861,6 +2861,7 @@ curves Smooth 平滑 Settings from {name} 來自 {name} 的設定 Settings from {name}; {count} not supported: {names} 來自 {name} 的設定;{count} 項不支援:{names} Could not write {name}: {error} 無法寫入 {name}:{error} + Kept {name}: written by another application 已保留 {name}:由其他應用程式寫入 Shadow Tint 陰影色調 # PhotoCraft release checks. Check for Updates… 檢查更新… diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4db3dc2a344..722b8ec9d77 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -899,8 +899,9 @@ pub struct PhotocraftApp { /// A raw file just opened interactively, waiting for the open-time Camera Raw dialog (shown /// on the next frame, which has the egui context). pub(crate) pending_raw_open: Option, - /// The open-time re-develop (or its Camera Raw step) running in the background. - pub(crate) raw_redevelop: Option, + /// The open-time re-develops (or their Camera Raw steps) running in the background, one per + /// raw being opened. + pub(crate) raw_redevelop: Vec, /// Filter › Adaptive Wide Angle dialog (wide_angle_ui). pub(crate) wide_angle: Option, /// ⌘Z history of each open parameter dialog (edit_history). @@ -1137,7 +1138,7 @@ impl PhotocraftApp { gradient: Default::default(), camera_raw: None, pending_raw_open: None, - raw_redevelop: None, + raw_redevelop: Vec::new(), wide_angle: None, dialog_edits: Default::default(), pending_after_prompt: None, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 98520aa7984..0eea2d5c07c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -509,11 +509,14 @@ least one level apart. Commit dispatches one `filter.cameraRaw` engine command; keeps the dialog open for correction. Nothing else writes document history. A raw file opened from a path reads its sidecar (`IMG_0001.xmp` beside `IMG_0001.CR2`, Camera -Raw's `crs:` settings) into the open-time dialog, and Open writes it back (Preferences › Camera -Raw Defaults › Write xmp sidecars; never beside a DNG). Open also applies the other Camera Raw -Defaults (colour space, bit depth, resolution, Sharpen For as a Camera Raw step, Open as Smart -Object, Apply auto tone), reported as `defaults` in the commit's reply; with "Open in Camera Raw" -off the sidecar and the defaults apply without the dialog. +Raw's `crs:` settings) into the open-time dialog, and Open writes changed settings back +(Preferences › Camera Raw Defaults › Write xmp sidecars). It never writes beside a DNG, over a +sidecar another application wrote (a notice says it was kept), or for a control or MCP request. +Open also applies the other Camera Raw Defaults (Sharpen For as part of the Camera Raw step, then +colour space, bit depth and Open as Smart Object, so the step works on the pixels the dialog +previewed; Apply auto tone fills the dialog), reported as `defaults` in the commit's reply; the +resolution is set when the file opens. With "Open in Camera Raw" off the sidecar and the defaults +apply without the dialog. **Opening a raw file.** An interactive open (File › Open, Open Recent, drag and drop, the command line) of a camera raw developed from its sensor data shows this dialog first, titled diff --git a/docs/scorecard.md b/docs/scorecard.md index 09f8c61ab9b..30239e3a223 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -7,9 +7,9 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | Area | Done | Partial | Missing | Key numbers | |---|---:|---:|---:|---| | [Performance](#performance) | 3 | 22 | 30 | 64 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 26 not run, 4 not measurable yet (baseline 2026-10-05) | -| [File compatibility](#file-compatibility) | 9 | 13 | 5 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/256, round trip ≥ 258/256 | +| [File compatibility](#file-compatibility) | 9 | 14 | 4 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/256, round trip ≥ 258/256 | | [Tools](#tools) | 36 | 8 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 20 of 177 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 15 of 178 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -116,7 +116,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu | FILE-215-8 | Large and BigTIFF import with banded decode across all IFDs | done | [#215](https://github.com/storytold/photocraft/issues/215) | codecs tiff_ifd.rs (bounds-checked IFD chain + SubIFD walk, classic and BigTIFF, cycle-safe; tiff_info / decode_tiff_page), tiff.rs banded parallel strip/tile decode, planar 1 and 2, BigTIFF write (tiff_bigtiff or > 4 GiB); io import_tiff_page; 30 MP RGB8 Deflate 345 -> 32 ms; no page picker in the UI yet | | FILE-215-9 | SVG opens and places as shape layers or a vector Smart Object | done | [#215](https://github.com/storytold/photocraft/issues/215) | io svg.rs: paths, groups, text outlines as shape layers (gradients approximated; clip/mask/filter/pattern/image subtrees rasterised); smart_cmds.rs renders an SVG source at its placement scale | | FILE-215-10 | Multi-page PDF save, PDF presentation, layer comps to PDF, vector/text output, PDF import | partial | [#215](https://github.com/storytold/photocraft/issues/215) | io pdf.rs: Save As / Save a Copy / CLI write one flattened RGB/Gray/CMYK page with ICC (#3401); print PDFs in print_cmds. Multi-page save, presentation, comps, vector/text output and PDF import (#2541) remain | -| FILE-215-11 | RAW: lossy DNG, highlight modes, .xmp sidecars, RAW prefs wired, per-camera corpus | missing | [#215](https://github.com/storytold/photocraft/issues/215) | raw sensor.rs:210 lossy DNG unsupported; raw_defaults unread; no xmp | +| FILE-215-11 | RAW: lossy DNG, highlight modes, .xmp sidecars, RAW prefs wired, per-camera corpus | partial | [#215](https://github.com/storytold/photocraft/issues/215) | 2026-10-13: lossy DNG (34892) decodes stored 8-bit samples with padded edge tiles (raw sensor.rs lossy_jpeg, #5112); a raw's sidecar IMG.xmp fills the open-time dialog and Open writes it back (camera_raw_ui.rs read_sidecar/write_sidecar, pref rawDefaults.writeXmpSidecars); every Camera Raw Defaults preference is read (colour space, bit depth, resolution, Sharpen For, Open as Smart Object, Apply auto tone: apply_raw_defaults); Calibration panel (shadow tint, primaries hue/saturation) in the dialog, the filter and the crs: keys. Still missing: highlight recovery modes, the absolute (kelvin) white balance of raw sidecars, a per-camera corpus | | FILE-215-12 | Camera Raw dialog shows a histogram; settings persist as a PSD Smart Filter | partial | [#215](https://github.com/storytold/photocraft/issues/215) | Interactive RGB/Lab scopes. PSD WB/Light/Presence, curves, HSL, grading, sharpening/noise detail, grain and numeric vignette controls mapped with descriptor preservation. Active manual Optics and unverified vignette style keep the updated ACR 18.4 fixture opaque; PSD/.pcraft saves preserve it. HDR, remaining settings and Photoshop acceptance still open | | FILE-215-13 | Video layer frames persist in .pcraft; PSD video layers mapped | partial | [#215](https://github.com/storytold/photocraft/issues/215) | format convert.rs:89 + tests/it/roundtrip.rs:282 persist frames; no PSD video mapping | | FILE-215-14 | User swatch model with ACO/ASE import and export | done | [#215](https://github.com/storytold/photocraft/issues/215) | engine presets/swatches.rs (RGB/HSB/CMYK/Lab/Gray + verbatim colour books, persisted in prefs) + swatch_cmds.rs (swatches.*); psd aco.rs (v1/v2) and ase.rs (groups, spot/global) read+write; ui swatches_ui.rs, Color Picker Add to Swatches | @@ -185,9 +185,9 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 20 of 177** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 15 of 178** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. -Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.cache_levels`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. +Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.cache_levels`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`, `integrations.allow_agent_control`, `integrations.control_port`. | Id | Target | Status | Issue | Note | |---|---|---|---|---|