diff --git a/Cargo.lock b/Cargo.lock index 79e7cd895e..6820d6dee5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4397,6 +4397,7 @@ dependencies = [ "blake3", "crc32fast", "flate2", + "libc", "photocraft-codecs", "photocraft-color", "photocraft-doc", diff --git a/contributors/people.toml b/contributors/people.toml index 30ba09061c..cdfbc95b1c 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -155,6 +155,10 @@ sync_github_name = true display_name = "VanTan" sync_github_name = false +[people.yeniufuklar-com] +real_name = "Ufuk Efe" +sync_github_name = true + [people.LorenzoFasolino] real_name = "Lorenzo Fasolino" display_name = "Lorenzo Fasolino" diff --git a/crates/algo/src/segment/maxflow/push_relabel.rs b/crates/algo/src/segment/maxflow/push_relabel.rs index 914645d4c9..1041f9ef51 100644 --- a/crates/algo/src/segment/maxflow/push_relabel.rs +++ b/crates/algo/src/segment/maxflow/push_relabel.rs @@ -71,7 +71,10 @@ impl Graph { let ai = a as usize; let j = self.head[ai] as usize; work += 1; - if self.r_cap[ai] > EPS && self.dist[i] == self.dist[j].saturating_add(1) { + // `checked_add`: two nodes a global relabel left unreachable (`u32::MAX`) must + // not count as admissible for each other, or float-stranded excess ping-pongs + // between them forever. + if self.r_cap[ai] > EPS && self.dist[j].checked_add(1) == Some(self.dist[i]) { let delta = (excess[i] as f32).min(self.r_cap[ai]); self.r_cap[ai] -= delta; self.r_cap[ai ^ 1] += delta; diff --git a/crates/algo/src/segment/maxflow/push_relabel/tests.rs b/crates/algo/src/segment/maxflow/push_relabel/tests.rs index 6c7141572e..ce0c0b8628 100644 --- a/crates/algo/src/segment/maxflow/push_relabel/tests.rs +++ b/crates/algo/src/segment/maxflow/push_relabel/tests.rs @@ -179,3 +179,28 @@ fn solver_workload_release_comparison() { } } } + +#[test] +fn stranded_excess_terminates_and_matches_bk() { + // Source capacities far beyond f32 precision (ulp 32 at 3e8) next to small links: rounding + // strands excess on nodes a global relabel finds reachable from neither terminal. Those + // nodes (height u32::MAX) used to count as admissible for each other and pushed the excess + // back and forth forever (Remove Background never finished on some photos). + let mut g = Graph::with_capacity(6, 7); + for (i, &(s, t)) in [(33123824.0, 0.0), (347622050.0, 0.0), (0.0, 5539047.5), (76592.22, 0.0), (3514.0022, 0.0), (0.0, 13670.268)].iter().enumerate() { + g.add_tweights(i, s, t); + } + for (i, j, c) in [(0, 1, 0.0), (0, 3, 0.0007301044), (1, 2, 2.803e-42), (1, 4, 8.160078), (2, 5, 3.1224866e-7), (3, 4, 28.512966), (4, 5, 4.099367)] { + g.add_edge(i, j, c, c); + } + let mut bk = g.clone(); + let checks = std::cell::Cell::new(0); + let cancel = || { + checks.set(checks.get() + 1); + checks.get() > 1000 + }; + let flow = g.push_relabel(&cancel).expect("push/relabel did not terminate"); + let bk_flow = bk.maxflow_bk(); + assert!((flow - bk_flow).abs() <= 1e-6 * bk_flow, "{flow} vs {bk_flow}"); + assert_eq!((0..6).map(|i| g.in_source(i)).collect::>(), (0..6).map(|i| bk.in_source(i)).collect::>()); +} diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs index 2544a1066d..885af6e29f 100644 --- a/crates/codecs/src/codecs/png.rs +++ b/crates/codecs/src/codecs/png.rs @@ -17,6 +17,15 @@ fn err(e: impl std::fmt::Display) -> CodecError { CodecError::malformed(F, e) } +/// Pixels per inch for `pHYs` pixels per metre. A whole number of ppi is stored rounded to whole +/// pixels per metre (300 ppi = 11811), so reading it back gives 299.9994: the whole number that +/// rounds to the stored value is the resolution that was meant, as Photoshop reads it. +pub(crate) fn dpi_of_ppm(ppm: u32) -> f32 { + let dpi = f64::from(ppm) * f64::from(METERS_PER_INCH); + let whole = dpi.round(); + if (whole / f64::from(METERS_PER_INCH)).round() == f64::from(ppm) { whole as f32 } else { dpi as f32 } +} + pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { let mut input = Cursor::new(bytes); let mut decoder = png::Decoder::new_with_limits(&mut input, png::Limits { bytes: limits.alloc_usize() }); @@ -74,7 +83,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result && d.xppu > 0 && d.yppu > 0 { - meta.dpi = Some((d.xppu as f32 * METERS_PER_INCH, d.yppu as f32 * METERS_PER_INCH)); + meta.dpi = Some((dpi_of_ppm(d.xppu), dpi_of_ppm(d.yppu))); } drop(reader); let end = usize::try_from(input.position()).map_err(|_| err("invalid PNG reader position"))?; diff --git a/crates/codecs/src/options.rs b/crates/codecs/src/options.rs index b955e42d3f..eee5b38c0a 100644 --- a/crates/codecs/src/options.rs +++ b/crates/codecs/src/options.rs @@ -100,12 +100,13 @@ pub enum PngCompression { Best, } -/// TIFF strip compression. +/// TIFF strip compression. The default is none, as in Photoshop: uncompressed strips are the +/// only kind every TIFF reader opens (Deflate and the predictor are not baseline TIFF, #4484). #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum TiffCompression { + #[default] None, Lzw, - #[default] Deflate, PackBits, } @@ -190,7 +191,7 @@ impl Default for EncodeOptions { png_interlaced: false, webp_lossless: true, webp_quality: 80, - tiff_compression: TiffCompression::Deflate, + tiff_compression: TiffCompression::None, tiff_bigtiff: false, exr_compression: ExrCompression::Zip16, dpx_bits: None, diff --git a/crates/codecs/src/web.rs b/crates/codecs/src/web.rs index f48de8634d..584ceb9d6e 100644 --- a/crates/codecs/src/web.rs +++ b/crates/codecs/src/web.rs @@ -307,7 +307,9 @@ pub fn encode_jpeg_rgb8( } let mut out = Vec::new(); let mut enc = jpeg_encoder::Encoder::new(&mut out, quality.clamp(1, 100)); - let subsampled = quality < 90; + // Like Photoshop's Save for Web: 4:2:0 chroma up to quality 50, 4:4:4 from 51 (measured on + // Photoshop 2025's output; its Save As keeps 4:2:0 at every quality). + let subsampled = quality <= 50; enc.set_progressive(progressive); // jpeg-encoder 0.6 writes corrupt baseline scans when optimised Huffman tables meet 4:2:0 // (both zune-jpeg and image-rs decode them green); progressive output is fine. @@ -345,6 +347,24 @@ mod tests { (0..w * h).map(|i| (((i % w) * 7 + (i / w) * 13 + (i * i) % 5) % n) as u8).collect() } + /// The luma sampling factors (h, v) of a baseline or progressive JPEG. + fn luma_sampling(bytes: &[u8]) -> Option<(u8, u8)> { + let i = bytes.windows(2).position(|w| w[0] == 0xFF && matches!(w[1], 0xC0..=0xC2))?; + let f = *bytes.get(i + 11)?; + Some((f >> 4, f & 15)) + } + + #[test] + fn jpeg_chroma_is_full_above_quality_50() { + let rgb: Vec = (0..16 * 16 * 3).map(|i| (i * 37 % 256) as u8).collect(); + for (q, want) in [(1, (2, 2)), (50, (2, 2)), (51, (1, 1)), (60, (1, 1)), (89, (1, 1)), (100, (1, 1))] { + for progressive in [false, true] { + let bytes = encode_jpeg_rgb8(16, 16, &rgb, q, progressive, false, None, None, None).unwrap(); + assert_eq!(luma_sampling(&bytes), Some(want), "quality {q} progressive {progressive}"); + } + } + } + #[test] fn gif_roundtrips_through_the_decoder() { let pal: Vec<[u8; 3]> = (0..200).map(|i| [i as u8, (255 - i) as u8, (i * 3 % 256) as u8]).collect(); diff --git a/crates/codecs/tests/resolution.rs b/crates/codecs/tests/resolution.rs index 5eb6acad3a..15ddc95749 100644 --- a/crates/codecs/tests/resolution.rs +++ b/crates/codecs/tests/resolution.rs @@ -425,16 +425,38 @@ fn png_phys_outranks_its_exif() { img.meta.exif = Some(camera_exif(&LE)); let png = encode(&img, Format::Png, &EncodeOptions::default()).unwrap(); near(decode(&png).unwrap().meta.dpi, 300.0); + near(decode(&with_phys(&png, 5906)).unwrap().meta.dpi, 150.0); +} + +/// `png` with a `pHYs` chunk of `ppm` pixels per metre after IHDR. +fn with_phys(png: &[u8], ppm: u32) -> Vec { let mut body = b"pHYs".to_vec(); - body.extend_from_slice(&5906u32.to_be_bytes()); - body.extend_from_slice(&5906u32.to_be_bytes()); + body.extend_from_slice(&ppm.to_be_bytes()); + body.extend_from_slice(&ppm.to_be_bytes()); body.push(1); let mut chunk = 9u32.to_be_bytes().to_vec(); chunk.extend_from_slice(&body); chunk.extend_from_slice(&crc32(&body).to_be_bytes()); let ihdr_end = 8 + 8 + 13 + 4; - let with_phys = [&png[..ihdr_end], &chunk, &png[ihdr_end..]].concat(); - near(decode(&with_phys).unwrap().meta.dpi, 150.0114); + [&png[..ihdr_end], &chunk, &png[ihdr_end..]].concat() +} + +#[test] +fn png_phys_of_a_whole_ppi_reads_back_whole() { + // pHYs holds whole pixels per metre: 300 ppi is stored as 11811 (299.9994 ppi), 72 as 2835 + // (72.009). The whole number that rounds to the stored value is read, as Photoshop does; a + // value no whole ppi rounds to stays as it is. + let img = Image::from_raw(4, 4, ChannelLayout::Rgb, SampleType::U8, vec![90; 48]).unwrap(); + let png = encode(&img, Format::Png, &EncodeOptions { embed_metadata: false, ..Default::default() }).unwrap(); + for (ppm, want) in [(11811, 300.0), (2835, 72.0), (3937, 100.0), (11812, 300.0248)] { + let (x, y) = decode(&with_phys(&png, ppm)).unwrap().meta.dpi.unwrap(); + assert!((x - want).abs() < 1e-4 && (y - want).abs() < 1e-4, "{ppm} px/m: {x} × {y}, wanted {want}"); + } + // And a 300 ppi PNG written by the encoder opens at exactly 300. + let mut img = img; + img.meta.dpi = Some((300.0, 300.0)); + let png = encode(&img, Format::Png, &EncodeOptions::default()).unwrap(); + assert_eq!(decode(&png).unwrap().meta.dpi, Some((300.0, 300.0))); } /// `camera_exif` plus IFD1, the embedded thumbnail a camera (or the last editor) wrote: diff --git a/crates/codecs/tests/tiff_regressions.rs b/crates/codecs/tests/tiff_regressions.rs index a7c1aa486e..d823f33f4a 100644 --- a/crates/codecs/tests/tiff_regressions.rs +++ b/crates/codecs/tests/tiff_regressions.rs @@ -150,3 +150,27 @@ fn ccitt_group4_tiff_decodes() { assert_ne!(d[0], d[8], "{d:?}"); assert_eq!(d[0], 255, "white row of a WhiteIsZero image"); } + +/// #4484: a TIFF saved with the default options must open in software that only reads +/// baseline TIFF (embroidery and plotter tools, older readers). Like Photoshop's default, that +/// means uncompressed strips with no predictor, classic offsets and unassociated alpha. +#[test] +fn default_tiff_is_baseline() { + use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, SampleType, encode}; + use std::io::Cursor; + use tiff::tags::Tag; + + for layout in [ChannelLayout::Rgb, ChannelLayout::Rgba] { + let img = common::synth(33, 21, layout, SampleType::U8, 7, 0.4); + let bytes = encode(&img, Format::Tiff, &EncodeOptions::default()).expect("encode"); + assert!(bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*"), "{layout:?}: not a classic TIFF"); + let mut dec = tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).expect("open"); + assert_eq!(dec.get_tag_u32(Tag::Compression).ok(), Some(1), "{layout:?}: Compression"); + assert_eq!(dec.find_tag(Tag::Predictor).ok().flatten().and_then(|v| v.into_u16().ok()).unwrap_or(1), 1, "{layout:?}: Predictor"); + assert!(dec.find_tag(Tag::TileWidth).ok().flatten().is_none(), "{layout:?}: tiled"); + assert_eq!(dec.get_tag_u32(Tag::PlanarConfiguration).ok().unwrap_or(1), 1, "{layout:?}: planar"); + let extra = dec.find_tag(Tag::ExtraSamples).ok().flatten().and_then(|v| v.into_u16_vec().ok()); + assert_eq!(extra, if layout == ChannelLayout::Rgba { Some(vec![2]) } else { None }, "{layout:?}: ExtraSamples"); + assert_eq!(decode(&bytes).expect("decode").data(), img.data(), "{layout:?}: round trip"); + } +} diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index 4366ab0a0d..22a8cf063a 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -605,8 +605,9 @@ const BALANCE_LEVELS: f32 = 0.39; /// - Preserve Luminosity off: a slider only moves its own channel. Midtones is gamma 2^−a. /// Shadows is gamma 2^(−a/2) after a black point at 0.39·|a| when lowered; highlights is /// gamma 2^(−a/2) after a white point at 1 − 0.39·a when raised. -/// - Preserve Luminosity on: midtones is gamma 2^(−a/2) on the slider's channel and 2^(a/2) on -/// the other two. Shadows and highlights go by the differences between a tone's three sliders: +/// - Preserve Luminosity on: midtones uses gamma 2^((max(a) + min(a))/2 − a_ch), +/// preserving the one-slider behaviour without summing offsets when multiple sliders move. +/// Shadows and highlights go by the differences between a tone's three sliders: /// each channel gets a plain black point at 0.39·(max − its own) for shadows and a plain white /// point at 1 − 0.39·(its own − min) for highlights (so one raised shadows slider darkens the /// other two channels, and two raised together darken only the third). @@ -620,28 +621,27 @@ pub fn color_balance_channel(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch let mut v = v.clamp(0.0, 1.0); for (tone, sliders) in [(2, highlights), (0, shadows), (1, midtones)] { let a: [f32; 3] = sliders.map(|s| (s / 100.0).clamp(-1.0, 1.0)); - if preserve_luminosity && tone != 1 { + if preserve_luminosity { let own = a.get(ch).copied().unwrap_or(0.0); let (lo, hi) = a.iter().fold((f32::MAX, f32::MIN), |m, x| (m.0.min(*x), m.1.max(*x))); - v = if tone == 0 { black(v, BALANCE_LEVELS * (hi - own)) } else { white(v, 1.0 - BALANCE_LEVELS * (own - lo)) }; + v = match tone { + 0 => black(v, BALANCE_LEVELS * (hi - own)), + 1 => v.powf(2f32.powf((hi + lo) / 2.0 - own)), + _ => white(v, 1.0 - BALANCE_LEVELS * (own - lo)), + }; continue; } for (src, slider) in sliders.iter().enumerate() { let a = (slider / 100.0).clamp(-1.0, 1.0); - let own = src == ch; - if a == 0.0 || (!preserve_luminosity && !own) { + if a == 0.0 || src != ch { continue; } - v = match (tone, preserve_luminosity) { - (1, false) => v.powf(2f32.powf(-a)), - (1, true) => v.powf(2f32.powf(if own { -a } else { a } / 2.0)), - (0, false) if a < 0.0 => black(v, BALANCE_LEVELS * -a).powf(2f32.powf(-a / 2.0)), - (0, false) => v.powf(2f32.powf(-a / 2.0)), - - (2, false) if a > 0.0 => white(v, 1.0 - BALANCE_LEVELS * a).powf(2f32.powf(-a / 2.0)), - (2, false) => v.powf(2f32.powf(-a / 2.0)), - - _ => v, + v = match tone { + 1 => v.powf(2f32.powf(-a)), + 0 if a < 0.0 => black(v, BALANCE_LEVELS * -a).powf(2f32.powf(-a / 2.0)), + 0 => v.powf(2f32.powf(-a / 2.0)), + 2 if a > 0.0 => white(v, 1.0 - BALANCE_LEVELS * a).powf(2f32.powf(-a / 2.0)), + _ => v.powf(2f32.powf(-a / 2.0)), }; } } @@ -1254,6 +1254,26 @@ mod tone_tests { } } + #[test] + fn color_balance_midtones_with_multiple_sliders_preserve_luminosity() { + // A shared offset depends on the two extremes, not the sum of moved sliders. + // The old per-slider product leaves red/blue unchanged for [30, 0, 30]. + let tones = [[0.0; 3], [30.0, 0.0, 30.0], [0.0; 3]]; + for input in [0.25_f32, 0.5, 0.75] { + for (ch, offset) in [-0.15_f32, 0.15, -0.15].into_iter().enumerate() { + let expected = input.powf(2f32.powf(offset)); + let actual = color_balance_channel(tones, true, ch, input); + assert!((actual - expected).abs() < 1e-6, "channel {ch}, input {input}: {actual} vs {expected}"); + } + // Preserve Luminosity off must still affect only the moved channels. + assert_eq!(color_balance_channel(tones, false, 1, input), input); + // One moved slider retains its previous half-strength compensation. + let single = [[0.0; 3], [30.0, 0.0, 0.0], [0.0; 3]]; + assert!((color_balance_channel(single, true, 0, input) - input.powf(2f32.powf(-0.15))).abs() < 1e-6); + assert!((color_balance_channel(single, true, 1, input) - input.powf(2f32.powf(0.15))).abs() < 1e-6); + } + } + #[test] fn levels_and_curves_apply_each_channel_before_the_master() { // These two affine tone adjustments describe the same mapping: diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 378f71c18e..1dc82005db 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -58,7 +58,7 @@ choice!(ColorPicker { Adobe = "adobe", System = "system" } default Adobe); choice!(Theme { Pro = "pro", ProMedium = "proMedium", ProLightGray = "proLightGray", ProLight = "proLight", Studio = "studio", StudioLight = "studioLight", Classic = "classic", SolarizedDark = "solarizedDark", Adwaita = "adwaita", AdwaitaDark = "adwaitaDark", BreezeLight = "breezeLight", BreezeDark = "breezeDark", SoftDark = "softDark", SoftLight = "softLight" } default ProMedium); choice!(AppearanceMode { Auto = "auto", Dark = "dark", Light = "light" } default Dark); choice!(DarkTheme { Pro = "pro", ProMedium = "proMedium", Studio = "studio", SolarizedDark = "solarizedDark", AdwaitaDark = "adwaitaDark", BreezeDark = "breezeDark", SoftDark = "softDark" } default ProMedium); -choice!(LightTheme { StudioLight = "studioLight", ProLightGray = "proLightGray", ProLight = "proLight", Classic = "classic", Adwaita = "adwaita", BreezeLight = "breezeLight", SoftLight = "softLight" } default StudioLight); +choice!(LightTheme { ProLight = "proLight", ProLightGray = "proLightGray", StudioLight = "studioLight", Classic = "classic", Adwaita = "adwaita", BreezeLight = "breezeLight", SoftLight = "softLight" } default ProLight); choice!(CanvasColor { Default = "default", Black = "black", DarkGray = "darkGray", MediumGray = "mediumGray", LightGray = "lightGray", Custom = "custom" } default Default); choice!(CanvasBorder { DropShadow = "dropShadow", Line = "line", None = "none" } default DropShadow); choice!(UiScale { Auto = "auto", P75 = "75", P80 = "80", P85 = "85", P90 = "90", P95 = "95", P100 = "100", P125 = "125", P150 = "150", P175 = "175", P200 = "200", P250 = "250", P300 = "300" } default Auto); @@ -293,7 +293,7 @@ impl Default for Interface { theme: Theme::ProMedium, appearance_mode: AppearanceMode::Dark, dark_theme: DarkTheme::ProMedium, - light_theme: LightTheme::StudioLight, + light_theme: LightTheme::ProLight, favorite_themes: Vec::new(), canvas_color: CanvasColor::Default, canvas_custom_color: "#282828".into(), diff --git a/crates/engine/src/prefs/tests.rs b/crates/engine/src/prefs/tests.rs index 6bb34a9706..36a5b69abc 100644 --- a/crates/engine/src/prefs/tests.rs +++ b/crates/engine/src/prefs/tests.rs @@ -55,9 +55,9 @@ fn appearance_defaults_and_legacy_theme_migrate() { // New users keep Photoshop's default; following the system is opt-in. assert_eq!(p.interface.appearance_mode, AppearanceMode::Dark); assert_eq!(p.interface.dark_theme, DarkTheme::ProMedium); - assert_eq!(p.interface.light_theme, LightTheme::StudioLight); + assert_eq!(p.interface.light_theme, LightTheme::ProLight); for (theme, mode, dark, light) in - [("pro", AppearanceMode::Dark, DarkTheme::Pro, LightTheme::StudioLight), ("classic", AppearanceMode::Light, DarkTheme::ProMedium, LightTheme::Classic)] + [("pro", AppearanceMode::Dark, DarkTheme::Pro, LightTheme::ProLight), ("classic", AppearanceMode::Light, DarkTheme::ProMedium, LightTheme::Classic)] { let mut s = Session::new(); s.load_prefs_json(&json!({"interface": {"theme": theme}}).to_string()).unwrap(); diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 00a41ac070..45d7a4ccf3 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -24,10 +24,15 @@ crc32fast = "1.5" blake3 = { version = "1.8", default-features = false, features = ["pure"] } ruzstd = "0.9" -# A plain fsync where a file system refuses the full flush (`sync_file`, atomic.rs). Already in -# Cargo.lock on Apple targets (cap-std), so this adds no new crate. -[target.'cfg(target_vendor = "apple")'.dependencies] +# Unix directory cleanup uses no-follow descriptor-relative operations; the same +# dependency provides the plain-fsync fallback on Apple file systems. +[target.'cfg(unix)'.dependencies] rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } +# rustix does not expose Apple's directory-search open mode. Only the named +# constant is used; all descriptor operations remain in safe rustix APIs. +[target.'cfg(target_vendor = "apple")'.dependencies] +libc = "0.2" + [dev-dependencies] proptest = { workspace = true } diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index c14b488250..d047668cb0 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -570,10 +570,82 @@ fn write_bundle_file(root: &Path, path: &Path, data: &[u8]) -> Result<()> { result } -fn remove_bundle_file(root: &Path, path: &Path) -> Result<()> { +/// Keep the existing leaf/path validation and pin the actual unlink to opened +/// directory handles on Unix. This closes the check-then-remove path-swap gap. +fn remove_bundle_file(root: &Path, path: &Path, gc: &BundleGc) -> Result<()> { validate_bundle_file(root, path)?; - std::fs::remove_file(path)?; - Ok(()) + let relative = path.strip_prefix(root).map_err(|_| unsafe_bundle_entry(path))?; + gc.remove(relative) +} + +#[cfg(unix)] +struct BundleGc { + root: rustix::fd::OwnedFd, + tiles: rustix::fd::OwnedFd, + blobs: rustix::fd::OwnedFd, + composite: rustix::fd::OwnedFd, +} + +#[cfg(unix)] +fn gc_directory_flags() -> rustix::fs::OFlags { + use rustix::fs::OFlags; + + // GC needs directory traversal, not permission to read a directory listing. + // Both modes retain a descriptor for the directory opened here, so a later + // pathname replacement cannot redirect descriptor-relative cleanup. + #[cfg(any(target_os = "linux", target_os = "android"))] + let access = OFlags::PATH; + #[cfg(target_vendor = "apple")] + let access = OFlags::from_bits_retain(libc::O_SEARCH.cast_unsigned()); + #[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))] + let access = OFlags::RDONLY; + access | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC +} + +#[cfg(unix)] +impl BundleGc { + fn new(root: &Path) -> Result { + use rustix::fs::{Mode, open, openat}; + + let flags = gc_directory_flags(); + let root = open(root, flags, Mode::empty()).map_err(std::io::Error::from)?; + let tiles = openat(&root, "tiles", flags, Mode::empty()).map_err(std::io::Error::from)?; + let blobs = openat(&root, "blobs", flags, Mode::empty()).map_err(std::io::Error::from)?; + let composite = openat(&root, "composite", flags, Mode::empty()).map_err(std::io::Error::from)?; + Ok(Self { root, tiles, blobs, composite }) + } + + fn remove(&self, relative: &Path) -> Result<()> { + let relative = relative.to_str().ok_or_else(|| unsafe_bundle_entry(relative))?; + let (handle, name) = match relative { + THUMB => (&self.root, THUMB), + COMPOSITE => (&self.composite, "preview.png"), + _ => match relative.split_once('/') { + Some(("tiles", name)) if name.strip_suffix(".zst").is_some_and(is_valid_hash) => (&self.tiles, name), + Some(("blobs", name)) if name.strip_suffix(".zst").is_some_and(is_valid_hash) => (&self.blobs, name), + _ => return Err(FormatError::Unsupported(format!("invalid bundle cleanup target: {relative}"))), + }, + }; + rustix::fs::unlinkat(handle, name, rustix::fs::AtFlags::empty()).map_err(std::io::Error::from)?; + Ok(()) + } +} + +#[cfg(not(unix))] +struct BundleGc { + root: PathBuf, +} + +#[cfg(not(unix))] +impl BundleGc { + fn new(root: &Path) -> Result { + Ok(Self { root: root.to_path_buf() }) + } + + fn remove(&self, relative: &Path) -> Result<()> { + std::fs::remove_file(self.root.join(relative))?; + Ok(()) + } } fn existing_object_is_valid(path: &Path, object: &Object, what: &str) -> Result<(bool, Option)> { @@ -802,11 +874,14 @@ impl PcraftWriter { for (name, data) in &p.previews { write_bundle_file(dir, &dir.join(name), data)?; } + // Pin all GC directories before removing stale previews or objects. + // Unix cleanup then stays within these directories even if a pathname is swapped. + let gc = BundleGc::new(dir)?; for stale in [THUMB, COMPOSITE] { if !p.previews.iter().any(|(n, _)| *n == stale) { let path = dir.join(stale); validate_bundle_file(dir, &path)?; - match remove_bundle_file(dir, &path) { + match remove_bundle_file(dir, &path, &gc) { Err(FormatError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {} other => other?, } @@ -818,7 +893,7 @@ impl PcraftWriter { // complete save into a reported failure); a leftover is retried on the next save. for path in existing { if !p.objects.contains_key(&path) { - if remove_bundle_file(dir, &dir.join(&path)).is_ok() { + if remove_bundle_file(dir, &dir.join(&path), &gc).is_ok() { stats.objects_removed += 1; } if let Some(cache) = &mut self.verified_directory { @@ -866,6 +941,36 @@ impl PcraftWriter { } } +#[cfg(all(test, unix))] +#[test] +fn gc_pinned_directory_handles_resist_subdirectory_swap() { + use std::os::unix::fs::symlink; + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(0); + let root = std::env::temp_dir().join(format!("pcraft-gc-swap-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let bundle = root.join("project.pcraft"); + let outside = root.join("outside"); + for sub in ["tiles", "blobs", "composite"] { + std::fs::create_dir_all(bundle.join(sub)).unwrap(); + } + std::fs::create_dir(&outside).unwrap(); + let filename = format!("{}.zst", "c".repeat(64)); + std::fs::write(bundle.join("tiles").join(&filename), b"stale bundle file").unwrap(); + std::fs::write(outside.join(&filename), b"outside file must survive").unwrap(); + + let gc = BundleGc::new(&bundle).unwrap(); + std::fs::rename(bundle.join("tiles"), bundle.join("old-tiles")).unwrap(); + symlink(&outside, bundle.join("tiles")).unwrap(); + + // Exercise the descriptor-relative unlink directly: the public save path + // also validates the leaf, but that check itself cannot prevent a later swap. + gc.remove(Path::new(&format!("tiles/{filename}"))).unwrap(); + assert!(!bundle.join("old-tiles").join(&filename).exists()); + assert_eq!(std::fs::read(outside.join(&filename)).unwrap(), b"outside file must survive"); + std::fs::remove_dir_all(root).unwrap(); +} + fn list_objects(dir: &Path) -> Result> { let mut out = HashSet::new(); for sub in ["tiles", "blobs"] { @@ -878,7 +983,7 @@ fn list_objects(dir: &Path) -> Result> { for e in rd { let e = e?; let name = e.file_name().to_string_lossy().into_owned(); - if name.ends_with(".zst") { + if name.strip_suffix(".zst").is_some_and(is_valid_hash) { let path = e.path(); match std::fs::symlink_metadata(&path) { Ok(metadata) if metadata.file_type().is_symlink() => return Err(unsafe_bundle_entry(&path)), diff --git a/crates/format/tests/directory_symlinks.rs b/crates/format/tests/directory_symlinks.rs new file mode 100644 index 0000000000..0302593f49 --- /dev/null +++ b/crates/format/tests/directory_symlinks.rs @@ -0,0 +1,176 @@ +//! Directory cleanup only owns content-addressed objects; unrelated files survive. + +mod common; + +use common::temp_dir; +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::Document; +use photocraft_format::{PcraftWriter, SaveOptions}; +use photocraft_geom::Size; + +fn empty_doc() -> Document { + Document::new("clean", Size::new(1, 1), ColorMode::Rgb, SampleType::U8) +} + +#[test] +fn directory_cleanup_preserves_unrelated_zst_files() { + let root = temp_dir("unrelated-object"); + let bundle = root.join("project.pcraft"); + let mut writer = PcraftWriter::new(); + writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); + + let unrelated = bundle.join("tiles/personal-notes.zst"); + let orphan = bundle.join("blobs").join(format!("{}.zst", "b".repeat(64))); + std::fs::write(&unrelated, b"unrelated file").unwrap(); + std::fs::write(&orphan, b"unused content-addressed object").unwrap(); + + let stats = writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); + assert_eq!(std::fs::read(&unrelated).unwrap(), b"unrelated file"); + assert!(!orphan.exists(), "a valid but unreferenced object is removed"); + assert_eq!(stats.objects_removed, 1); + std::fs::remove_dir_all(root).unwrap(); +} + +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] +mod permissions { + use super::*; + use photocraft_format::load_path; + use photocraft_raster::Rgba8Image; + use std::os::unix::fs::{PermissionsExt, symlink}; + use std::path::{Path, PathBuf}; + + struct RestoreMode { + path: PathBuf, + permissions: std::fs::Permissions, + } + + impl RestoreMode { + fn set(path: &Path, mode: u32) -> Self { + let permissions = std::fs::metadata(path).unwrap().permissions(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap(); + Self { path: path.to_path_buf(), permissions } + } + } + + impl Drop for RestoreMode { + fn drop(&mut self) { + let _ = std::fs::set_permissions(&self.path, self.permissions.clone()); + } + } + + #[test] + fn directory_save_without_previews_does_not_require_composite_read_permission() { + let root = temp_dir("composite-search-only"); + let bundle = root.join("project.pcraft"); + let mut writer = PcraftWriter::new(); + writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); + let restricted = RestoreMode::set(&bundle.join("composite"), 0o300); + let mut changed = empty_doc(); + changed.name = "saved without previews".into(); + let result = writer.save_dir(&changed, &bundle, &SaveOptions::default()); + drop(restricted); + result.expect("saving without previews does not read composite"); + assert_eq!(load_path(&bundle).unwrap(), changed); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn directory_save_cleans_stale_previews_through_search_only_root_and_composite() { + let root = temp_dir("bundle-search-only"); + let bundle = root.join("project.pcraft"); + let link = root.join("linked.pcraft"); + let mut writer = PcraftWriter::new(); + writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); + symlink(&bundle, &link).unwrap(); + std::fs::write(bundle.join("thumb.png"), b"stale thumbnail").unwrap(); + std::fs::write(bundle.join("composite/preview.png"), b"stale composite").unwrap(); + let orphan = bundle.join("blobs").join(format!("{}.zst", "a".repeat(64))); + std::fs::write(&orphan, b"unreferenced object").unwrap(); + let composite_mode = RestoreMode::set(&bundle.join("composite"), 0o300); + let root_mode = RestoreMode::set(&bundle, 0o300); + let mut changed = empty_doc(); + changed.name = "saved through linked root".into(); + let result = writer.save_dir(&changed, &link, &SaveOptions::default()); + drop(root_mode); + drop(composite_mode); + let stats = result.expect("cleanup needs directory traversal and write permission, not read"); + assert_eq!(stats.objects_removed, 1); + assert!(!orphan.exists()); + assert!(!bundle.join("thumb.png").exists()); + assert!(!bundle.join("composite/preview.png").exists()); + assert_eq!(load_path(&bundle).unwrap(), changed); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn directory_save_writes_current_preview_without_composite_read_permission() { + let root = temp_dir("preview-search-only"); + let bundle = root.join("project.pcraft"); + let mut writer = PcraftWriter::new(); + writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); + let restricted = RestoreMode::set(&bundle.join("composite"), 0o300); + let mut changed = empty_doc(); + changed.name = "saved with preview".into(); + let opts = SaveOptions { composite: Some(Rgba8Image::new(2, 2)), ..Default::default() }; + let result = writer.save_dir(&changed, &bundle, &opts); + drop(restricted); + result.expect("writing a preview does not require listing its directory"); + assert!(std::fs::read(bundle.join("composite/preview.png")).unwrap().starts_with(b"\x89PNG\r\n\x1a\n")); + assert_eq!(load_path(&bundle).unwrap(), changed); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn denied_stale_preview_cleanup_preserves_the_previous_manifest() { + let root = temp_dir("denied-preview-cleanup"); + let bundle = root.join("project.pcraft"); + let mut writer = PcraftWriter::new(); + let original = empty_doc(); + writer.save_dir(&original, &bundle, &SaveOptions::default()).unwrap(); + let preview = bundle.join("composite/preview.png"); + std::fs::write(&preview, b"stale composite").unwrap(); + let restricted = RestoreMode::set(&bundle.join("composite"), 0o500); + let permission_probe = bundle.join("composite/permission-probe"); + if std::fs::write(&permission_probe, b"probe").is_ok() { + // An elevated test process may bypass directory permissions. + std::fs::remove_file(permission_probe).unwrap(); + drop(restricted); + std::fs::remove_dir_all(root).unwrap(); + return; + } + let mut changed = empty_doc(); + changed.name = "must not commit".into(); + let result = writer.save_dir(&changed, &bundle, &SaveOptions::default()); + drop(restricted); + assert!(result.is_err(), "a required pre-commit cleanup failure is reported"); + assert_eq!(std::fs::read(preview).unwrap(), b"stale composite"); + assert_eq!(load_path(&bundle).unwrap(), original); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn denied_object_cleanup_remains_best_effort_after_manifest_commit() { + let root = temp_dir("denied-object-cleanup"); + let bundle = root.join("project.pcraft"); + let mut writer = PcraftWriter::new(); + writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); + let orphan = bundle.join("tiles").join(format!("{}.zst", "d".repeat(64))); + std::fs::write(&orphan, b"unreferenced object").unwrap(); + let restricted = RestoreMode::set(&bundle.join("tiles"), 0o500); + let permission_probe = bundle.join("tiles/permission-probe"); + if std::fs::write(&permission_probe, b"probe").is_ok() { + std::fs::remove_file(permission_probe).unwrap(); + drop(restricted); + std::fs::remove_dir_all(root).unwrap(); + return; + } + let mut changed = empty_doc(); + changed.name = "committed despite housekeeping failure".into(); + let result = writer.save_dir(&changed, &bundle, &SaveOptions::default()); + drop(restricted); + assert_eq!(result.unwrap().objects_removed, 0); + assert!(orphan.exists()); + assert_eq!(load_path(&bundle).unwrap(), changed); + std::fs::remove_dir_all(root).unwrap(); + } +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index cd2c77491f..279c316adc 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -845,6 +845,26 @@ impl Compositor { self.prefix.forget(doc); } + /// [`Self::forget_doc`] for every document `keep` rejects: what the compositor holds for + /// documents that were closed, however their canvas entry went (#4529). + pub fn retain_docs(&mut self, keep: impl Fn(DocId) -> bool) { + let mut gone: Vec = + self.residents.values().map(|r| r.doc).chain(self.fx.values().map(|e| e.doc)).chain(self.prefix.doc()).filter(|d| !keep(*d)).collect(); + gone.sort_by_key(|d| d.0); + gone.dedup(); + for d in gone { + self.forget_doc(d); + } + } + + /// Documents the compositor holds pages, effect maps or a lower-stack composite for. + pub fn held_docs(&self) -> Vec { + let mut docs: Vec = self.residents.values().map(|r| r.doc).chain(self.fx.values().map(|e| e.doc)).chain(self.prefix.doc()).collect(); + docs.sort_by_key(|d| d.0); + docs.dedup(); + docs + } + /// GPU memory held by cached effect maps (bytes). pub fn fx_cache_bytes(&self) -> usize { self.fx.values().map(FxEntry::bytes).sum() diff --git a/crates/gpu/src/prefix.rs b/crates/gpu/src/prefix.rs index fcd5c0a049..0312a25fa2 100644 --- a/crates/gpu/src/prefix.rs +++ b/crates/gpu/src/prefix.rs @@ -85,6 +85,11 @@ impl Prefix { } } + /// The document the cached composite belongs to, if any. + pub(crate) fn doc(&self) -> Option { + self.context.as_ref().map(|d| d.id) + } + pub(crate) fn prepare(&mut self, doc: &Document, plan: &Plan<'_>) -> Option { if self.budget == 0 { return None; diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs index 944c756662..bdeb9fe09c 100644 --- a/crates/gpu/tests/parity.rs +++ b/crates/gpu/tests/parity.rs @@ -187,6 +187,27 @@ fn check(g: &mut Gpu, doc: &Document, what: &str) { diff_rect(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}")); } +/// Closing a document frees what the compositor holds for it, however its canvas entry went +/// (#4529): `retain_docs` drops the resident pages, effect maps and lower-stack composite of +/// documents that aren't open, and keeps the open ones. +#[test] +fn retain_docs_frees_closed_documents() { + let Some(mut g) = gpu() else { return }; + let a = base_doc(64, 48); + let mut b = base_doc(32, 32); + b.id = photocraft_doc::DocId(a.id.0 + 1); + for d in [&a, &b] { + render_to_vec(&mut g.comp, &g.device, &g.queue, d, d.bounds()).expect("render"); + } + assert_eq!(g.comp.held_docs(), vec![a.id, b.id]); + g.comp.retain_docs(|d| d == b.id); + assert_eq!(g.comp.held_docs(), vec![b.id], "only the open document is left"); + g.comp.retain_docs(|_| false); + assert!(g.comp.held_docs().is_empty()); + assert_eq!(g.comp.composite_cache_bytes(), 0); + check(&mut g, &a, "renders again after being forgotten"); +} + #[test] fn first_frame_renders() { // Regression: the first submission after device creation is dropped on some drivers diff --git a/crates/io/src/abr_map.rs b/crates/io/src/abr_map.rs index e7fd290f0e..c21800f13d 100644 --- a/crates/io/src/abr_map.rs +++ b/crates/io/src/abr_map.rs @@ -429,7 +429,12 @@ impl Mapper<'_> { } dual.mode = mask_mode(enum_value(db, "BlnM")).unwrap_or(MaskMode::Multiply); dual.flip = boolean(db, "Flip").unwrap_or(false); - if let Some(v) = pct(db, "Spcn") { + // The dual tip's own spacing (`Brsh › Spcn`) is what Photoshop's Dual Brush panel + // shows. The `Spcn` beside it on the `dualBrush` object reads 100 % in Photoshop CC + // presets whatever the panel says (#4809), so it only stands in for a tip without one. + if obj(db, "Brsh").and_then(|t| pct(t, "Spcn")).is_none() + && let Some(v) = pct(db, "Spcn") + { dual.spacing = v.clamp(0.01, 10.0); } dual.scatter = self.dynamic(obj(db, "scatterDynamics")).jitter; diff --git a/crates/io/src/abr_map/tests.rs b/crates/io/src/abr_map/tests.rs index a97193457c..8bea763861 100644 --- a/crates/io/src/abr_map/tests.rs +++ b/crates/io/src/abr_map/tests.rs @@ -399,3 +399,32 @@ fn low_depth_height_texture_brush_paints() { assert_eq!(covered, 36, "{mode}: the stroke painted {covered} of 36 pixels"); } } + +/// #4809: Photoshop CC presets store the dual tip's spacing in `dualBrush › Brsh › Spcn` and a +/// `Spcn` of 100 % on the `dualBrush` object beside it; the tip's value is the panel's. A tip +/// without one still takes the outer value. +#[test] +fn dual_brush_spacing_comes_from_its_tip() { + let dual = |tip: Descriptor| { + Descriptor::new("brushPreset") + .with("Nm ", t("SPACING 10%")) + .with("Brsh", Value::Descriptor(Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 30.0)))) + .with( + "dualBrush", + Value::Descriptor( + Descriptor::new("dualBrush") + .with("useDualBrush", Value::Boolean(true)) + .with("Brsh", Value::Descriptor(tip)) + .with("BlnM", en("BlnM", "Ovrl")) + .with("Spcn", prc(100.0)), + ), + ) + }; + let spacing = |preset: Descriptor| { + let bytes = write_v6(2, &[], &[], &[preset], false).unwrap(); + read_abr(&bytes, "Test").unwrap().presets[0].brush.dual_brush.spacing + }; + let tip = Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 40.0)); + assert!((spacing(dual(tip.clone().with("Spcn", prc(10.0)))) - 0.10).abs() < 1e-6, "the tip's 10 %, not the outer 100 %"); + assert!((spacing(dual(tip)) - 1.0).abs() < 1e-6, "no tip spacing: the outer value"); +} diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rs index d7ebad09f6..6e82478389 100644 --- a/crates/io/src/adjust_map.rs +++ b/crates/io/src/adjust_map.rs @@ -509,11 +509,12 @@ fn parse_black_white(d: &[u8]) -> Option { /// (colour space + four u16), version 3 "4 bytes each for XYZ color"; then density (u32 percent) /// and preserve luminosity (1 byte). /// -/// The spec gives no scale for the XYZ values. They are read as D50 XYZ (the ICC PCS) with -/// 1.0 = 32768, the ICC 16-bit PCSXYZ encoding. That is inferred, not documented: the -/// Photoshop CS2 file in #3777 holds (24191, 25002, 3827), a bright warm yellow at this scale, -/// and rendering it against Photoshop's export fit best between 30000 and 32768 (1.0 = 65536, -/// a dull olive, was clearly worse). +/// The spec gives no scale for the XYZ values. They are read as XYZ relative to the D50 white +/// (X / 0.9642, Y, Z / 0.8249) with 1.0 = 32768, so white is stored as (32768, 32768, 32768). +/// That is inferred, not documented: decoded this way, every version 3 colour in the Photoshop +/// CS2 files of #3777 and #4940 is exactly a Photoshop preset (the Yellow filter holds +/// (24191, 25002, 3827) and decodes to #F9E31C, Warming Filter (85) holds (15548, 12029, 0) +/// and decodes to #EC8A00); reading them as absolute XYZ gives #FFE03A and #F18600. const PHFL_XYZ_ONE: f32 = 32768.0; fn parse_photo_filter(d: &[u8]) -> Option { @@ -527,11 +528,14 @@ fn parse_photo_filter(d: &[u8]) -> Option { (crate::channel_map::decode_color(space, c).to_rgb(), 12) } 3 => { - let xyz = [be32(d, 2)?, be32(d, 6)?, be32(d, 10)?].map(|v| v as f32 / PHFL_XYZ_ONE); - // Real colours stay below about 1.0; anything past 2.0 is not an XYZ colour. - if xyz.iter().any(|v| *v > 2.0) { + let rel = [be32(d, 2)?, be32(d, 6)?, be32(d, 10)?].map(|v| v as f32 / PHFL_XYZ_ONE); + // Relative to the white, real colours stay below about 2.0 (Cooling Filter (82) + // reaches 1.99 on Z); anything past that is not an XYZ colour. + if rel.iter().any(|v| *v > 2.0) { return None; } + // Relative to the D50 white: bring it back to absolute D50 XYZ before converting. + let xyz = [rel[0] * photocraft_color::convert::D50[0], rel[1], rel[2] * photocraft_color::convert::D50[2]]; let lin = photocraft_color::convert::mat3_mul(&photocraft_color::convert::XYZ_D50_TO_SRGB, xyz); (lin.map(|v| photocraft_color::convert::linear_to_srgb(v.clamp(0.0, 1.0))), 14) } @@ -1168,25 +1172,37 @@ mod tests { let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } = parse(b"phfl", &lab, None, Channels::Rgb) else { panic!() }; assert!(color.iter().all(|c| (c - 0.466).abs() < 0.01), "{color:?}"); assert_eq!(density, 0.25); - // Version 3: D50 XYZ, 1.0 = 32768. The ICC sRGB white point (D50) is white. - let v3 = phfl_v3([31595, 32768, 27040], 100, true); + // Version 3: XYZ relative to the D50 white, 1.0 = 32768. White is (32768, 32768, 32768). + let v3 = phfl_v3([32768, 32768, 32768], 100, true); let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &v3, None, Channels::Rgb) else { panic!() }; assert!(color.iter().all(|c| (c - 1.0).abs() < 0.005), "{color:?}"); assert_eq!(density, 1.0); - // Photoshop's Warming Filter (85) preset, sRGB #EC8A00, is D50 XYZ (15193, 12086, 1192). + // Photoshop's Warming Filter (85) preset, sRGB #EC8A00: the CS2 file of #4940 stores it + // relative to the D50 white as (15548, 12029, 0). let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } = - parse(b"phfl", &phfl_v3([15193, 12086, 1192], 25, false), None, Channels::Rgb) + parse(b"phfl", &phfl_v3([15548, 12029, 0], 25, false), None, Channels::Rgb) else { panic!() }; let expected = [0xecu8, 0x8a, 0x00].map(|v| f32::from(v) / 255.0); assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}"); assert_eq!(density, 0.25); - // The block from #3777 (Photoshop CS2): a warm yellow, density 63 %, preserve luminosity. + // The block from #3777 (Photoshop CS2): the Yellow filter preset, #F9E31C, density 63 %. let issue = [0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0]; let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &issue, None, Channels::Rgb) else { panic!() }; - assert!(color[0] > color[1] && color[1] > color[2] && color[1] > 0.8 && color[2] < 0.3, "{color:?}"); + let expected = [0xf9u8, 0xe3, 0x1c].map(|v| f32::from(v) / 255.0); + assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}"); assert_eq!(density, 0.63); + // Cooling Filter (82) from #4940: a deep blue outside sRGB; its Z stays under the 2.0 + // garbage guard and the colour clamps to (0, 181, 255). + let Adjustment::PhotoFilter { color: cooling, density, preserve_luminosity: true } = + parse(b"phfl", &phfl_v3([5327, 9584, 65357], 72, true), None, Channels::Rgb) + else { + panic!("Cooling Filter (82) must parse") + }; + let expected = [0u8, 181, 255].map(|v| f32::from(v) / 255.0); + assert!(cooling.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{cooling:?}"); + assert_eq!(density, 0.72); // The 19-byte form (no trailing pad) parses the same. assert_eq!(parse(b"phfl", &issue[..19], None, Channels::Rgb), parse(b"phfl", &issue, None, Channels::Rgb)); // Version 3 is read, never written: an edited filter is saved as version 2 and keeps its colour. diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 1778e5d064..c75418da73 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -312,8 +312,10 @@ fn document_to_image_for(doc: &Document, warnings: &mut Vec, cmyk_target let canvas = doc.bounds(); let fmt = doc.pixel_format(); let n = (w as usize) * (h as usize); - // Lab has no flat-format layout here: Lab documents always go through the composite. - let native = single_layer(doc).filter(|_| fmt.mode != ColorMode::Lab); + // Lab has no flat-format layout here: Lab documents always go through the composite, which + // flattens nothing when there is a single plain layer. + let single = single_layer(doc); + let native = single.filter(|_| fmt.mode != ColorMode::Lab); let mut icc = doc.icc_profile.as_ref().map(|i| i.to_vec()); let img = if let Some(s) = native { // Native path: keep model and depth. The surface's encoded samples are the codec's raw @@ -340,8 +342,10 @@ fn document_to_image_for(doc: &Document, warnings: &mut Vec, cmyk_target } Image::from_raw(w, h, layout, csample(fmt.sample), data)? } else { - let count = doc.layer_count(); - warnings.push(format!("{count} layer(s) flattened; layers, masks and blend modes are not kept")); + if single.is_none() { + let count = doc.layer_count(); + warnings.push(format!("{count} layer(s) flattened; layers, masks and blend modes are not kept")); + } let cmyk = fmt.mode == ColorMode::Cmyk && cmyk_target; // Only a CMYK target needs the document's profile; RGB-only targets keep the compositor's // own handling (built-in coated CMYK when the embedded profile is unusable). diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b80da66c3c..49e4bb60e2 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -508,7 +508,10 @@ pub fn merged_composite(file: &PsdFile) -> Result, IoError> { } let l = doc.layers.first().ok_or_else(|| IoError::Unsupported("no merged image".into()))?; let s = l.surface().ok_or_else(|| IoError::Unsupported("no merged image".into()))?; - Ok(photocraft_compose::surface_to_buffer(s, doc.bounds()).px) + // CMYK reads through the file's own profile, as the compositor reads its layers, so a tagged + // file's merged image and its composite are compared in the same colours. + let cmyk = photocraft_compose::cmyk_space(&doc); + Ok(photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || photocraft_compose::surface_to_buffer(s, doc.bounds()).px)) } #[cfg(test)] diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 4eada2422d..dfc7e46c9e 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -60,6 +60,8 @@ struct Ex { cmyk: bool, version: Version, next_id: u32, + /// Reserved imported layer and generated divider IDs. + used_ids: std::collections::HashSet, /// PSD ids assigned to document layers (kept from `psd_id` when unique). layer_ids: std::collections::HashMap, /// The generated `Txt2` object number of each type layer (a preserved `TySh` keeps its own @@ -363,10 +365,14 @@ impl Ex { (MaskData::Mask(pm), Some(self.encode(-2, &plane, w, h))) } - /// Ids for section dividers: above every layer id. + /// Prefer numbers above imported layer IDs, wrapping safely at u32::MAX. fn fresh_id(&mut self) -> u32 { - self.next_id += 1; - self.next_id + loop { + self.next_id = self.next_id.wrapping_add(1).max(1); + if self.used_ids.insert(self.next_id) { + return self.next_id; + } + } } fn layer_id(&mut self, l: &Layer) -> u32 { @@ -1444,6 +1450,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c cmyk: fmt.mode == ColorMode::Cmyk, version, next_id: 0, + used_ids: Default::default(), layer_ids: Default::default(), canvas: doc.bounds(), records: Vec::new(), @@ -1484,6 +1491,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c } } ex.next_id = used.iter().copied().max().unwrap_or(0); + ex.used_ids = used; // Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the // number it already names — its `Txt2` object must sit at that slot for `apply_txt2` — // and new layers get the next free number. @@ -1743,6 +1751,27 @@ mod tests { Document::new("size estimate", photocraft_geom::Size::new(width, height), ColorMode::Rgb, SampleType::U8) } + #[test] + fn group_divider_id_wraps_without_colliding_with_imported_layer_ids() { + let mut doc = document(8, 8); + let mut group = Layer::group("Imported group", vec![Layer::raster("Child", doc.pixel_format())]); + group.psd_id = Some(u32::MAX); + doc.layers.push(group); + + let file = document_to_psd(&doc); + let ids: Vec = file.layers().iter().filter_map(|layer| layer.layer_id()).collect(); + let unique: std::collections::HashSet = ids.iter().copied().collect(); + assert_eq!(ids.len(), 3, "group, child and closing divider"); + assert_eq!(unique.len(), ids.len(), "no generated ID may collide"); + assert!(unique.contains(&u32::MAX), "preserve the imported group ID"); + assert!(unique.contains(&1), "reuse the first unused positive ID on wrap"); + + let encoded = file.to_bytes().unwrap(); + let parsed = PsdFile::from_bytes(&encoded).unwrap(); + let reloaded_ids: std::collections::HashSet = parsed.layers().iter().filter_map(|layer| layer.layer_id()).collect(); + assert_eq!(unique, reloaded_ids); + } + #[test] fn unreadable_lr16_warns_on_import_and_is_not_saved_twice() { // #2700: a 16-bit file whose Lr16 block claims five layers but holds none. diff --git a/crates/io/tests/cmyk_composite_export.rs b/crates/io/tests/cmyk_composite_export.rs index 6364305304..9f537dabfd 100644 --- a/crates/io/tests/cmyk_composite_export.rs +++ b/crates/io/tests/cmyk_composite_export.rs @@ -233,3 +233,37 @@ fn layered_tiff_keeps_its_existing_cmyk_psd_composite_path() { assert_eq!(tag(&result.bytes, 338), Some(2)); assert!(image.to_normalized().as_chunks::<5>().0.iter().all(|px| (px[4] - 0.5).abs() < 0.0001)); } + +/// A tagged CMYK file's merged image reads through its own profile, as the compositor reads the +/// layers, so the two are compared in the same colours (the oracle tests rely on it: psd-tools' +/// tagged CMYK files were 95–100% off before). +#[test] +fn merged_composite_of_a_tagged_cmyk_file_reads_through_its_profile() { + use photocraft_cms::synth::{CmykParams, cmyk_profile}; + use photocraft_color::convert::{CmykSpace, cmyk_to_rgb, with_cmyk_space}; + let mut doc = Document::new("tagged", Size::new(6, 4), ColorMode::Cmyk, SampleType::U8); + let profile = + cmyk_profile(&CmykParams { description: "Merged Test CMYK".into(), tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, grid_b2a: 9, ..Default::default() }); + doc.icc_profile = Some(profile.to_bytes()); + let mut surface = Surface::new(photocraft_color::PixelFormat::new(ColorMode::Cmyk, SampleType::U8, false)); + for x in 0..6 { + for y in 0..4 { + surface.write_pixel(x, y, &[x as f32 / 5.0, y as f32 / 3.0, 0.4, (x * y) as f32 / 15.0]); + } + } + doc.layers.push(Layer::new("Background", LayerContent::Raster(surface))); + let psd = export(&doc, "psd", &ExportOptions::default()).unwrap(); + let file = photocraft_psd::PsdFile::from_bytes(&psd.bytes).unwrap(); + let merged = photocraft_io::merged_composite(&file).unwrap(); + // The merged image's own inks (planar, 255 = no ink), shown through the file's profile. + let raw = file.decode_merged().unwrap(); + let plane = 6 * 4; + let space = CmykSpace::for_profile(doc.icc_profile.as_ref()); + assert!(space.is_some(), "a profile other than the built-in coated CMYK"); + let shown: Vec<[f32; 3]> = + with_cmyk_space(space.as_ref(), || (0..plane).map(|i| cmyk_to_rgb(std::array::from_fn(|c| 1.0 - f32::from(raw[c * plane + i]) / 255.0))).collect()); + let builtin: Vec<[f32; 3]> = (0..plane).map(|i| cmyk_to_rgb(std::array::from_fn(|c| 1.0 - f32::from(raw[c * plane + i]) / 255.0))).collect(); + let apart = |a: &[[f32; 3]]| merged.iter().zip(a).flat_map(|(m, s)| (0..3).map(move |c| (m[c] - s[c]).abs())).fold(0.0f32, f32::max); + assert!(apart(&shown) < 1e-4, "merged image read through its profile: {}", apart(&shown)); + assert!(apart(&builtin) > 0.01, "the built-in profile would show it differently"); +} diff --git a/crates/io/tests/flat.rs b/crates/io/tests/flat.rs index 35a5e5ad46..f57041a72e 100644 --- a/crates/io/tests/flat.rs +++ b/crates/io/tests/flat.rs @@ -963,3 +963,20 @@ fn tga_default_bits_follow_the_alpha_channels() { assert_eq!(tga_default_bits(&with_alpha_channel(d, "Alpha 1")), TgaBits::Bits32); assert_eq!((TgaBits::from_bits(24), TgaBits::from_bits(32), TgaBits::from_bits(16)), (Some(TgaBits::Bits24), Some(TgaBits::Bits32), None)); } + +#[test] +fn a_lab_document_with_one_layer_is_not_reported_as_flattened() { + // Lab always goes through the sRGB composite, but a lone layer loses nothing to it. + let d = single(ColorMode::Lab, SampleType::U8, false); + for ext in ["tif", "png", "jpg"] { + let r = export(&d, ext, &ExportOptions::default()).unwrap(); + assert!(r.warnings.iter().all(|w| !w.contains("flattened")), "{ext}: {:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("Lab composite written as sRGB")), "{ext}: {:?}", r.warnings); + } + // Two layers are flattened, and say so. + let mut two = single(ColorMode::Lab, SampleType::U8, false); + let fmt = two.pixel_format(); + two.layers.push(raster("Top", fmt, two.bounds(), 5, true)); + let r = export(&two, "tif", &ExportOptions::default()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("2 layer(s) flattened")), "{:?}", r.warnings); +} diff --git a/crates/io/tests/resolution_axes.rs b/crates/io/tests/resolution_axes.rs index bc069d7f30..58b67d93c4 100644 --- a/crates/io/tests/resolution_axes.rs +++ b/crates/io/tests/resolution_axes.rs @@ -27,7 +27,7 @@ fn png_with_unequal_axes_reports_the_dropped_vertical_resolution() { assert!((r.document.resolution_dpi - 300.0).abs() < 0.01, "{}", r.document.resolution_dpi); let notes = resolution_notes(&r); assert_eq!(notes.len(), 1, "{:?}", r.warnings); - assert!(notes[0].contains("150.01") && notes[0].contains("300.00"), "{notes:?}"); + assert!(notes[0].contains("150.00") && notes[0].contains("300.00"), "{notes:?}"); } #[test] diff --git a/crates/psd/src/image_data.rs b/crates/psd/src/image_data.rs index 0f05eed909..fee0e18dc8 100644 --- a/crates/psd/src/image_data.rs +++ b/crates/psd/src/image_data.rs @@ -41,9 +41,15 @@ impl ImageData { /// Decodes and returns a single channel plane. pub fn decode_channel(&self, header: &Header, index: usize) -> Result> { + let invalid = || crate::error::PsdError::invalid(format!("no merged channel {index}")); + if index >= usize::from(header.channels) { + return Err(invalid()); + } + let plane = header.row_bytes().checked_mul(header.height as usize).ok_or_else(invalid)?; + let start = index.checked_mul(plane).ok_or_else(invalid)?; + let end = start.checked_add(plane).ok_or_else(invalid)?; let all = self.decode(header)?; - let plane = header.row_bytes() * header.height as usize; - all.get(index * plane..(index + 1) * plane).map(<[u8]>::to_vec).ok_or_else(|| crate::error::PsdError::invalid(format!("no merged channel {index}"))) + all.get(start..end).map(<[u8]>::to_vec).ok_or_else(invalid) } pub(crate) fn read(r: &mut Reader<'_>, header: &Header) -> Result { @@ -55,3 +61,25 @@ impl ImageData { Ok(ImageData { compression, data }) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::header::{ColorMode, Version}; + + #[test] + fn merged_channels_reject_invalid_indices_without_decoding_or_overflow() { + let header = Header::new(Version::Psd, 2, 1, 3, 8, ColorMode::Rgb); + let data = ImageData { compression: Compression::Raw, data: vec![10, 11, 20, 21, 30, 31] }; + for (index, expected) in [(0, [10, 11]), (1, [20, 21]), (2, [30, 31])] { + assert_eq!(data.decode_channel(&header, index).unwrap(), expected.to_vec()); + } + for index in [3, 4, usize::MAX] { + assert!(data.decode_channel(&header, index).is_err(), "invalid channel {index}"); + } + // Reject an invalid index before trying to decode corrupt merged data. + let corrupt = ImageData { compression: Compression::Raw, data: vec![] }; + let err = corrupt.decode_channel(&header, usize::MAX).unwrap_err().to_string(); + assert!(err.contains("no merged channel"), "{err}"); + } +} diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 194ecad12f..ff45764980 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -747,7 +747,8 @@ impl Surface { /// The surface moved by whole pixels: its encoded samples copied tile to tile (no float /// round trip, no intermediate buffer); moves by whole tiles share the tiles themselves, and /// a target tile read entirely from tiles of one single pixel value shares one such tile (the - /// inside of a solid fill stays one copy-on-write tile however often it moves). + /// inside of a solid fill stays one copy-on-write tile however often it moves). A tile it + /// copies that ends up holding only the default pixel isn't stored. /// `content` must hold every pixel that isn't the default one (`content_bounds`, say): only /// tiles it reaches are kept. pub fn translated(&self, dx: i32, dy: i32, content: Rect) -> Surface { @@ -763,6 +764,8 @@ impl Surface { let targets: std::collections::BTreeSet = sources().flat_map(|(c, _)| c.rect().translate(dx, dy).intersect(&moved).tiles()).collect(); let mut uniform = UniformTiles::default(); let zero = vec![0u8; bpp]; + // One tile row of the default pixel, to compare a finished tile with a row at a time. + let default_row = self.default_pixel.repeat(TILE_SIZE.unsigned_abs() as usize); for dc in targets { let dr = dc.rect(); let sr = dr.translate(dx.saturating_neg(), dy.saturating_neg()); @@ -774,7 +777,10 @@ impl Surface { && content.contains_rect(&sr) && sr.tiles().all(|sc| self.tiles.contains_key(&sc)); if covered && let Some(shared) = uniform.window(self, sr) { - out.tiles.insert(dc, shared); + // A tile of only the default pixel is left out, as `prune` would. + if shared.data.get(..bpp) != Some(&*self.default_pixel) { + out.tiles.insert(dc, shared); + } continue; } // A covered target is overwritten whole, so skip filling it with the default pixel. @@ -795,7 +801,11 @@ impl Surface { } } } - out.tiles.insert(dc, Arc::new(tile)); + // A target that got only default pixels isn't stored, as `prune` would drop it. Checked + // after the copy, a row at a time: a tile with content stops at its first such row. + if tile.data.chunks(default_row.len()).any(|row| row != default_row) { + out.tiles.insert(dc, Arc::new(tile)); + } } out } @@ -1427,6 +1437,43 @@ mod tests { let _ = s.translated(i32::MIN + 1, 3, all); } + #[test] + fn translated_stores_no_tiles_of_only_the_default_pixel() { + let only_default = |t: &Surface| { + let dp = t.default_pixel(); + t.tiles().filter(|(c, _)| t.read_region(c.rect()).chunks_exact(dp.len()).all(|p| p == dp.as_slice())).count() + }; + // Two blocks a few tiles apart, moved off the tile grid and back: the default-pixel edges + // of their tiles land on tiles of their own, which aren't stored. + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { + for default in [0.0, 0.25] { + let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); + s.fill_rect(Rect::new(0, 0, 300, 300), &vec![1.0; fmt.channels()]); + s.fill_rect(Rect::new(2000, 1000, 2300, 1300), &vec![0.5; fmt.channels()]); + let all = Rect::new(-600, -600, 3000, 2000); + let mut t = s.clone(); + for (dx, dy) in [(100, 56), (-100, -56), (10, 7), (-3, 40), (130, -90), (-137, 43)] { + let moved = t.translated(dx, dy, t.content_bounds()); + assert_eq!(moved.read_region(all), t.read_region(all.translate(-dx, -dy)), "{fmt:?} over {default} by ({dx}, {dy})"); + assert_eq!(only_default(&moved), 0, "{fmt:?} over {default} by ({dx}, {dy})"); + t = moved; + } + assert_eq!(t.read_region(all), s.read_region(all), "{fmt:?} over {default}: back where it started"); + assert_eq!(t.tile_count(), s.tile_count(), "{fmt:?} over {default}: back where it started"); + } + } + // Stored tiles of the default pixel inside `content`: the targets that would share one of + // them (#4414's uniform windows) are left out too. + let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]); + s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.25]); + s.write_pixel(600, 600, &[1.0]); + let content = Rect::new(0, 0, 1024, 1024); + let t = s.translated(10, 7, content); + assert_eq!(only_default(&t), 0); + assert_eq!(t.tile_count(), 1); + assert_eq!(t.read_region(Rect::new(-20, -20, 1100, 1100)), s.read_region(Rect::new(-30, -27, 1090, 1093))); + } + proptest! { #[test] fn region_write_read_roundtrip(x in -600i32..600, y in -600i32..600, w in 1u32..90, h in 1u32..90, seed in any::()) { diff --git a/crates/ui-egui/src/brush_panel.rs b/crates/ui-egui/src/brush_panel.rs index d91e6ff459..515e6e5a21 100644 --- a/crates/ui-egui/src/brush_panel.rs +++ b/crates/ui-egui/src/brush_panel.rs @@ -14,7 +14,7 @@ //! The lock beside a section name keeps that section's settings when another preset is picked //! (`locks` in the brush, applied by the engine). The Brushes tab lives in [`crate::brushes_tab`]. -use egui::{Color32, CornerRadius, RichText, Sense, Stroke, vec2}; +use egui::{Color32, CornerRadius, Sense, Stroke, vec2}; use photocraft_engine::BrushSettings; use photocraft_engine::paint; use serde::{Deserialize, Serialize}; @@ -359,9 +359,8 @@ fn settings_tab(app: &mut PhotocraftApp, ui: &mut egui::Ui) { widgets::vline(ui, 482.0); ui.vertical(|ui| { ui.set_width(WIDTH - 190.0); - let name = SECTIONS.get(section).map_or("Brush Tip Shape", |entry| entry.0); - ui.label(RichText::new(tl!(name)).font(theme::semibold(12.5)).color(t.text)); - ui.add_space(6.0); + // No title above the options (#3477): the selected row in the list names them, as + // in Photoshop, and the line is better spent on the options. let on = section_flag(&mut b, section).is_none_or(|f| *f); egui::ScrollArea::vertical().id_salt(("brush-section", section)).max_height(450.0).auto_shrink([false, false]).show(ui, |ui| { ui.set_width(WIDTH - 204.0); diff --git a/crates/ui-egui/src/brush_panel_tests.rs b/crates/ui-egui/src/brush_panel_tests.rs index 9bd669fefe..750a9d5506 100644 --- a/crates/ui-egui/src/brush_panel_tests.rs +++ b/crates/ui-egui/src/brush_panel_tests.rs @@ -560,6 +560,51 @@ fn toggle_value(app: &PhotocraftApp, section: usize) -> bool { brush.pointer(path).and_then(Value::as_bool).expect("the checkbox has a boolean brush setting") } +#[test] +fn hue_jitter_amount_edits_keep_percentage_units_and_command_routing() { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut h = harness(0, 5); + h.state_mut() + .session + .execute( + "tools.setBrush", + json!({"brush": {"colorDynamics": { + "enabled": true, "hueJitter": 0.37, "saturationJitter": 0.23, "brightnessJitter": 0.41, "purity": -0.16 + }}}), + ) + .unwrap(); + let before = h.state().session.tools.brush.clone(); + h.run_steps(2); + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(37.0)).unwrap(); + let center = field.rect().center(); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + assert_eq!(h.state().session.tools.brush.color_dynamics.hue_jitter, 0.38); + h.key_press(egui::Key::Enter); + // Click near the high end of the track, then beyond its right edge while dragging. + let from = egui::pos2(center.x, center.y + 24.0); + h.event(egui::Event::PointerMoved(from)); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + let to = from + vec2(200.0, 0.0); + h.event(egui::Event::PointerMoved(to)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); + let mut expected = before; + expected.color_dynamics.hue_jitter = 1.0; + assert_eq!(h.state().session.tools.brush, expected, "the amount clamps at 100% and preserves neighboring settings"); + assert_eq!(last_journal(h.state()).unwrap().0, "tools.setBrush"); + let mut replay = photocraft_engine::Session::new(); + for (id, params) in h.state().session.journal.clone() { + replay.execute(&id, params).unwrap(); + } + assert_eq!(replay.tools.brush, expected, "the edit remains replayable through the engine"); +} + #[test] fn checkbox_only_rows_toggle_without_changing_the_selected_controls() { use egui_kittest::kittest::Queryable; @@ -992,7 +1037,7 @@ fn app_harness_with_language(lang: crate::i18n::Lang) -> Harness<'static, Photoc } #[test] -fn brush_sections_paint_simplified_chinese_labels_and_heading() { +fn brush_sections_paint_simplified_chinese_labels() { fn collect_text(shape: &egui::Shape, out: &mut Vec) { match shape { egui::Shape::Text(text) => out.push(text.galley.job.text.clone()), @@ -1017,8 +1062,27 @@ fn brush_sections_paint_simplified_chinese_labels_and_heading() { assert!(painted.iter().any(|s| s == translated), "{name} must paint as {translated}"); assert!(!painted.iter().any(|s| s == name), "{name} must not paint in English"); } - let heading = crate::i18n::tr(zh, "Brush Tip Shape"); - assert_eq!(painted.iter().filter(|s| s.as_str() == heading).count(), 2, "both the section row and heading are translated"); +} + +/// #3477: the options pane has no title of its own. The selected row in the section list is the +/// only place the section's name is painted. +#[test] +fn options_pane_does_not_repeat_the_selected_sections_name() { + fn collect_text(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(text) => out.push(text.galley.job.text.clone()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect_text(s, out)), + _ => {} + } + } + for (section, (name, _)) in SECTIONS.iter().enumerate().take(CHECKBOX_ONLY_START) { + let h = harness(0, section); + let mut painted = Vec::new(); + for shape in &h.output().shapes { + collect_text(&shape.shape, &mut painted); + } + assert_eq!(painted.iter().filter(|s| s.as_str() == *name).count(), 1, "{name} is painted once, in the section list"); + } } #[test] diff --git a/crates/ui-egui/src/brush_sections.rs b/crates/ui-egui/src/brush_sections.rs index db044557a9..ff7ca5d292 100644 --- a/crates/ui-egui/src/brush_sections.rs +++ b/crates/ui-egui/src/brush_sections.rs @@ -512,10 +512,7 @@ fn color_dynamics(ui: &mut egui::Ui, b: &mut BrushSettings) { widgets::checkbox(ui, &mut c.per_tip, tl!("Apply Per Tip")); ui.add_space(6.0); dynamic(ui, "brush-fgbg-ctl", tl!("Foreground/Background Jitter"), &mut c.fg_bg, 1.0, None, false); - let mut h = (c.hue_jitter * 100.0).round(); - if widgets::slider_row(ui, tl!("Hue Jitter"), &mut h, 0.0..=100.0, "%", Some(&widgets::hue_stops())).changed() { - c.hue_jitter = (h.round() / 100.0).clamp(0.0, 1.0); - } + pct(ui, tl!("Hue Jitter"), &mut c.hue_jitter, 1.0); pct(ui, tl!("Saturation Jitter"), &mut c.saturation_jitter, 1.0); pct(ui, tl!("Brightness Jitter"), &mut c.brightness_jitter, 1.0); signed_pct(ui, tl!("Purity"), &mut c.purity, -1.0, 1.0); @@ -648,6 +645,29 @@ mod tests { h } + /// #3825: jitter is an amount, not a hue selector; it uses the themed amount track. + #[test] + fn hue_jitter_paints_an_amount_track_in_every_theme() { + for kind in theme::ThemeKind::ALL { + let mut b = BrushSettings::default(); + b.color_dynamics.hue_jitter = 0.37; + let mut h = section_harness(5, b.clone()); + crate::PhotocraftApp::setup_context(&h.ctx, kind); + h.run_steps(3); + let label = h.get_by_label("Hue Jitter").rect(); + let t = Tokens::get(&h.ctx); + assert!( + h.output().shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Rect(r) + if r.rect.width() > 150.0 && (r.rect.height() - 3.0).abs() < 0.1 + && r.rect.top() > label.bottom() && r.rect.bottom() < label.bottom() + 30.0 + && r.fill == t.field_border)), + "{kind:?}: Hue Jitter paints the same neutral track as other percentage amounts" + ); + assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.accesskit_node().numeric_value() == Some(37.0))); + assert_eq!(h.state(), &b, "rendering does not change saved brush settings"); + } + } + fn set_controls(b: &mut BrushSettings, control: Control) { for d in [ &mut b.shape_dynamics.size, diff --git a/crates/ui-egui/src/brushes_tab.rs b/crates/ui-egui/src/brushes_tab.rs index 7a8d56b3d0..703b6e0290 100644 --- a/crates/ui-egui/src/brushes_tab.rs +++ b/crates/ui-egui/src/brushes_tab.rs @@ -475,6 +475,22 @@ fn darker(c: Color32, f: f32) -> Color32 { Color32::from_rgba_unmultiplied((r as f32 * f).round() as u8, (g as f32 * f).round() as u8, (b as f32 * f).round() as u8, a) } +/// Where a card's tip thumbnail goes in its `cell`. `number_h` is the height of the size number +/// under it, `None` on compact cards (no number: the tip takes the cell whole). Otherwise the +/// number keeps a band at the bottom of the cell and the tip is centred in what's left above it, +/// at [`CARD_TIP_BASE`] × `scale` or that room's side, whichever is smaller, times the preset's +/// [`crate::brush_sections::thumb_scale`]: big brushes still read bigger than small ones, and +/// none of them reaches down over the number. +fn card_tip_rect(cell: egui::Rect, number_h: Option, size: f32, scale: f32) -> egui::Rect { + let Some(number_h) = number_h else { + return egui::Rect::from_center_size(cell.center(), egui::Vec2::splat((cell.width().min(cell.height()) - 2.0).max(1.0))); + }; + // The number sits 1 pt off the cell's bottom, with a 1 pt gap above it. + let room = egui::Rect::from_min_max(cell.min, pos2(cell.right(), (cell.bottom() - number_h - 2.0).max(cell.top()))); + let side = (CARD_TIP_BASE * scale).min(room.width().min(room.height())).max(0.0) * crate::brush_sections::thumb_scale(size); + egui::Rect::from_center_size(room.center(), egui::Vec2::splat(if side.is_finite() { side.max(1.0) } else { 1.0 })) +} + /// One preset in the Brush Preset picker: a 2 × 2 grid whose bottom row (the name) spans both /// columns — tip at the top left, stroke preview at the top right. A part that's off loses its /// cell (the other takes the room): with only the tip and the name on, the name moves into the @@ -545,18 +561,13 @@ fn preset_card( let tip_w = if tip_only { top.width() } else { (CARD_TIP_W * scale).min(top.width() * 0.5) }; let cell = egui::Rect::from_min_size(top.left_top(), vec2(tip_w, top_h)); let tip = brush_preview::tip_texture(ui.ctx(), &format!("brushes-tip:{}", p.name), &pb.tip, (pb.hardness, pb.angle, pb.roundness), 36, t.text); - let side = if compact { (cell.width().min(cell.height()) - 2.0).max(1.0) } else { CARD_TIP_BASE * scale * crate::brush_sections::thumb_scale(pb.size) }; - let center = if compact { cell.center() } else { pos2(cell.center().x, cell.center().y - 2.0 * scale_h) }; - let tr = egui::Rect::from_center_size(center, vec2(side, side)); + let number = + (!compact).then(|| ui.painter().layout_no_wrap(format!("{}", pb.size.round() as i64), egui::FontId::proportional(CARD_NUM_FONT), t.text_faint)); + let tr = card_tip_rect(cell, number.as_ref().map(|g| g.size().y), pb.size, scale); ui.painter().image(tip.id(), tr, full_uv(), Color32::WHITE); - if !compact { - ui.painter().text( - pos2(cell.center().x, cell.bottom() - 1.0), - egui::Align2::CENTER_BOTTOM, - format!("{}", pb.size.round() as i64), - egui::FontId::proportional(CARD_NUM_FONT), - t.text_faint, - ); + if let Some(g) = number { + let at = pos2(cell.center().x - g.size().x / 2.0, cell.bottom() - 1.0 - g.size().y); + ui.painter().galley(at, g, t.text_faint); } x = cell.right(); } diff --git a/crates/ui-egui/src/brushes_tab_tests.rs b/crates/ui-egui/src/brushes_tab_tests.rs index 3a225aa6c6..4c61ecc54d 100644 --- a/crates/ui-egui/src/brushes_tab_tests.rs +++ b/crates/ui-egui/src/brushes_tab_tests.rs @@ -265,3 +265,56 @@ fn the_brushes_tab_grid_is_centred_past_its_indent() { h.run_steps(6); rows_are_centred(&h, PANEL_LIST.indent, 2); } + +/// #4454: a card's size number sat under the tip thumbnail of any medium or large brush (the +/// tip took up to 44.8 pt of a 42 pt cell, the number anchored to the cell's bottom), so the +/// "30" of Hard Round and the "45" of Soft Round couldn't be read. At every footer scale that +/// shows numbers, in each card kind, the tip now stays above the number, and bigger brushes still +/// get bigger tips. +#[test] +fn card_tips_never_cover_their_size_number() { + let number_h = std::rc::Rc::new(std::cell::Cell::new(0.0_f32)); + let seen = number_h.clone(); + let mut h = Harness::new_ui(move |ui| { + let g = ui.painter().layout_no_wrap("45".into(), egui::FontId::proportional(CARD_NUM_FONT), Color32::WHITE); + seen.set(g.size().y); + }); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run(); + let number_h = number_h.get(); + assert!(number_h > 8.0, "the number has a real height: {number_h}"); + let mut scale = CARD_COMPACT_SCALE + 0.01; + while scale <= *crate::brush_picker::SCALE_RANGE.end() + 1e-3 { + let scale_h = scale.max(CARD_MIN_H_SCALE); + // The tip cell of a full card (name row under it), a tip-and-name card and a tip-only one, + // as [`preset_card`] sizes them in a wide column. + let cells = [ + vec2(CARD_TIP_W * scale, (CARD_MAX_H - CARD_PAD * 2.0 - CARD_NAME_H) * scale_h), + vec2(CARD_TIP_W * scale, (CARD_TIP_NAME_H - CARD_PAD * 2.0) * scale_h), + vec2((CARD_TIP_ONLY_W - 16.0) * scale, (CARD_TIP_ONLY_H - CARD_PAD * 2.0) * scale_h), + ]; + for size in cells { + let cell = Rect::from_min_size(egui::pos2(10.0, 20.0), size); + let number_top = cell.bottom() - 1.0 - number_h; + let mut last = 0.0; + for brush in [1.0, 5.0, 13.0, 30.0, 45.0, 100.0, 2500.0] { + let tip = card_tip_rect(cell, Some(number_h), brush, scale); + assert!(tip.bottom() <= number_top + 1e-3, "scale {scale}, cell {size:?}, {brush} px: tip {tip:?} reaches the number at {number_top}"); + assert!(cell.expand(1e-3).contains_rect(tip), "scale {scale}, {brush} px: tip {tip:?} leaves its cell {cell:?}"); + assert!(tip.width() >= last, "scale {scale}, {brush} px: a bigger brush gets a smaller tip"); + last = tip.width(); + } + } + scale += 0.05; + } + // The tip-only grid's cells are tall enough for the number: a big brush's tip still spans + // the cell's width. + let cell = Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(CARD_TIP_ONLY_W - 16.0, CARD_TIP_ONLY_H - CARD_PAD * 2.0)); + assert!((card_tip_rect(cell, Some(number_h), 45.0, 1.0).width() - cell.width()).abs() < 1e-3); + // Compact cards: no number, the tip fills the cell; nonsense never makes a non-finite rect. + assert_eq!(card_tip_rect(cell, None, 45.0, 0.5).width(), cell.width() - 2.0); + for (n, size, scale) in [(f32::NAN, 30.0, 1.0), (500.0, f32::NAN, 1.0), (12.0, 30.0, f32::INFINITY), (12.0, -5.0, 0.0)] { + let r = card_tip_rect(cell, Some(n), size, scale); + assert!(r.min.is_finite() && r.max.is_finite(), "{n} {size} {scale}: {r:?}"); + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 231b4612ca..febb6571ea 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -944,8 +944,10 @@ pub fn doc_point_at(app: &PhotocraftApp, pos: Pos2) -> Option<[f64; 2]> { pub fn fit_view(view: &mut View, doc: &Document, area: Vec2, ppp: f32, aspect: f32) { let (w, h) = (doc.size.width as f32, doc.size.height as f32); let shown_w = w * if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; - let points = ((area.x - 40.0) / shown_w).min((area.y - 40.0) / h).min(1.0); - let zoom = crate::zoom_levels::clamp(points * ppp, [doc.size.width, doc.size.height]); + // Fit never magnifies past 100%: one image pixel per *physical* pixel, so the cap applies + // after the points → device pixels conversion (a 150% display would otherwise open at 150%). + let fit = ((area.x - 40.0) / shown_w).min((area.y - 40.0) / h) * ppp; + let zoom = crate::zoom_levels::clamp(fit.min(1.0), [doc.size.width, doc.size.height]); view.zoom = zoom; view.center = [w / 2.0, h / 2.0]; view.fit_pending = false; @@ -1254,6 +1256,14 @@ pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz Some(tex.id()) } +/// The CPU canvas texture's sampling (#4810). Zoomed in, a full-resolution texture shows each +/// document pixel as a crisp square, as the GPU canvas's sharp nearest filter and Photoshop do; +/// zoomed out it is still filtered. A reduced texture (`factor` > 1) stays bilinear: its texels +/// are averages of several pixels, and squares of them would be blocks the image doesn't have. +fn canvas_texture_options(factor: u32) -> TextureOptions { + if factor > 1 { TextureOptions::LINEAR } else { TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR } } +} + /// Make sure the canvas texture for document `idx` on `display` is current; returns (texture /// id, scale). pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, display: Option) -> Option<(egui::TextureId, f32)> { @@ -1298,7 +1308,7 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, let r = buf.rect; if !r.is_empty() { let t1 = crate::gpu_canvas::now_ms(); - t.set_partial([r.x0 as usize, r.y0 as usize], display_image(display.as_deref(), &buf), TextureOptions::LINEAR); + t.set_partial([r.x0 as usize, r.y0 as usize], display_image(display.as_deref(), &buf), canvas_texture_options(factor)); let px = (r.width() as u64 * r.height() as u64).saturating_mul(u64::from(factor).pow(2)); app.perf.record("rect", px, t1 - t0, crate::gpu_canvas::now_ms() - t1); } @@ -1308,8 +1318,8 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, let t1 = crate::gpu_canvas::now_ms(); let (img, scale) = (display_image(display.as_deref(), &full), 1.0 / factor as f32); match cache.texture.as_mut() { - Some(t) if t.size() == img.size => t.set(img, TextureOptions::LINEAR), - _ => cache.texture = Some(ctx.load_texture(format!("canvas-{}-{}", id.0, cache_key(id, output).1), img, TextureOptions::LINEAR)), + Some(t) if t.size() == img.size => t.set(img, canvas_texture_options(factor)), + _ => cache.texture = Some(ctx.load_texture(format!("canvas-{}-{}", id.0, cache_key(id, output).1), img, canvas_texture_options(factor))), } cache.scale = scale; app.perf.record("full", doc.size.width as u64 * doc.size.height as u64, t1 - t0, crate::gpu_canvas::now_ms() - t1); @@ -3253,7 +3263,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); } // Zoom tool drags: scrubby zoom or a zoom rectangle (zoom_tool.rs); clicks step below. - if tool == Tool::Zoom && crate::zoom_tool::drag(app, &ctx, &mut view, &xf, &buttons, response.interact_pointer_pos()) { + // Like the Hand, the selected Zoom yields to an open Free Transform box (#4799). + if tool == Tool::Zoom && !transform_owns_pointer && crate::zoom_tool::drag(app, &ctx, &mut view, &xf, &buttons, response.interact_pointer_pos()) { (buttons.started, buttons.dragged, buttons.stopped) = (false, false, false); } // A drag is only recognised once the pointer has moved past egui's click distance: the @@ -3387,7 +3398,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods); let d = xf.to_doc(p); match tool { - Tool::Zoom => { + Tool::Zoom if !transform_owns_pointer => { let nz = crate::zoom_levels::step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }, view.doc_size); let center = app.session.prefs().tools.zoom_clicked_point_to_center; zoom_about(&mut view, &xf, p, nz, center, ppp); @@ -5850,6 +5861,46 @@ mod tests { assert_eq!((app.canvases[&(id, 1)].tex_revision, app.canvases[&(id, 4)].tex_revision), (rev, rev)); } + #[test] + fn cpu_canvas_shows_crisp_pixels_when_zoomed_in() { + // #4810: above 100% the CPU canvas shows each pixel as a square, like the GPU canvas's + // sharp nearest filter; below 100% it still filters. Both the first upload and a + // damage-rect update carry the sampling, since the renderer takes it from each delta. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 2, "height": 2})).unwrap(); + let ctx = egui::Context::default(); + let tex = ensure_texture(&mut app, &ctx, 0, None).unwrap().0; + let uploads = |ctx: &egui::Context| { + let mut delta = ctx.tex_manager().write().take_delta(); + let seen = delta.set.get(&tex).into_iter().flatten().map(|d| (d.pos.is_some(), d.options)).collect::>(); + delta.clear(); + seen + }; + let crisp = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR }; + assert_eq!(uploads(&ctx), vec![(false, crisp)]); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap(); + ensure_texture(&mut app, &ctx, 0, None).unwrap(); + uploads(&ctx); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + assert_eq!(ensure_texture(&mut app, &ctx, 0, None).unwrap().0, tex); + assert_eq!(uploads(&ctx), vec![(true, crisp)], "a partial update keeps the crisp sampling"); + } + + #[test] + fn cpu_canvas_of_a_reduced_document_stays_bilinear() { + // Over MAX_TEXTURE the texture holds one texel per `factor` pixels: a texel is not a + // document pixel, so showing it as a square would draw blocks that aren't in the image. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": MAX_TEXTURE + 1, "height": 2})).unwrap(); + let ctx = egui::Context::default(); + let (tex, scale) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); + assert!(scale < 1.0); + let mut delta = ctx.tex_manager().write().take_delta(); + let uploads: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| d.options).collect(); + delta.clear(); + assert_eq!(uploads, vec![TextureOptions::LINEAR]); + } + #[test] fn gpu_display_luts_are_per_display() { let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else { @@ -7210,6 +7261,46 @@ mod tests { assert!(app.style_preview.is_none()); } + /// Layer Style opened while Free Transform is open applies the box first, as Photoshop does, + /// so the dialog previews on the transformed layer (#4821): a dropped file (placed in the box, + /// untouched) and a box opened by hand and moved. + #[test] + fn layer_style_opened_during_free_transform_applies_the_box_and_previews() { + for placed in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); + app.run("edit.fill", json!({"color": "#0000ff"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.sync_views(); + let ctx = egui::Context::default(); + let dx = if placed { + crate::transform_tool::begin_placed(&mut app, &ctx).unwrap(); + 0 + } else { + crate::transform_tool::begin(&mut app, &ctx).unwrap(); + app.ui.transform.as_mut().unwrap().quad = [[28.0, 8.0], [44.0, 8.0], [44.0, 24.0], [28.0, 24.0]]; + 20 + }; + crate::layer_style::open(&mut app, Some("dropShadow")).unwrap(); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "placed {placed}: the box is applied"); + let (shown, _) = display_doc(&mut app, 0); + let rect = photocraft_geom::Rect::new(0, 0, 64, 64); + let with = photocraft_compose::render(&shown, rect); + let without = photocraft_compose::render(&app.session.documents()[0].doc, rect); + assert!( + with.get(16 + dx, 16)[0] < 0.1 && with.get(16 + dx, 16)[2] > 0.9, + "placed {placed}: the blue block where the box left it, not the white under it" + ); + // The shadow darkens the white around the block, which the document doesn't have yet. + let block = |x: i32, y: i32| (8 + dx..24 + dx).contains(&x) && (8..24).contains(&y); + let shadow = + (0..64).flat_map(|y| (0..64).map(move |x| (x, y))).filter(|&(x, y)| !block(x, y) && without.get(x, y)[0] - with.get(x, y)[0] > 0.05).count(); + assert!(shadow > 20, "placed {placed}: the Drop Shadow is previewed ({shadow} px)"); + } + } + #[test] fn fill_view_covers_the_canvas_and_centres_the_document() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -7228,13 +7319,22 @@ mod tests { fill_view(&mut view, &doc, vec2(600.0, 600.0), 2.0, 1.0); assert_eq!(view.zoom, 6.0); - // Fit never magnifies past the 1 point-per-pixel cap; on a scaled display the cap is 2. + // Fit never magnifies past 100% = one image pixel per physical pixel, at any display + // scale (it used to cap at one per *point*, so a 150% display opened images at 150%). + for ppp in [1.0f32, 1.5, 2.0] { + let mut view = View { fit_pending: true, ..View::default() }; + fit_view(&mut view, &doc, vec2(600.0, 600.0), ppp, 1.0); + assert_eq!(view.zoom, 1.0, "ppp {ppp}: a small image opens at 100%"); + } + // A large image still shrinks to fit: 1000×500 into 440 points is 0.44 pt/px, so 0.66 + // physical at ppp 1.5. + let big = { + app.run("file.new", json!({"width": 1000, "height": 500})).unwrap(); + app.session.active().unwrap().doc.clone() + }; let mut view = View { fit_pending: true, ..View::default() }; - fit_view(&mut view, &doc, vec2(600.0, 600.0), 1.0, 1.0); - assert_eq!(view.zoom, 1.0); - let mut view = View { fit_pending: true, ..View::default() }; - fit_view(&mut view, &doc, vec2(600.0, 600.0), 2.0, 1.0); - assert_eq!(view.zoom, 2.0); + fit_view(&mut view, &big, vec2(480.0, 480.0), 1.5, 1.0); + assert!((view.zoom - 0.66).abs() < 1e-5, "{}", view.zoom); } #[test] diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rs index 24f0afd78a..0d51f5d2f5 100644 --- a/crates/ui-egui/src/color_picker_ui.rs +++ b/crates/ui-egui/src/color_picker_ui.rs @@ -686,7 +686,7 @@ fn fields(ui: &mut egui::Ui, f: &mut Map, mode: &str, now: &Compo ui.memory_mut(|m| m.request_focus(id)); } let typing = if ui.memory(|m| m.has_focus(id)) { ui.data(|d| d.get_temp::(id)) } else { None }; - let mut h = typing.unwrap_or_else(|| hex(rgb).trim_start_matches('#').to_string()); + let mut h = typing.unwrap_or_else(|| hex(rgb).trim_start_matches('#').to_ascii_uppercase()); let r = crate::widgets::text_field_ex(ui, id, &mut h, "", 64.0, true, Some(6)); if r.gained_focus() { crate::field_tab::select_all(ui.ctx(), id, &h); @@ -859,6 +859,13 @@ mod tests { h.state().get("color").and_then(Value::as_str).unwrap().to_string() } + #[test] + fn hex_field_shows_uppercase_without_rewriting_the_selected_color() { + let h = picker("#12abef"); + assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("12ABEF")); + assert_eq!(color(&h), "#12abef", "casing is presentation only"); + } + #[test] fn hex_field_takes_typed_digits() { let mut h = picker("#000000"); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7ae2730bd0..1adc9051da 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -14,6 +14,11 @@ fn rects(ctx: &egui::Context) -> Vec { ctx.data(|m| m.get_temp(egui::Id::new(RECTS))).unwrap_or_default() } +/// The window drag target must not cover a dialog which has been moved into the title bar. +pub(crate) fn titlebar_drag_area_is_clear(ctx: &egui::Context, area: egui::Rect) -> bool { + rects(ctx).iter().all(|dialog| !dialog.intersects(area)) +} + /// With a dialog open the rest of the window is inert (egui's modal layer), but like Photoshop the /// image can still be panned and zoomed under it. The pointer position when it is over `canvas` /// and not over a dialog or one of its popups. @@ -338,7 +343,14 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { ui.spacing_mut().item_spacing.x = 10.0; if matches!(d.kind, DialogKind::About | DialogKind::Error) { - if dialog_buttons(ui, &[DialogButton::new(ButtonRole::Default, tl!("OK"), 84.0)]).is_some() { + // ↩ is OK too, as on every other dialog (#4872), from the frame after the + // alert appeared: the ↩ that raised it (committing a locked layer's Free + // Transform, say) must not close it again at once. + let seen = id.with("alert-seen"); + let shown_before = ui.ctx().data(|m| m.get_temp::(seen).unwrap_or(false)); + ui.ctx().data_mut(|m| m.insert_temp(seen, true)); + let enter = interactive && shown_before && ui.input(|i| i.key_pressed(egui::Key::Enter)); + if dialog_buttons(ui, &[DialogButton::new(ButtonRole::Default, tl!("OK"), 84.0)]).is_some() || enter { outcome = Some(false); } } else { @@ -795,6 +807,32 @@ mod tests { assert_eq!(harness.state().ui.dialogs.len(), 1, "dragging must not close the dialog"); } + /// #4872: an alert (Error, About) closes with ↩ as with OK, but not on the ↩ that raised it. + #[test] + fn enter_closes_an_alert_but_not_the_enter_that_opened_it() { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 600.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(2); + let alert = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>| { + h.state_mut().ui.open_dialog(DialogKind::Error, json!({"message": crate::move_lock::MESSAGE}).as_object().cloned().unwrap_or_default()) + }; + // Raised in the frame its own ↩ arrives: that ↩ leaves it open. + alert(&mut h); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(h.state().ui.dialogs.len(), 1, "the ↩ that raised the alert doesn't close it"); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(h.state().ui.dialogs.is_empty(), "↩ is OK"); + // A new alert starts over, and Esc still closes it. + alert(&mut h); + h.run_steps(2); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.dialogs.is_empty(), "Esc too"); + } + fn dialog_harness(size: egui::Vec2, command: &str) -> egui_kittest::Harness<'static, PhotocraftApp> { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); diff --git a/crates/ui-egui/src/direct_select.rs b/crates/ui-egui/src/direct_select.rs index b18361828d..ab997d47e3 100644 --- a/crates/ui-egui/src/direct_select.rs +++ b/crates/ui-egui/src/direct_select.rs @@ -7,6 +7,7 @@ //! canvas to marquee-select anchors, click empty canvas to deselect. //! * Drag selected anchors to move them, a direction handle to turn it (a smooth point keeps its //! handles collinear; ⌥ breaks them apart), or a segment to bend it (straight segments move). +//! The arrow keys nudge the selected anchors 1 px (⇧ 10 px), one history step per press. //! * Convert Point (the tool, or Pen + ⌥): click an anchor to make it a corner, drag from it to //! pull out smooth handles, drag a handle to move it alone. The tool selects the anchor it //! converts, so its handles show; a press on empty canvas or a segment does nothing, and ⌘/Ctrl @@ -346,6 +347,37 @@ fn marquee(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2], add: bool) { } } +/// Arrow keys with Direct Selection and selected anchors (#4486), as in Photoshop: nudge them +/// 1 px (⇧ 10 px) through `path.moveAnchors`, one history step per press. Not while a drag is +/// in progress. Returns true when a key was used. +pub fn arrow_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + let ds = &app.ui.direct_selection; + let Some(target) = ds.target.filter(|_| app.ui.tool == Tool::DirectSelection && !ds.anchors.is_empty() && ds.drag.is_none()) else { + return false; + }; + let anchors = ds.anchors.clone(); + use egui::Key; + let keys = [(Key::ArrowLeft, -1.0, 0.0), (Key::ArrowRight, 1.0, 0.0), (Key::ArrowUp, 0.0, -1.0), (Key::ArrowDown, 0.0, 1.0)]; + for (key, ux, uy) in keys { + // ⇧ first: `consume_key` ignores an extra ⇧. + for mods in [Modifiers::SHIFT, Modifiers::NONE] { + if ctx.input_mut(|i| i.consume_key(mods, key)) { + let k = if mods.shift { 10.0 } else { 1.0 }; + let mut params = json!({"anchors": anchors, "move": [ux * k, uy * k]}); + if let (Some(p), Some(t)) = (params.as_object_mut(), target.params().as_object()) { + p.extend(t.clone()); + } + if let Err(e) = app.run("path.moveAnchors", params) { + app.ui.status = e; + app.ui.status_error = true; + } + return true; + } + } + } + false +} + /// Paths with their anchors (selected ones filled), the shown handles, the drag's preview in /// place of its path, and the marquee. `paths` false (View › Show › Target Path off) leaves only /// the marquee. diff --git a/crates/ui-egui/src/direct_select_tests.rs b/crates/ui-egui/src/direct_select_tests.rs index 17334a1626..51759992d7 100644 --- a/crates/ui-egui/src/direct_select_tests.rs +++ b/crates/ui-egui/src/direct_select_tests.rs @@ -225,3 +225,39 @@ fn the_convert_point_tool_shows_the_path_overlay() { assert!(!super::shows(&app, Modifiers::NONE)); assert!(super::shows(&app, Modifiers::COMMAND)); } + +/// One key press through the canvas arrow keys, as egui delivers it. +fn press(app: &mut PhotocraftApp, key: egui::Key, mods: Modifiers) -> bool { + let ctx = egui::Context::default(); + ctx.input_mut(|i| { + i.modifiers = mods; + i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: mods }); + }); + crate::move_mods::arrow_keys(app, &ctx) +} + +/// #4486: the arrow keys nudge the selected anchors 1 px (⇧ 10 px), one history step per press, +/// as in Photoshop. With no anchor selected they leave the path alone. +#[test] +fn arrow_keys_nudge_the_selected_anchors() { + let mut app = app(Tool::DirectSelection); + with_path(&mut app); + // The path stays targeted after a click on empty canvas, but no anchor is selected. + click(&mut app, [40.0, 120.0], Modifiers::NONE); + click(&mut app, [80.0, 80.0], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::Work)); + let n = steps(&app); + assert!(!press(&mut app, egui::Key::ArrowRight, Modifiers::NONE), "no anchor selected: not Direct Selection's key"); + assert_eq!(steps(&app), n); + click(&mut app, [40.0, 120.0], Modifiers::NONE); + click(&mut app, [120.0, 120.0], Modifiers::SHIFT); + let (before, n) = (work(&app), steps(&app)); + assert!(press(&mut app, egui::Key::ArrowRight, Modifiers::NONE)); + assert_eq!((anchor(&app, 2), anchor(&app, 3)), (Point::new(121.0, 120.0), Point::new(41.0, 120.0))); + assert!(press(&mut app, egui::Key::ArrowDown, Modifiers::SHIFT)); + assert_eq!((anchor(&app, 2), anchor(&app, 3)), (Point::new(121.0, 130.0), Point::new(41.0, 130.0)), "⇧ nudges 10 px"); + assert_eq!(anchor(&app, 0), Point::new(40.0, 40.0), "unselected anchors stay"); + assert_eq!(steps(&app), n + 2, "one history step per press"); + assert!(app.session.undo() && app.session.undo()); + assert_eq!(work(&app), before); +} diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index 486a13dee0..7cdff50af9 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -149,9 +149,17 @@ impl PhotocraftApp { { suggested = dir.join(suggested); } + // The format comes from the extension, so a name typed without one (common where file + // extensions are hidden, #5039) gets the suggested file's extension, as Photoshop's + // Save As appends the extension of the chosen file type. + let suggested_ext = suggested.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase()); self.ask_file(FileDialogRequest::Save { suggested: suggested.to_string_lossy().into_owned() }, move |app, answer| match answer { FileDialogAnswer::SaveTo(path) => { let path = Self::lowercased_extension(app, path); + let path = match &suggested_ext { + Some(ext) if Path::new(&path).extension().is_none() => Path::new(&path).with_extension(ext).to_string_lossy().into_owned(), + _ => path, + }; // The web answers a download name, which has no folder to remember. if let Some(doc) = doc && let Some(dir) = Path::new(&path).parent().filter(|p| !p.as_os_str().is_empty()) diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs index 8e19c67b48..c3f41b487d 100644 --- a/crates/ui-egui/src/file_dialog/tests.rs +++ b/crates/ui-egui/src/file_dialog/tests.rs @@ -290,6 +290,26 @@ fn save_paths_get_a_lowercase_extension_when_the_preference_is_on() { assert_eq!(*written.borrow(), ["/pics/CAT.PSD"], "off keeps the user's spelling"); } +/// #5039: a name typed without an extension (where file extensions are hidden) gets the +/// suggested file's extension, so the save picks its format instead of failing. +#[test] +fn save_paths_without_an_extension_get_the_suggested_one() { + let (mut app, open, written) = app(); + let ctx = egui::Context::default(); + menus::invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap(); + app.poll_file_dialog(&ctx, None); + answer(&open, Some(FileDialogAnswer::SaveTo("/pics/cat".into()))); + app.poll_file_dialog(&ctx, None); + assert_eq!(*written.borrow(), ["/pics/cat.psd"]); + assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/pics/cat.psd")); + // A name that already has an extension is left alone. + menus::invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap(); + app.poll_file_dialog(&ctx, None); + answer(&open, Some(FileDialogAnswer::SaveTo("/pics/dog.png".into()))); + app.poll_file_dialog(&ctx, None); + assert_eq!(*written.borrow(), ["/pics/cat.psd", "/pics/dog.png"]); +} + #[test] fn save_and_export_dialogs_start_beside_the_document() { let (mut app, open, _) = app(); diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index ac1ed2ba7f..492da515b1 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -168,6 +168,12 @@ impl PhotocraftApp { DropTarget::Tabs(slot) => Some(slot), DropTarget::Canvas | DropTarget::Elsewhere => None, }; + // A box still open from an earlier drop (or any Free Transform) is applied first (#4833): + // the queue below places the next file only once no box is open, so a separate drop + // would otherwise wait unseen for ↩. Files dropped together still go one by one. + if target == DropTarget::Canvas && self.ui.transform.is_some() && files.iter().any(|f| !crate::preset_files_ui::is_preset_file(&dropped_name(f))) { + crate::transform_tool::commit(self); + } for f in files { let name = dropped_name(&f); if target == DropTarget::Canvas && !crate::preset_files_ui::is_preset_file(&name) { diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 0177fc8381..bdefab6229 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -464,6 +464,29 @@ fn files_dropped_onto_the_canvas_are_placed_in_free_transform_one_by_one() { let _ = std::fs::remove_dir_all(&dir); } +/// #4833: a file dropped on the canvas on its own while the previous one is still in Free +/// Transform applies that box and is placed at once, instead of waiting unseen for ↩. +#[test] +fn a_separate_drop_applies_the_open_transform_and_places_at_once() { + let ctx = egui::Context::default(); + let mut app = app_with_canvas(); + let (layers, steps) = (layer_count(&app), history_steps(&app)); + let at = Some(egui::pos2(400.0, 300.0)); + app.open_dropped(&ctx, vec![dropped("first.png", Ok(png_bytes(4, 4)))], at); + app.place_next_dropped(&ctx); + assert!(app.ui.transform.is_some(), "the first file is in Free Transform"); + app.open_dropped(&ctx, vec![dropped("second.png", Ok(png_bytes(2, 2)))], at); + app.place_next_dropped(&ctx); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().name, "second", "placed without waiting for ↩"); + assert_eq!(app.ui.transform.as_ref().and_then(|t| t.made), Some(crate::state::MadeLayer::Place)); + // The first place was applied, not taken back: both layers, one Place Embedded step each. + assert_eq!(layer_count(&app), layers + 2); + assert!(app.drop_places.is_empty()); + crate::transform_tool::commit(&mut app); + assert_eq!(history_steps(&app), steps + 2); +} + /// #1099: switching tabs after an actual canvas drop cancels the place in its source document. #[test] fn switching_documents_after_a_canvas_drop_undoes_only_the_place() { diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs index f118798aab..6cceb79e1f 100644 --- a/crates/ui-egui/src/filter_dialog.rs +++ b/crates/ui-egui/src/filter_dialog.rs @@ -385,6 +385,36 @@ fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map) { + let Some(st) = app.session.active() else { return }; + let Some(spec) = photocraft_engine::commands::find("edit.assignProfile") else { return }; + let space = photocraft_engine::color_cmds::mode_space(st.doc.mode); + let fits = |name: &str| name == "none" || app.session.color.resolve(name, Some(&st.doc), None).is_ok_and(|p| p.color_space == space); + let builtin: Vec = parse_spec(spec.params) + .into_iter() + .filter(|p| p.key == "profile") + .flat_map(|p| match p.kind { + Kind::Choice { options, .. } => options, + _ => Vec::new(), + }) + .collect(); + let installed: Vec<_> = photocraft_engine::installed_profiles::installed().into_iter().filter(|i| i.is_destination()).collect(); + let allowed: Vec = + builtin.iter().filter(|name| fits(name)).cloned().chain(installed.iter().filter(|i| i.color_space == space).map(|i| i.path.clone())).collect(); + // A path nobody lists (typed by an agent) is left alone: the command decides about it. + let listed = |cur: &str| builtin.iter().any(|name| name == cur) || installed.iter().any(|i| i.path == cur); + if fields.get("profile").and_then(Value::as_str).is_some_and(|cur| listed(cur) && !allowed.iter().any(|name| name == cur)) { + fields.insert("profile".into(), json!("working")); + } + fields.insert("__profiles".into(), json!(allowed)); } /// Alt+Cancel (Reset): schema defaults + command hooks, without last-used remembered prefs. @@ -665,6 +695,12 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { Vec::new() }; opts.extend(installed.iter().map(|i| (i.path.clone(), i.description.as_str()))); + // Assign Profile: only what the document's colour mode can take (#4951). + if p.key == "profile" + && let Some(allowed) = f.get("__profiles").and_then(Value::as_array) + { + opts.retain(|(v, _)| allowed.iter().any(|a| a.as_str() == Some(v.as_str()))); + } // A profile given by path that isn't listed (typed by an agent, or spelled with // different case) still shows, by its file name, instead of a blank menu. let stem = std::path::Path::new(&cur).file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); @@ -1931,6 +1967,61 @@ mod tests { } } + /// The profiles Assign Profile offers for a new document converted with `mode` (if any), + /// and which of the command's built-in profiles the command itself accepts for it. + fn assign_profile_offers(mode: Option<&str>) -> (Vec, Vec) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + if let Some(mode) = mode { + app.run(mode, json!({})).unwrap(); + } + open(&mut app, "edit.assignProfile").unwrap(); + let offered: Vec = + app.ui.dialogs.last().unwrap().fields["__profiles"].as_array().unwrap().iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(); + let spec = photocraft_engine::commands::find("edit.assignProfile").unwrap(); + let builtin = parse_spec(spec.params).into_iter().find(|p| p.key == "profile").unwrap(); + let Kind::Choice { options, .. } = builtin.kind else { panic!("profile is a menu") }; + let accepted = options.into_iter().filter(|name| app.session.execute("edit.assignProfile", json!({"profile": name})).is_ok()).collect(); + (offered, accepted) + } + + /// #4951: Assign Profile lists the profiles the command accepts for the document's colour + /// mode, and none of the others. + #[test] + fn assign_profile_offers_only_profiles_of_the_documents_colour_mode() { + for mode in [None, Some("image.mode.cmyk"), Some("image.mode.grayscale")] { + let (offered, accepted) = assign_profile_offers(mode); + for name in &accepted { + assert!(offered.contains(name), "{mode:?}: {name} can be assigned, so it is offered"); + } + for name in ["srgb", "coated-cmyk", "sgray"] { + assert_eq!(offered.iter().any(|o| o == name), accepted.iter().any(|a| a == name), "{mode:?}: {name}"); + } + assert!(offered.iter().any(|o| o == "working") && offered.iter().any(|o| o == "none"), "{mode:?}: working space and none always fit"); + } + let (rgb, _) = assign_profile_offers(None); + assert!(rgb.iter().any(|o| o == "srgb") && !rgb.iter().any(|o| o == "coated-cmyk"), "an RGB document gets RGB profiles"); + let (cmyk, _) = assign_profile_offers(Some("image.mode.cmyk")); + assert!(cmyk.iter().any(|o| o == "coated-cmyk") && !cmyk.iter().any(|o| o == "srgb"), "a CMYK document gets CMYK profiles"); + } + + /// #4951: a profile remembered from a document of another colour mode isn't preselected. + #[test] + fn assign_profile_drops_a_remembered_profile_that_does_not_fit() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.session.prefs.edit(|prefs| { + prefs.dialogs.insert("edit.assignProfile".into(), json!({"profile": "coated-cmyk"})); + }); + open(&mut app, "edit.assignProfile").unwrap(); + assert_eq!(app.ui.dialogs.last().unwrap().fields["profile"], json!("working")); + app.session.prefs.edit(|prefs| { + prefs.dialogs.insert("edit.assignProfile".into(), json!({"profile": "display-p3"})); + }); + open(&mut app, "edit.assignProfile").unwrap(); + assert_eq!(app.ui.dialogs.last().unwrap().fields["profile"], json!("display-p3"), "one that fits is kept"); + } + #[test] fn schema_dialogs_respect_explicit_dropdown_defaults() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs index e73c59985a..bcf0e69516 100644 --- a/crates/ui-egui/src/gpu_canvas.rs +++ b/crates/ui-egui/src/gpu_canvas.rs @@ -638,14 +638,14 @@ impl GpuCanvas { let mut renderer = self.rs.renderer.write(); let Some(res) = renderer.callback_resources.get_mut::() else { return }; if res.docs.keys().any(|k| !live.contains(k)) { - let gone: Vec = res.docs.keys().filter(|k| !live.contains(k)).copied().collect(); - if let Some(c) = res.compositor.as_mut() { - for k in &gone { - c.forget_doc(photocraft_doc::DocId(*k)); - } - } res.docs.retain(|k, _| live.contains(k)); } + // Everything the compositor holds for documents that aren't open, also when their + // texture entry was dropped earlier (over budget, a failed render), which used to leave + // their pages and effect maps resident after closing (#4529). + if let Some(c) = res.compositor.as_mut() { + c.retain_docs(|d| live.contains(&d.0)); + } // LUTs and identity-transform signatures can outlive document textures. Prune both, // or a preserved-ID reopen can skip rebuilding a missing LUT. res.luts.retain(|k, _| live.contains(&k.0)); diff --git a/crates/ui-egui/src/gradient_ui.rs b/crates/ui-egui/src/gradient_ui.rs index 5590c13f25..be35f66028 100644 --- a/crates/ui-egui/src/gradient_ui.rs +++ b/crates/ui-egui/src/gradient_ui.rs @@ -678,6 +678,25 @@ pub fn options_changed(app: &mut PhotocraftApp, before: &crate::state::ToolOptio let _ = app.run(cmds::SET, p); } +/// Live mode: the options bar's Opacity sets a selected gradient fill layer's opacity, as a +/// drag's `opacity` does, live while it is scrubbed; `drag` numbers the scrub so it is one undo +/// step, as in the Layers panel (#5012). +pub fn opacity_changed(app: &mut PhotocraftApp, drag: Option) { + let o = &app.ui.tool_options; + if app.ui.tool != Tool::Gradient || o.gradient_classic { + return; + } + let opacity = o.fill_opacity / 100.0; + let Some((l, ..)) = active_gradient(app) else { return }; + if (l.opacity - opacity).abs() > 1e-6 { + let mut p = json!({"layer": l.id.0, "opacity": opacity}); + if let Some(n) = drag { + p["coalesce"] = json!(format!("gradient-tool-opacity:{n}")); + } + let _ = app.run("layer.setProps", p); + } +} + // ---------------------------------------------------------------- Properties panel /// Properties panel for a live gradient. Every change uses the existing gradient commands. @@ -1257,6 +1276,27 @@ mod tests { assert_eq!(layer.blend, BlendMode::Difference); } + #[test] + fn changing_live_gradient_opacity_updates_selected_fill_layer() { + let mut app = app_with_gradient("linear"); + drag(&mut app, [20.0, 60.0], [180.0, 60.0]); + let past = app.session.active().unwrap().history.past_len(); + // A scrub is live on every frame and one undo step. + for pct in [70.0, 55.0, 40.0] { + app.ui.tool_options.fill_opacity = pct; + opacity_changed(&mut app, Some(7)); + } + opacity_changed(&mut app, None); + let st = app.session.active().unwrap(); + assert!((st.doc.layers.last().unwrap().opacity - 0.4).abs() < 1e-6); + assert_eq!(st.history.past_len(), past + 1, "one undo step, none for an unchanged value"); + // Classic mode paints pixels: the options bar leaves the layer alone. + app.ui.tool_options.gradient_classic = true; + app.ui.tool_options.fill_opacity = 80.0; + opacity_changed(&mut app, None); + assert!((app.session.active().unwrap().doc.layers.last().unwrap().opacity - 0.4).abs() < 1e-6); + } + #[test] fn preview_shows_the_drag_before_commit() { let mut app = app_with_gradient("radial"); diff --git a/crates/ui-egui/src/guide_layout_ui.rs b/crates/ui-egui/src/guide_layout_ui.rs index 9117baa829..8d47e628c8 100644 --- a/crates/ui-egui/src/guide_layout_ui.rs +++ b/crates/ui-egui/src/guide_layout_ui.rs @@ -157,6 +157,10 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result