From 88ed837a86e5c8489c504f0c3aefb5756abece26 Mon Sep 17 00:00:00 2001 From: Gert Pellin - GPE Date: Tue, 13 Oct 2026 17:56:16 +0200 Subject: [PATCH 001/107] Save for Web: JPEG chroma is full (4:4:4) above quality 50, as in Photoshop (#4823) Save for Web subsampled the chroma (4:2:0) up to quality 89. Photoshop 2025's Save for Web writes 4:2:0 up to quality 50 and 4:4:4 from 51 (measured on its output; its Save As keeps 4:2:0 at every quality, as PhotoCraft's Save As already does). Fixes #4822 --- crates/codecs/src/web.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) 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(); From cb6ccaafc4efdfcef11da5e2897252c25115989a Mon Sep 17 00:00:00 2001 From: Gert Pellin - GPE Date: Tue, 13 Oct 2026 17:56:21 +0200 Subject: [PATCH 002/107] Flat export: a Lab document with one layer isn't reported as flattened (#4853) Lab skips the native single-layer path (the codecs have no Lab layout) and goes through the sRGB composite, which always warned that the layers were flattened. With a single plain layer nothing is flattened: only the sRGB conversion is reported now. Fixes #4852 --- crates/io/src/flat.rs | 12 ++++++++---- crates/io/tests/flat.rs | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) 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/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); +} From 5c73f4fffae0d9f658e7a075d251ce4749be8dad Mon Sep 17 00:00:00 2001 From: Marco Arnulfo <103679419+marcoarnulfo@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:56:27 +0200 Subject: [PATCH 003/107] TIFF: save uncompressed by default, like Photoshop (fixes #4484) (#4491) --- crates/codecs/src/options.rs | 7 ++++--- crates/codecs/tests/tiff_regressions.rs | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) 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/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"); + } +} From 1735c81e67ca4a19539d2c8904f4f160fe662b5e Mon Sep 17 00:00:00 2001 From: LloydNicholson <34131158+LloydNicholson@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:56:34 +0200 Subject: [PATCH 004/107] fix(segment): stop push/relabel looping forever on unreachable nodes (#4869) Remove Background (and Select Subject's full-resolution refinement) could hang at "Finding subject" on some photos. One refinement tile's max-flow never finished, and the job ignores Cancel there. Push/relabel's admissibility test was `dist[i] == dist[j].saturating_add(1)`. A global relabel gives nodes reachable from neither terminal the height u32::MAX, and MAX.saturating_add(1) == MAX, so two such neighbours counted as admissible for each other. When f32 rounding strands excess on them (source capacities near 3e8 have an ulp of 32), they pushed it back and forth forever. Use checked_add so an unreachable node is never a push target; its excess stays put and the loop ends. The regression test is a 6-node graph that looped before and now matches the Boykov-Kolmogorov cut. Co-authored-by: lloyd Co-authored-by: Claude Opus 5.5 --- .../algo/src/segment/maxflow/push_relabel.rs | 5 +++- .../src/segment/maxflow/push_relabel/tests.rs | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) 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::>()); +} From 41e578b4d341496ea12b886b6dcb35b34e3d636c Mon Sep 17 00:00:00 2001 From: mroxso <24775431+mroxso@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:56:40 +0200 Subject: [PATCH 005/107] fix(io): a version 3 Photo Filter colour is XYZ relative to the D50 white (#4987) Photoshop CS2 stores the phfl version 3 colour as XYZ divided by the D50 white point (X / 0.9642, Y, Z / 0.8249), so white is (32768, 32768, 32768). We read those values as absolute D50 XYZ, giving every CS2 Photo Filter a slightly wrong colour: the Yellow filter preset (24191, 25002, 3827) decoded to #FFE03A instead of #F9E31C, and Warming Filter (85) (15548, 12029, 0) to #F18600 instead of #EC8A00. Multiply by the white point before converting; decoded this way, every version 3 colour in the reporter's CS2 files is exactly a Photoshop preset (#4940). Fixes #4940 Co-authored-by: highperfocused --- crates/io/src/adjust_map.rs | 44 +++++++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 14 deletions(-) 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. From 40c9c3c451e736064ea866da1fd49a3ccb99bd15 Mon Sep 17 00:00:00 2001 From: Nigel Ihza Firdausy <106657905+Ni-zav@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:56:47 +0700 Subject: [PATCH 006/107] Validate merged PSD channel indices before decoding (#4994) * fix(psd): validate merged channel index before decoding (#4981) * test(psd): compare decoded channel bytes as vectors --- crates/psd/src/image_data.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) 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}"); + } +} From ccb33741f9dc51ac070aa9fe661f6f7cd4a66352 Mon Sep 17 00:00:00 2001 From: Nigel Ihza Firdausy <106657905+Ni-zav@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:56:55 +0700 Subject: [PATCH 007/107] fix(psd): reserve imported layer IDs when allocating section dividers (#4885) --- crates/io/src/psd_export.rs | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) 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. From 13047650672ee87d258149a5c5cea68727c8228a Mon Sep 17 00:00:00 2001 From: Jyrki Vesterinen Date: Tue, 13 Oct 2026 19:01:34 +0300 Subject: [PATCH 008/107] fix(canvas): Fit View opens small images at 100%, not at the display scale (#5089) fit_view capped the fit at 1.0 in egui points and then multiplied by pixels-per-point, so on a 150% display a small image opened at 150%. Since View::zoom became physical pixels per document pixel (27263bb16, #1978) the cap has to apply after the conversion: scale by ppp first, then min(1.0). The test for fit_view asserted the old value (zoom 2.0 at ppp 2.0); it now checks a small image opens at 1.0 for ppp 1.0, 1.5 and 2.0 and that a large image still shrinks to fit. Co-authored-by: Claude Sonnet 5.5 --- crates/ui-egui/src/canvas.rs | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 231b4612ca..ea6da72539 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; @@ -7228,13 +7230,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] From 6f9227efa3fce3fb34e436692e791cd4860bea29 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Tue, 13 Oct 2026 12:01:40 -0400 Subject: [PATCH 009/107] Brush Settings: no section title above the options pane (#3477) (#5017) * Brush Settings: no section title above the options pane (#3477) The options pane repeated the selected section's name as a title line. The selected row in the section list already names it, as in Photoshop, so the title is gone and the options start at the top of the pane. Co-Authored-By: Claude Opus 5.5 * i18n test: the brush section name is drawn once, without a heading (#3477) dynamic_brush_sections_have_translations_and_draw_in_the_selected_language still expected the translated section name twice: the list row and the options pane heading this branch removes. It now expects the row alone. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/brush_panel.rs | 7 +++---- crates/ui-egui/src/brush_panel_tests.rs | 25 ++++++++++++++++++++++--- crates/ui-egui/src/i18n/live_tests.rs | 3 ++- 3 files changed, 27 insertions(+), 8 deletions(-) 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..6b929cd83b 100644 --- a/crates/ui-egui/src/brush_panel_tests.rs +++ b/crates/ui-egui/src/brush_panel_tests.rs @@ -992,7 +992,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 +1017,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/i18n/live_tests.rs b/crates/ui-egui/src/i18n/live_tests.rs index 6ab8b340ad..b02da6f3ce 100644 --- a/crates/ui-egui/src/i18n/live_tests.rs +++ b/crates/ui-egui/src/i18n/live_tests.rs @@ -93,7 +93,8 @@ fn dynamic_brush_sections_have_translations_and_draw_in_the_selected_language() h.state_mut().ui.panels.brush_settings = true; h.run_steps(4); let text = drawn_text(&h); - assert!(text.iter().filter(|text| text.as_str() == "画笔笔尖形状").count() >= 2, "both the section row and heading must be translated"); + // The section row is the only place the name is drawn: the options pane has no heading (#3477). + assert_eq!(text.iter().filter(|text| text.as_str() == "画笔笔尖形状").count(), 1, "the section row must be translated"); assert!(!text.iter().any(|text| text == "Brush Tip Shape")); }); } From 26e003059bc0f9599acfd4418a44ea3d57d5862e Mon Sep 17 00:00:00 2001 From: mroxso <24775431+mroxso@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:01:47 +0200 Subject: [PATCH 010/107] fix(ui): a save name without an extension gets the suggested one (#5039) (#5049) Co-authored-by: highperfocused --- crates/ui-egui/src/file_dialog.rs | 8 ++++++++ crates/ui-egui/src/file_dialog/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+) 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(); From 9a4efabe22c83114d6ba633b09898419dda6b377 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo <103679419+marcoarnulfo@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:01:54 +0200 Subject: [PATCH 011/107] A file dropped on the canvas applies the open Free Transform and is placed at once (fixes #4833) (#4849) --- crates/ui-egui/src/file_open.rs | 6 ++++++ crates/ui-egui/src/file_open/tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+) 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() { From 78dea7c6e4b5154769d48931839348f2f1371f19 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo <103679419+marcoarnulfo@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:02:01 +0200 Subject: [PATCH 012/107] fix(ui): an open Free Transform box takes Zoom tool drags and clicks (part of #4799) (#4808) --- crates/ui-egui/src/canvas.rs | 5 ++-- crates/ui-egui/src/transform_undo_tests.rs | 27 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ea6da72539..c9425910e7 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3255,7 +3255,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 @@ -3389,7 +3390,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); diff --git a/crates/ui-egui/src/transform_undo_tests.rs b/crates/ui-egui/src/transform_undo_tests.rs index 2944456c88..832b221900 100644 --- a/crates/ui-egui/src/transform_undo_tests.rs +++ b/crates/ui-egui/src/transform_undo_tests.rs @@ -241,6 +241,33 @@ fn the_hand_tool_does_not_steal_a_free_transform_drag() { assert!(width(&h) > 150, "the committed resize applied: {}", width(&h)); } +/// With the Zoom tool selected, a Free Transform drag resizes the box rather than zooming the view: +/// the open box owns the pointer, as it does for the Hand (#4799). +#[test] +fn the_zoom_tool_does_not_steal_a_free_transform_drag() { + let mut h = harness_tool(Tool::Zoom); + begin(&mut h); + let q0 = quad(&h); + let (zoom0, center0) = (h.state().ui.views[0].zoom, h.state().ui.views[0].center); + let inside = screen(&h, [150.0, 130.0]); + h.event(egui::Event::PointerMoved(inside)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: inside, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(2); + assert_eq!(h.state().ui.views[0].zoom, zoom0, "a click inside the box did not zoom"); + drag(&mut h, q0[2], [300.0, 220.0]); + let q1 = quad(&h); + assert!(!close(q1, q0), "the drag scaled the box, not the view: {q1:?}"); + assert_eq!(h.state().ui.views[0].zoom, zoom0, "the Zoom tool did not zoom"); + assert_eq!(h.state().ui.views[0].center, center0, "the Zoom tool did not move the view"); + key(&mut h, Modifiers::NONE, Key::Enter); + assert!(h.state().ui.transform.is_none(), "the transform committed"); + assert!(width(&h) > 150, "the committed resize applied: {}", width(&h)); +} + /// With the (freehand) Lasso selected, a Free Transform of a lasso selection follows the drag: the /// Lasso reads its own pointer events, and dropped the moves and release of a drag it hadn't /// started, so the box never changed (#2153). From e50b25f45c6ffba3157699bebd03ad891c18d7f3 Mon Sep 17 00:00:00 2001 From: F4LCON <107556180+itsF4LCON@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:02:07 +0200 Subject: [PATCH 013/107] Shapes: test that the options bar Fill swatch recolours the shape just drawn (#3997, #3999) (#4510) In v0.7.0 the options bar's Fill swatch only previewed the foreground colour, so a drawn shape's fill could not be changed from it while Stroke could. Main fixed that in #3019 and #3370; this test covers the reported steps (draw a rectangle, pick a colour from the Fill swatch): the fill changes, the stroke does not, and it is one undo step. --- crates/ui-egui/src/vector_paint_tests.rs | 31 ++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/ui-egui/src/vector_paint_tests.rs b/crates/ui-egui/src/vector_paint_tests.rs index 15a0c3f92c..c62277fb1e 100644 --- a/crates/ui-egui/src/vector_paint_tests.rs +++ b/crates/ui-egui/src/vector_paint_tests.rs @@ -285,3 +285,34 @@ fn selected_shape_colour_drags_apply_live_coalesce_per_gesture_and_keep_tool_def h.state_mut().run("edit.redo", json!({})).unwrap(); assert_eq!(shape(h.state()).fill, first.fill); } + +/// #3997, #3999: after drawing a shape, the options bar's Fill swatch recolours it, as Stroke +/// does (in v0.7.0 the Fill swatch was only a preview of the foreground colour). +#[test] +fn options_bar_fill_swatch_recolours_the_shape_just_drawn() { + let mut app = app("rgb", 8); + app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); + app.ui.tool_options.stroke_width = 3.0; + finish_shape(&mut app, Tool::Rectangle, [20.0, 20.0], [100.0, 80.0], Modifiers::NONE); + let original = shape(&app).clone(); + let history = app.session.active().unwrap().history.past_len(); + let mut h = harness(app, false); + h.get_by_label("Fill color").click(); + h.run_steps(4); + let rect = popup_rect(&h); + let start = rect.min + vec2(55.0, rect.height() * 0.5); + h.hover_at(start); + h.step(); + pointer(&mut h, start, true); + h.event(Event::PointerMoved(start + vec2(30.0, 6.0))); + h.step(); + pointer(&mut h, start + vec2(30.0, 6.0), false); + h.run_steps(2); + let edited = shape(h.state()).clone(); + assert_ne!(edited.fill, original.fill, "the Fill swatch recoloured the shape"); + assert_eq!(edited.fill.as_ref().and_then(color_of), Some(h.state().session.tools.foreground), "and the next shape's fill"); + assert_eq!(edited.stroke, original.stroke, "the stroke is untouched"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), history + 1); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(shape(h.state()).fill, original.fill); +} From 3d54e8cd68e128fb14f7ae95ad166792858423a2 Mon Sep 17 00:00:00 2001 From: F4LCON <107556180+itsF4LCON@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:02:12 +0200 Subject: [PATCH 014/107] Alerts: Enter is OK, but not the Enter that raised the alert (#4872) (#4880) --- crates/ui-egui/src/dialogs.rs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7ae2730bd0..7b747f42fb 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -338,7 +338,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 +802,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(); From 334d378f0f2d49637a405ec30e7bb2a1bf0c2b05 Mon Sep 17 00:00:00 2001 From: Dan Hiorns Date: Tue, 13 Oct 2026 10:02:26 -0600 Subject: [PATCH 015/107] Toolbar: clicking a tool's button again closes its open flyout (#4932) (#4937) A right-click (or long press) on a tool button opens the flyout of the tools grouped with it. Any press outside the flyout closed it, but the press-outside check leaves out the tool button itself, so clicking that button again, with either mouse button, left the flyout open. A click on the button of its open flyout now closes it, as in Photoshop: a right-click just closes it, a left click closes it and picks the tool as any click does. The release that ends the long press that opened the flyout still keeps it open. Fixes #4932 Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/panels.rs | 40 ++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 2ab7fbf794..a7f0347822 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -189,7 +189,14 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(0.35 - seconds)); } let long_press = held_for.is_some_and(|seconds| seconds >= 0.35); - if slot.len() > 1 && (resp.secondary_clicked() || long_press) { + // Clicking the button of its open flyout again, with either button, closes + // it (#4932); the release that ends the long press that opened it doesn't. + let open_here = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id)).is_some_and(|(k, _)| k == key); + let reclicked = open_here + && (resp.secondary_clicked() || (resp.clicked() && ui.data(|d| d.get_temp::(held_id)) != Some(key))); + if reclicked { + ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id)); + } else if slot.len() > 1 && (resp.secondary_clicked() || long_press) { ui.data_mut(|d| { d.insert_temp(flyout_id, (key, resp.rect)); if long_press { @@ -4901,6 +4908,7 @@ mod type_flyout_tests { /// #4460: a press outside an open flyout closes it, even when it becomes a drag (cropping or /// painting on the canvas) rather than a click; a press on the flyout keeps it for its pick. + /// #4932: so does a click on its own tool button. #[test] fn a_drag_outside_closes_the_tool_flyout() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -4924,10 +4932,13 @@ mod type_flyout_tests { let flyout = |ctx: &egui::Context| ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::new("tool-flyout"))).is_some(); let secondary = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }; let primary = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + // A right-click on the button of an open flyout closes it (#4932), so open only a closed one. let open = |app: &mut PhotocraftApp, t: f64| { - frame(app, &ctx, t, vec![egui::Event::PointerMoved(at), secondary(true)]); - frame(app, &ctx, t + 0.05, vec![secondary(false)]); - frame(app, &ctx, t + 0.1, vec![]); + if !flyout(&ctx) { + frame(app, &ctx, t, vec![egui::Event::PointerMoved(at), secondary(true)]); + frame(app, &ctx, t + 0.05, vec![secondary(false)]); + frame(app, &ctx, t + 0.1, vec![]); + } assert!(flyout(&ctx), "right-click opens it"); }; // A press on the flyout itself keeps it open (the row picks on release). @@ -4944,6 +4955,27 @@ mod type_flyout_tests { assert!(!flyout(&ctx), "a press outside closes it, even one that becomes a drag"); frame(&mut app, &ctx, 2.6, vec![primary(canvas + vec2(80.0, 60.0), false)]); assert!(!flyout(&ctx)); + // #4932: clicking its own tool button again closes it, with either button. + open(&mut app, 3.0); + frame(&mut app, &ctx, 3.5, vec![egui::Event::PointerMoved(at), secondary(true)]); + frame(&mut app, &ctx, 3.55, vec![secondary(false)]); + frame(&mut app, &ctx, 3.6, vec![]); + assert!(!flyout(&ctx), "a second right-click on the button closes it"); + open(&mut app, 4.0); + app.ui.tool = Tool::Move; + frame(&mut app, &ctx, 4.5, vec![egui::Event::PointerMoved(at), primary(at, true)]); + frame(&mut app, &ctx, 4.55, vec![primary(at, false)]); + frame(&mut app, &ctx, 4.6, vec![]); + assert!(!flyout(&ctx), "a click on the button closes it"); + assert_eq!(app.ui.tool, Tool::Brush, "and picks the tool, as any click on it does"); + // The release that ends a long press keeps the flyout it opened. + frame(&mut app, &ctx, 5.0, vec![egui::Event::PointerMoved(at), primary(at, true)]); + frame(&mut app, &ctx, 5.2, vec![]); + frame(&mut app, &ctx, 5.5, vec![]); + assert!(flyout(&ctx), "a long press opens it"); + frame(&mut app, &ctx, 5.55, vec![primary(at, false)]); + frame(&mut app, &ctx, 5.6, vec![]); + assert!(flyout(&ctx), "releasing the long press keeps it open"); } #[test] From 2ec1c8c0aaaccd0b1f627e9af50cc7f141248f09 Mon Sep 17 00:00:00 2001 From: Sir Starch Date: Tue, 13 Oct 2026 18:02:32 +0200 Subject: [PATCH 016/107] Themes: default light theme to Pro Light to preserve the Pro layout (#5016) (#5029) When appearance mode was toggled between dark and light with default settings, PhotoCraft switched from Pro Medium (Pro layout) to Studio Light (Studio layout), altering the UI and displaying a Fit button in the status bar. Now that the Photoshop Pro light brightness levels exist (#2661), default the saved light theme to Pro Light so the Pro interface layout and status bar are preserved when toggling appearance. Also map the "light" alias to Pro Light and list the Pro options first under Light Theme preferences. Fixes #5016. --- crates/engine/src/prefs.rs | 4 ++-- crates/engine/src/prefs/tests.rs | 4 ++-- crates/ui-egui/src/prefs_ui.rs | 12 ++++++------ crates/ui-egui/src/status_bar_tests.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/theme.rs | 5 +++-- docs/ui-design.md | 2 +- 6 files changed, 36 insertions(+), 13 deletions(-) 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/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index cf0ff51969..f1da8775a9 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -129,9 +129,9 @@ pub(crate) fn cycle_appearance(app: &mut PhotocraftApp, ctx: &egui::Context) { } const LIGHT_THEME_OPTIONS: &[(&str, ThemeKind)] = &[ - ("studioLight", ThemeKind::StudioLight), - ("proLightGray", ThemeKind::ProLightGray), ("proLight", ThemeKind::ProLight), + ("proLightGray", ThemeKind::ProLightGray), + ("studioLight", ThemeKind::StudioLight), ("classic", ThemeKind::Classic), ("adwaita", ThemeKind::Adwaita), ("breezeLight", ThemeKind::BreezeLight), @@ -2078,7 +2078,7 @@ mod tests { fn appearance_resolves_both_saved_themes_and_follows_system() { let mut interface = prefs::Interface { appearance_mode: AppearanceMode::Auto, ..prefs::Interface::default() }; assert_eq!(selected_theme(&interface, Some(egui::Theme::Dark)), ThemeKind::ProMedium); - assert_eq!(selected_theme(&interface, Some(egui::Theme::Light)), ThemeKind::StudioLight); + assert_eq!(selected_theme(&interface, Some(egui::Theme::Light)), ThemeKind::ProLight); interface.dark_theme = DarkTheme::Studio; interface.light_theme = LightTheme::Classic; assert_eq!(selected_theme(&interface, Some(egui::Theme::Dark)), ThemeKind::Studio); @@ -2119,7 +2119,7 @@ mod tests { app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": "auto"})).unwrap(); let ctx = egui::Context::default(); tick(&mut app, &ctx); - assert_eq!(app.ui.theme, ThemeKind::StudioLight); + assert_eq!(app.ui.theme, ThemeKind::ProLight); } #[test] @@ -2232,13 +2232,13 @@ mod tests { ctx.set_theme(egui::ThemePreference::Dark); assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::Dark); appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); - assert_palette(&ctx, ThemeKind::StudioLight); + assert_palette(&ctx, ThemeKind::ProLight); assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto); // A restored pin must also clear when the concrete PhotoCraft palette stays the same. ctx.set_theme(egui::ThemePreference::Dark); appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System); - assert_palette(&ctx, ThemeKind::StudioLight); + assert_palette(&ctx, ThemeKind::ProLight); appearance_frame(&mut app, &ctx, Some(egui::Theme::Dark)); assert_palette(&ctx, ThemeKind::ProMedium); assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto); diff --git a/crates/ui-egui/src/status_bar_tests.rs b/crates/ui-egui/src/status_bar_tests.rs index 5f2e576853..eebd7e84bc 100644 --- a/crates/ui-egui/src/status_bar_tests.rs +++ b/crates/ui-egui/src/status_bar_tests.rs @@ -196,3 +196,25 @@ fn fullscreen_status_zoom_preserves_shift_precision_and_recovers_from_the_minimu h.run_steps(1); assert!(h.state().ui.views[0].zoom > minimum, "reversing direction responds immediately after reaching a bound"); } + +/// #5016: toggling appearance between dark and light with default settings preserves the Pro +/// layout and does not make a Fit button appear. +#[test] +fn appearance_toggle_preserves_pro_layout_and_has_no_fit_button() { + let mut h = harness(ThemeKind::ProMedium); + assert!(h.query_by_label("Fit").is_none()); + assert!(Tokens::get(&h.ctx).pro); + + // Switch to Light mode (top-bar appearance button). + let ctx = h.ctx.clone(); + crate::prefs_ui::cycle_appearance(h.state_mut(), &ctx); + if h.state().session.prefs().interface.appearance_mode == photocraft_engine::prefs::AppearanceMode::Auto { + crate::prefs_ui::cycle_appearance(h.state_mut(), &ctx); + } + crate::prefs_ui::tick(h.state_mut(), &ctx); + h.run_steps(3); + assert_eq!(h.state().session.prefs().interface.appearance_mode, photocraft_engine::prefs::AppearanceMode::Light); + assert_eq!(h.state().ui.theme, ThemeKind::ProLight); + assert!(Tokens::get(&h.ctx).pro); + assert!(h.query_by_label("Fit").is_none(), "Fit button must not appear in light mode (#5016)"); +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index eb61cfbeaf..0b2cc7c044 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -122,9 +122,9 @@ impl ThemeKind { "pro" | "prodark" | "photoshop" | "dark" => Some(ThemeKind::Pro), "promedium" | "promediumgray" | "medium" | "mediumgray" => Some(ThemeKind::ProMedium), "prolightgray" | "lightgray" | "mediumlight" => Some(ThemeKind::ProLightGray), - "prolight" | "prolightest" | "lightest" => Some(ThemeKind::ProLight), + "prolight" | "prolightest" | "lightest" | "light" => Some(ThemeKind::ProLight), "studio" | "studiodark" => Some(ThemeKind::Studio), - "studiolight" | "light" => Some(ThemeKind::StudioLight), + "studiolight" => Some(ThemeKind::StudioLight), "classic" | "win2000" | "retro" => Some(ThemeKind::Classic), "adwaita" | "adwaitalight" | "gnome" | "gnomelight" => Some(ThemeKind::Adwaita), "adwaitadark" | "gnomedark" => Some(ThemeKind::AdwaitaDark), @@ -1202,6 +1202,7 @@ mod tests { assert_eq!(ThemeKind::from_name("Classic"), Some(ThemeKind::Classic)); assert_eq!(ThemeKind::from_name("studio (light)"), Some(ThemeKind::StudioLight)); assert_eq!(ThemeKind::from_name("dark"), Some(ThemeKind::Pro)); + assert_eq!(ThemeKind::from_name("light"), Some(ThemeKind::ProLight)); assert_eq!(ThemeKind::from_name("studio"), Some(ThemeKind::Studio)); assert_eq!(ThemeKind::from_name("Pro (Medium Gray)"), Some(ThemeKind::ProMedium)); assert_eq!(ThemeKind::from_name("Solarized Dark"), Some(ThemeKind::SolarizedDark)); diff --git a/docs/ui-design.md b/docs/ui-design.md index 4636cdb7cd..13fd8b99f1 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -19,7 +19,7 @@ Both Breeze themes are our own values close to Plasma's (not a copy of its colour schemes) and put text readability first: every text colour holds 4.5:1 on every surface and on hovered, pressed and selected states (`theme.rs` tests), so their secondary text, accent and status colours are darker (Light) or lighter (Dark) than Breeze's own, and the primary button is a deeper blue with white text. -Edit → Preferences → Interface shows an Appearance Mode selector (Sync with system, Dark, Light) above separate light and dark theme cards with PhotoCraft editor previews and radio choices. Auto is opt-in and follows the operating system while the app is running. On Linux it reads the desktop portal once and then listens for its `SettingChanged` signal (no polling, and the UI repaints only when the value changes); `gsettings` runs at most once at start-up, by absolute path, when the portal gives no answer. A missing system appearance falls back to Dark. New installs keep Photoshop's default: Dark mode with Pro Medium (Studio Light is the saved light theme). Existing saved single-theme preferences migrate to a fixed Dark or Light mode with their chosen theme. The header appearance button cycles Auto → Light → Dark; its icon shows a monitor, moon or sun for the selected mode. Window → Theme and `ui.set {"theme":"classic"}` select a theme and fix the mode to its light or dark family. +Edit → Preferences → Interface shows an Appearance Mode selector (Sync with system, Dark, Light) above separate light and dark theme cards with PhotoCraft editor previews and radio choices. Auto is opt-in and follows the operating system while the app is running. On Linux it reads the desktop portal once and then listens for its `SettingChanged` signal (no polling, and the UI repaints only when the value changes); `gsettings` runs at most once at start-up, by absolute path, when the portal gives no answer. A missing system appearance falls back to Dark. New installs keep Photoshop's default: Dark mode with Pro Medium (Pro Light is the saved light theme). Existing saved single-theme preferences migrate to a fixed Dark or Light mode with their chosen theme. The header appearance button cycles Auto → Light → Dark; its icon shows a monitor, moon or sun for the selected mode. Window → Theme and `ui.set {"theme":"classic"}` select a theme and fix the mode to its light or dark family. Window → Theme and macOS PhotoCraft → Appearance also offer Sync with system. Its checkmark follows the saved Auto mode rather than the displayed palette; choosing a manual theme selects its fixed appearance mode. From eae87bacfaf8ca758cb9d6c472afe33546465686 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20=C2=B7=20VanTan?= <77483789+VanTan666@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:02:38 +0200 Subject: [PATCH 017/107] i18n(ru): translate dynamic selection, theme and measurement labels (#4838) --- crates/ui-egui/src/i18n/mod.rs | 19 +++++++++++++++++++ crates/ui-egui/src/i18n/ru.tsv | 20 ++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index 2fdffdfc69..b976e395fc 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -1201,6 +1201,25 @@ mod tests { assert_eq!(tr(Lang::EN, "Seafoam"), "Seafoam"); } + /// These labels are passed to `tl!` dynamically, so the literal coverage scan misses them. + #[test] + fn russian_dynamic_selection_theme_and_measurement_labels_are_translated() { + let ru = Lang::from_code("ru").expect("ru registered"); + let (inverse_label, _) = + crate::canvas_tool_menu::SELECTION_MENU.iter().flatten().find(|(_, id)| *id == "select.inverse").expect("selection menu has Select Inverse"); + assert_eq!(tr(ru, inverse_label), "Инвертировать выделение"); + for kind in [crate::theme::ThemeKind::ProLight, crate::theme::ThemeKind::ProLightGray] { + assert!(has(ru, kind.label()), "Russian theme label missing {}", kind.label()); + } + for (_, label) in photocraft_engine::analysis_cmds::COLUMNS { + assert!(has(ru, label), "Russian measurement header missing {label}"); + } + assert_eq!(tr(ru, "Pro (Light)"), "Pro (светлая)"); + assert_eq!(tr(ru, "Pro (Light Gray)"), "Pro (светло-серая)"); + assert_eq!(tr(ru, "Date and Time"), "Дата и время"); + assert_eq!(tr(ru, "Integrated Density"), "Интегральная плотность"); + } + /// Font style labels are built from dynamic words (weights, "Italic"), so the literal /// scanner cannot cover them; "Light" there is a weight, distinct from the Camera Raw /// "Light" section (`type_tool::style_label`). diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca950c2e05..cc008ef425 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3071,3 +3071,23 @@ curves Smooth Сгладить @plural {n} action|{n} actions {n} операция|{n} операции|{n} операций Auto Add/Delete Автодобавление/удаление ICO is limited to 256 × 256 pixels ICO ограничен размером 256 × 256 пикселей + +# Dynamic selection context menu and appearance favorites + Select Inverse Инвертировать выделение + Pro (Light) Pro (светлая) + Pro (Light Gray) Pro (светло-серая) + +# Measurement Log column headers (analysis_cmds::COLUMNS) + Label Метка + Date and Time Дата и время + Scale Units Единицы масштаба + Scale Factor Коэффициент масштаба + Area Площадь + Perimeter Периметр + Circularity Круглость + Gray Value (Minimum) Уровень серого (минимум) + Gray Value (Maximum) Уровень серого (максимум) + Gray Value (Mean) Уровень серого (среднее) + Gray Value (Median) Уровень серого (медиана) + Integrated Density Интегральная плотность + Length Длина From 665cb581ad6475042a65f12c00c54c602998b280 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo <103679419+marcoarnulfo@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:02:44 +0200 Subject: [PATCH 018/107] Smart Filters: Delete removes the selected filter, not its smart object (part of #4751) (#4764) --- crates/ui-egui/src/panels.rs | 10 ++++- crates/ui-egui/src/smart_filter_rows_tests.rs | 39 +++++++++++++++++++ crates/ui-egui/src/smart_ui.rs | 20 ++++++++++ 3 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index a7f0347822..601f049eea 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2389,7 +2389,14 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ("layer.delete", "Delete layer") }; let trash = icons::button(ui, "trash", 26.0, false, tl!(label)); - if trash.clicked() { + // A selected smart filter row is what Delete removes, as in Photoshop (#4751). + let picked_filter = crate::smart_ui::selected(&ctx, &doc, active); + if trash.clicked() + && let Some(picked) = picked_filter + { + actions.push(crate::smart_ui::trash_action(picked)); + crate::smart_ui::deselect(&ctx, doc.id); + } else if trash.clicked() { // Like Photoshop, ⌥/Alt-click deletes without asking. let confirm = delete == "layer.delete" && !ui.input(|i| i.modifiers.alt); let params = if confirm { json!({"__trash": true}) } else { json!({}) }; @@ -2844,6 +2851,7 @@ fn layer_row( } else if resp.clicked() && !eye_resp.clicked() && !toggled && !fx_toggled && !masks.clicked { let mode = select_mode(ui.input(|i| i.modifiers)); actions.push(("layer.select".into(), json!({"layer": l.id.0, "mode": mode}))); + crate::smart_ui::deselect(ctx, doc.id); // A thumbnail explicitly selects content or a mask. Selecting an adjustment/fill row // defaults to its mask, but clicking its content thumbnail must leave the mask target. let pos = resp.interact_pointer_pos(); diff --git a/crates/ui-egui/src/smart_filter_rows_tests.rs b/crates/ui-egui/src/smart_filter_rows_tests.rs index 519402672c..da34be9c6c 100644 --- a/crates/ui-egui/src/smart_filter_rows_tests.rs +++ b/crates/ui-egui/src/smart_filter_rows_tests.rs @@ -162,3 +162,42 @@ fn a_camera_raw_filter_copies_and_its_copy_opens_on_the_target() { let dialog = h.state().camera_raw.as_ref().expect("Camera Raw opened"); assert_eq!(dialog.layer, LayerId(b)); } + +fn click_at(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, p: Pos2) { + h.hover_at(p); + h.run_steps(1); + h.drag_at(p); + h.run_steps(1); + h.drop_at(p); + h.run_steps(4); +} + +/// #4751: with a filter's row selected, clicking Delete removes that filter, not the smart object. +#[test] +fn clicking_delete_removes_the_selected_filter() { + let (mut h, a, _, _) = panel(); + let blur = at(&h, "Gaussian Blur"); + click_at(&mut h, blur); + let trash = at(&h, "Delete layer"); + click_at(&mut h, trash); + assert_eq!(filters(&h, a), ["filter.other.offset"]); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), 4, "no layer was deleted"); + // The deleted row's selection doesn't carry over to Offset, now at its index. + click_at(&mut h, trash); + assert_eq!(filters(&h, a), ["filter.other.offset"]); +} + +/// Clicking the smart object's own row leaves its filters: Delete then deletes the layer as usual. +#[test] +fn clicking_the_smart_object_row_deselects_its_filter() { + let (mut h, a, _, _) = panel(); + let offset = at(&h, "Offset"); + click_at(&mut h, offset); + let row = at(&h, "Smart A"); + click_at(&mut h, row); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(LayerId(a))); + assert!(!selected(&h, "Offset")); + let trash = at(&h, "Delete layer"); + click_at(&mut h, trash); + assert_eq!(filters(&h, a).len(), 2, "the filters stay"); +} diff --git a/crates/ui-egui/src/smart_ui.rs b/crates/ui-egui/src/smart_ui.rs index fd1ed6f01c..9932c88669 100644 --- a/crates/ui-egui/src/smart_ui.rs +++ b/crates/ui-egui/src/smart_ui.rs @@ -151,6 +151,26 @@ fn selected_key(doc: photocraft_doc::DocId) -> egui::Id { egui::Id::new(("smart-filter-selected", doc)) } +/// The selected smart filter row, while its smart object is active and the filter still exists. +pub(crate) fn selected(ctx: &egui::Context, doc: &Document, active: Option) -> Option { + let (layer, filter) = ctx.data(|d| d.get_temp::(selected_key(doc.id)))?; + if active != Some(LayerId(layer)) { + return None; + } + let LayerContent::Smart(sm) = &doc.layer(LayerId(layer))?.content else { return None }; + let exists = match filter { + Some(i) => i < sm.smart_filters.len(), + None => !sm.smart_filters.is_empty(), + }; + exists.then_some((layer, filter)) +} + +/// Forgets the selected smart filter row: its smart object's own row was clicked, or the filter +/// was deleted (its index would now name the next one). +pub(crate) fn deselect(ctx: &egui::Context, doc: photocraft_doc::DocId) { + ctx.data_mut(|d| d.remove::(selected_key(doc))); +} + /// While smart filters are dragged: their name by the pointer, and the copy cursor while ⌥ is held. pub(crate) fn drag_feedback(ctx: &egui::Context, doc: &Document) { let Some((from, filter)) = ctx.data(|d| d.get_temp::(drag_key())) else { return }; From 78b70df227c2253e5aa98b26b81d6accef29a93a Mon Sep 17 00:00:00 2001 From: Marco Arnulfo <103679419+marcoarnulfo@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:02:51 +0200 Subject: [PATCH 019/107] Canvas: the CPU canvas shows crisp pixels when zoomed in (fixes #4810) (#4825) --- crates/ui-egui/src/canvas.rs | 54 ++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c9425910e7..43c5012880 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1256,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)> { @@ -1300,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); } @@ -1310,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); @@ -5853,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 { From 997406a58491d118c015b7b0425ee87b74fcafd6 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo <103679419+marcoarnulfo@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:02:58 +0200 Subject: [PATCH 020/107] Layer Style applies an open Free Transform first, so its preview shows (fixes #4821) (#4835) --- crates/ui-egui/src/canvas.rs | 40 +++++++++++++++++++++++++++++++ crates/ui-egui/src/layer_style.rs | 8 +++++++ 2 files changed, 48 insertions(+) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 43c5012880..febb6571ea 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -7261,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()); diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rs index d3606e30b7..af3e36c904 100644 --- a/crates/ui-egui/src/layer_style.rs +++ b/crates/ui-egui/src/layer_style.rs @@ -503,6 +503,14 @@ pub fn initial_fields(layer: &Layer, select: Option<&str>, light: f32) -> Map) -> Option { + // An open Free Transform box is applied first, as in Photoshop (#4821): the canvas shows the + // box's preview while it is open, so the dialog's preview would not show until Enter. + if app.ui.transform.is_some() { + crate::transform_tool::commit(app); + if app.ui.transform.is_some() && crate::transform_tool::committing(app).is_none() { + return None; // refused: the box stays open, with the reason in the status bar + } + } let st = app.session.active()?; let layer = st.doc.layer(st.active_layer?)?.clone(); let light = st.doc.global_light.angle; From 77d3478df150f1ea156ed48cbaea09407a769e71 Mon Sep 17 00:00:00 2001 From: Alon Date: Tue, 13 Oct 2026 19:03:05 +0300 Subject: [PATCH 021/107] fix(gradient): options-bar Opacity updates the live gradient layer (#5012) (#5045) --- crates/ui-egui/src/gradient_ui.rs | 40 +++++++++++++++++++++++++++++++ crates/ui-egui/src/panels.rs | 12 +++++++++- 2 files changed, 51 insertions(+), 1 deletion(-) 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/panels.rs b/crates/ui-egui/src/panels.rs index 601f049eea..11d5ecbed9 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1264,7 +1264,17 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // The wheel over it steps the mode, as over the Layers panel's (#2061). widgets::dropdown_wheel_hovered(ui, "gradient-blend-mode", &mut app.ui.tool_options.gradient_blend_mode, &opts, 96.0); opt_label(ui, tl!("Opacity")); - widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); + let r = widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); + // Live while scrubbed, one undo step per scrub (#5012). + let drag_key = r.id.with("gradient-opacity-drag"); + if r.drag_started() { + let n = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(drag_key, n)); + } + if r.changed() { + let drag = if r.dragged() { ui.data(|d| d.get_temp::(drag_key)) } else { None }; + crate::gradient_ui::opacity_changed(app, drag); + } widgets::checkbox(ui, &mut app.ui.tool_options.gradient_reverse, tl!("Reverse")); widgets::checkbox(ui, &mut app.ui.tool_options.gradient_dither, tl!("Dither")); // Live mode: the options also change a selected gradient fill layer. From 35710a94ad537d10a6828bdca6777a2085d1a692 Mon Sep 17 00:00:00 2001 From: Nigel Ihza Firdausy <106657905+Ni-zav@users.noreply.github.com> Date: Tue, 13 Oct 2026 23:03:11 +0700 Subject: [PATCH 022/107] Fix: native gesture fallback dedupe (#5080) * fix(input): avoid double-applying native pinch during legacy fallback * test(input): cover native trackpad rotation and preference gating --- crates/ui-egui/src/rotate_view.rs | 19 +++++++++++++++++ crates/ui-egui/src/wheel_nav.rs | 34 +++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/crates/ui-egui/src/rotate_view.rs b/crates/ui-egui/src/rotate_view.rs index 01841b48f7..fa22ac9862 100644 --- a/crates/ui-egui/src/rotate_view.rs +++ b/crates/ui-egui/src/rotate_view.rs @@ -317,6 +317,25 @@ mod tests { assert!(huge.is_finite() && huge.abs() <= 180.0); } + #[test] + fn native_rotate_event_reaches_canvas_when_trackpad_rotation_is_enabled() { + let ctx = egui::Context::default(); + let mut enabled = None; + let mut disabled = None; + let raw = egui::RawInput { + events: vec![Event::Rotate(std::f32::consts::FRAC_PI_6)], + ..Default::default() + }; + let mut output = ctx.run_ui(raw, |ui| { + enabled = trackpad_delta(ui.ctx(), true); + disabled = trackpad_delta(ui.ctx(), false); + }); + output.textures_delta.clear(); + + assert!(enabled.is_some_and(|degrees| (degrees - 30.0).abs() < 1e-3), "{enabled:?}"); + assert_eq!(disabled, None); + } + #[test] fn trackpad_pref_gates_rotation() { assert_eq!(apply_trackpad(10.0, false, 0.5), None); diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rs index 42055a701f..4523fbc647 100644 --- a/crates/ui-egui/src/wheel_nav.rs +++ b/crates/ui-egui/src/wheel_nav.rs @@ -126,6 +126,14 @@ fn pinch_id() -> Id { /// [`legacy_pinch_to_zoom`] for one frame's raw input (`raw_input_hook`, Windows and Linux). pub fn fold_legacy_pinch(ctx: &Context, raw: &mut RawInput) { + // Native gesture events already carry their own magnification. Some backends + // also emit a Ctrl-wheel event in the same frame: folding that wheel event + // would apply the same pinch twice. End any legacy continuation as well, + // so a later real Ctrl+wheel notch isn't treated as part of that pinch. + if raw.events.iter().any(|event| matches!(event, Event::Zoom(_))) { + ctx.data_mut(|d| d.remove::(pinch_id())); + return; + } let (notch, speed) = ctx.options(|o| (o.input_options.line_scroll_speed, o.input_options.scroll_zoom_speed)); let now = raw.time.unwrap_or_else(|| ctx.input(|i| i.time)); let last = ctx.data(|d| d.get_temp::(pinch_id())); @@ -359,6 +367,32 @@ mod tests { assert!(matches!(wheel_only[0], Event::MouseWheel { .. }), "whole mouse notch is not a pinch"); } + #[test] + fn native_pinch_is_not_zoomed_twice_when_ctrl_wheel_arrives_in_the_same_frame() { + let (_, zoom) = gesture(vec![vec![Event::Zoom(1.2), wheel(Vec2::new(0.0, 0.25), CTRL)]], false, true); + assert!((zoom - 1.2).abs() < 1e-4, "native zoom must win over fallback: {zoom}"); + } + + #[test] + fn native_pinch_resets_legacy_gesture_continuation() { + let ctx = Context::default(); + let mut legacy = RawInput { time: Some(1.0), events: vec![wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() }; + fold_legacy_pinch(&ctx, &mut legacy); + assert!(matches!(legacy.events[0], Event::Zoom(_))); + + // Native magnification takes over before the synthetic gesture times out. + let mut native = + RawInput { time: Some(1.1), events: vec![Event::Zoom(1.1), wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() }; + fold_legacy_pinch(&ctx, &mut native); + assert!(matches!(native.events[0], Event::Zoom(f) if (f - 1.1).abs() < 1e-5)); + assert!(matches!(native.events[1], Event::MouseWheel { .. })); + + // A notched mouse scroll must no longer inherit the previous pinch. + let mut notch = RawInput { time: Some(1.12), events: vec![wheel(Vec2::new(0.0, 1.0), CTRL)], ..Default::default() }; + fold_legacy_pinch(&ctx, &mut notch); + assert!(matches!(notch.events[0], Event::MouseWheel { .. })); + } + #[test] fn a_whole_notch_inside_a_pinch_stays_a_pinch() { let mut ev = [wheel(Vec2::new(0.0, 0.5), CTRL)]; From f20605219e8e0d920155dc45b513b1c41e9fdfdb Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Wed, 14 Oct 2026 00:03:16 +0800 Subject: [PATCH 023/107] Keep applied guide layouts visible after preview closes (#5084) Co-authored-by: jonathnwxh <258340642+jonathanwxh-cell@users.noreply.github.com> --- crates/ui-egui/src/guide_layout_ui.rs | 4 ++ crates/ui-egui/src/guide_layout_ui/tests.rs | 51 +++++++++++++++++++++ 2 files changed, 55 insertions(+) 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