mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge main into task/T-0001, keeping both contributors entries
main gained a contributors/people.toml entry ([people.yeniufuklar-com]) while this PR added one ([people.LorenzoFasolino]); both are kept. The i18n change merged cleanly.
This commit is contained in:
commit
c3f0e407fc
79 files changed
+2043
-164
No files matched your search
Generated
+1
@@ -4397,6 +4397,7 @@ dependencies = [
|
||||
"blake3",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"libc",
|
||||
"photocraft-codecs",
|
||||
"photocraft-color",
|
||||
"photocraft-doc",
|
||||
|
||||
@@ -155,6 +155,10 @@ sync_github_name = true
|
||||
display_name = "VanTan"
|
||||
sync_github_name = false
|
||||
|
||||
[people.yeniufuklar-com]
|
||||
real_name = "Ufuk Efe"
|
||||
sync_github_name = true
|
||||
|
||||
[people.LorenzoFasolino]
|
||||
real_name = "Lorenzo Fasolino"
|
||||
display_name = "Lorenzo Fasolino"
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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::<Vec<_>>(), (0..6).map(|i| bk.in_source(i)).collect::<Vec<_>>());
|
||||
}
|
||||
@@ -17,6 +17,15 @@ fn err(e: impl std::fmt::Display) -> CodecError {
|
||||
CodecError::malformed(F, e)
|
||||
}
|
||||
|
||||
/// Pixels per inch for `pHYs` pixels per metre. A whole number of ppi is stored rounded to whole
|
||||
/// pixels per metre (300 ppi = 11811), so reading it back gives 299.9994: the whole number that
|
||||
/// rounds to the stored value is the resolution that was meant, as Photoshop reads it.
|
||||
pub(crate) fn dpi_of_ppm(ppm: u32) -> f32 {
|
||||
let dpi = f64::from(ppm) * f64::from(METERS_PER_INCH);
|
||||
let whole = dpi.round();
|
||||
if (whole / f64::from(METERS_PER_INCH)).round() == f64::from(ppm) { whole as f32 } else { dpi as f32 }
|
||||
}
|
||||
|
||||
pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {
|
||||
let mut input = Cursor::new(bytes);
|
||||
let mut decoder = png::Decoder::new_with_limits(&mut input, png::Limits { bytes: limits.alloc_usize() });
|
||||
@@ -74,7 +83,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
|
||||
&& d.xppu > 0
|
||||
&& d.yppu > 0
|
||||
{
|
||||
meta.dpi = Some((d.xppu as f32 * METERS_PER_INCH, d.yppu as f32 * METERS_PER_INCH));
|
||||
meta.dpi = Some((dpi_of_ppm(d.xppu), dpi_of_ppm(d.yppu)));
|
||||
}
|
||||
drop(reader);
|
||||
let end = usize::try_from(input.position()).map_err(|_| err("invalid PNG reader position"))?;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<u8> = (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();
|
||||
|
||||
@@ -425,16 +425,38 @@ fn png_phys_outranks_its_exif() {
|
||||
img.meta.exif = Some(camera_exif(&LE));
|
||||
let png = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
near(decode(&png).unwrap().meta.dpi, 300.0);
|
||||
near(decode(&with_phys(&png, 5906)).unwrap().meta.dpi, 150.0);
|
||||
}
|
||||
|
||||
/// `png` with a `pHYs` chunk of `ppm` pixels per metre after IHDR.
|
||||
fn with_phys(png: &[u8], ppm: u32) -> Vec<u8> {
|
||||
let mut body = b"pHYs".to_vec();
|
||||
body.extend_from_slice(&5906u32.to_be_bytes());
|
||||
body.extend_from_slice(&5906u32.to_be_bytes());
|
||||
body.extend_from_slice(&ppm.to_be_bytes());
|
||||
body.extend_from_slice(&ppm.to_be_bytes());
|
||||
body.push(1);
|
||||
let mut chunk = 9u32.to_be_bytes().to_vec();
|
||||
chunk.extend_from_slice(&body);
|
||||
chunk.extend_from_slice(&crc32(&body).to_be_bytes());
|
||||
let ihdr_end = 8 + 8 + 13 + 4;
|
||||
let with_phys = [&png[..ihdr_end], &chunk, &png[ihdr_end..]].concat();
|
||||
near(decode(&with_phys).unwrap().meta.dpi, 150.0114);
|
||||
[&png[..ihdr_end], &chunk, &png[ihdr_end..]].concat()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_phys_of_a_whole_ppi_reads_back_whole() {
|
||||
// pHYs holds whole pixels per metre: 300 ppi is stored as 11811 (299.9994 ppi), 72 as 2835
|
||||
// (72.009). The whole number that rounds to the stored value is read, as Photoshop does; a
|
||||
// value no whole ppi rounds to stays as it is.
|
||||
let img = Image::from_raw(4, 4, ChannelLayout::Rgb, SampleType::U8, vec![90; 48]).unwrap();
|
||||
let png = encode(&img, Format::Png, &EncodeOptions { embed_metadata: false, ..Default::default() }).unwrap();
|
||||
for (ppm, want) in [(11811, 300.0), (2835, 72.0), (3937, 100.0), (11812, 300.0248)] {
|
||||
let (x, y) = decode(&with_phys(&png, ppm)).unwrap().meta.dpi.unwrap();
|
||||
assert!((x - want).abs() < 1e-4 && (y - want).abs() < 1e-4, "{ppm} px/m: {x} × {y}, wanted {want}");
|
||||
}
|
||||
// And a 300 ppi PNG written by the encoder opens at exactly 300.
|
||||
let mut img = img;
|
||||
img.meta.dpi = Some((300.0, 300.0));
|
||||
let png = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert_eq!(decode(&png).unwrap().meta.dpi, Some((300.0, 300.0)));
|
||||
}
|
||||
|
||||
/// `camera_exif` plus IFD1, the embedded thumbnail a camera (or the last editor) wrote:
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -605,8 +605,9 @@ const BALANCE_LEVELS: f32 = 0.39;
|
||||
/// - Preserve Luminosity off: a slider only moves its own channel. Midtones is gamma 2^−a.
|
||||
/// Shadows is gamma 2^(−a/2) after a black point at 0.39·|a| when lowered; highlights is
|
||||
/// gamma 2^(−a/2) after a white point at 1 − 0.39·a when raised.
|
||||
/// - Preserve Luminosity on: midtones is gamma 2^(−a/2) on the slider's channel and 2^(a/2) on
|
||||
/// the other two. Shadows and highlights go by the differences between a tone's three sliders:
|
||||
/// - Preserve Luminosity on: midtones uses gamma 2^((max(a) + min(a))/2 − a_ch),
|
||||
/// preserving the one-slider behaviour without summing offsets when multiple sliders move.
|
||||
/// Shadows and highlights go by the differences between a tone's three sliders:
|
||||
/// each channel gets a plain black point at 0.39·(max − its own) for shadows and a plain white
|
||||
/// point at 1 − 0.39·(its own − min) for highlights (so one raised shadows slider darkens the
|
||||
/// other two channels, and two raised together darken only the third).
|
||||
@@ -620,28 +621,27 @@ pub fn color_balance_channel(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch
|
||||
let mut v = v.clamp(0.0, 1.0);
|
||||
for (tone, sliders) in [(2, highlights), (0, shadows), (1, midtones)] {
|
||||
let a: [f32; 3] = sliders.map(|s| (s / 100.0).clamp(-1.0, 1.0));
|
||||
if preserve_luminosity && tone != 1 {
|
||||
if preserve_luminosity {
|
||||
let own = a.get(ch).copied().unwrap_or(0.0);
|
||||
let (lo, hi) = a.iter().fold((f32::MAX, f32::MIN), |m, x| (m.0.min(*x), m.1.max(*x)));
|
||||
v = if tone == 0 { black(v, BALANCE_LEVELS * (hi - own)) } else { white(v, 1.0 - BALANCE_LEVELS * (own - lo)) };
|
||||
v = match tone {
|
||||
0 => black(v, BALANCE_LEVELS * (hi - own)),
|
||||
1 => v.powf(2f32.powf((hi + lo) / 2.0 - own)),
|
||||
_ => white(v, 1.0 - BALANCE_LEVELS * (own - lo)),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
for (src, slider) in sliders.iter().enumerate() {
|
||||
let a = (slider / 100.0).clamp(-1.0, 1.0);
|
||||
let own = src == ch;
|
||||
if a == 0.0 || (!preserve_luminosity && !own) {
|
||||
if a == 0.0 || src != ch {
|
||||
continue;
|
||||
}
|
||||
v = match (tone, preserve_luminosity) {
|
||||
(1, false) => v.powf(2f32.powf(-a)),
|
||||
(1, true) => v.powf(2f32.powf(if own { -a } else { a } / 2.0)),
|
||||
(0, false) if a < 0.0 => black(v, BALANCE_LEVELS * -a).powf(2f32.powf(-a / 2.0)),
|
||||
(0, false) => v.powf(2f32.powf(-a / 2.0)),
|
||||
|
||||
(2, false) if a > 0.0 => white(v, 1.0 - BALANCE_LEVELS * a).powf(2f32.powf(-a / 2.0)),
|
||||
(2, false) => v.powf(2f32.powf(-a / 2.0)),
|
||||
|
||||
_ => v,
|
||||
v = match tone {
|
||||
1 => v.powf(2f32.powf(-a)),
|
||||
0 if a < 0.0 => black(v, BALANCE_LEVELS * -a).powf(2f32.powf(-a / 2.0)),
|
||||
0 => v.powf(2f32.powf(-a / 2.0)),
|
||||
2 if a > 0.0 => white(v, 1.0 - BALANCE_LEVELS * a).powf(2f32.powf(-a / 2.0)),
|
||||
_ => v.powf(2f32.powf(-a / 2.0)),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1254,6 +1254,26 @@ mod tone_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_balance_midtones_with_multiple_sliders_preserve_luminosity() {
|
||||
// A shared offset depends on the two extremes, not the sum of moved sliders.
|
||||
// The old per-slider product leaves red/blue unchanged for [30, 0, 30].
|
||||
let tones = [[0.0; 3], [30.0, 0.0, 30.0], [0.0; 3]];
|
||||
for input in [0.25_f32, 0.5, 0.75] {
|
||||
for (ch, offset) in [-0.15_f32, 0.15, -0.15].into_iter().enumerate() {
|
||||
let expected = input.powf(2f32.powf(offset));
|
||||
let actual = color_balance_channel(tones, true, ch, input);
|
||||
assert!((actual - expected).abs() < 1e-6, "channel {ch}, input {input}: {actual} vs {expected}");
|
||||
}
|
||||
// Preserve Luminosity off must still affect only the moved channels.
|
||||
assert_eq!(color_balance_channel(tones, false, 1, input), input);
|
||||
// One moved slider retains its previous half-strength compensation.
|
||||
let single = [[0.0; 3], [30.0, 0.0, 0.0], [0.0; 3]];
|
||||
assert!((color_balance_channel(single, true, 0, input) - input.powf(2f32.powf(-0.15))).abs() < 1e-6);
|
||||
assert!((color_balance_channel(single, true, 1, input) - input.powf(2f32.powf(0.15))).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_and_curves_apply_each_channel_before_the_master() {
|
||||
// These two affine tone adjustments describe the same mapping:
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -24,10 +24,15 @@ crc32fast = "1.5"
|
||||
blake3 = { version = "1.8", default-features = false, features = ["pure"] }
|
||||
ruzstd = "0.9"
|
||||
|
||||
# A plain fsync where a file system refuses the full flush (`sync_file`, atomic.rs). Already in
|
||||
# Cargo.lock on Apple targets (cap-std), so this adds no new crate.
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||
# Unix directory cleanup uses no-follow descriptor-relative operations; the same
|
||||
# dependency provides the plain-fsync fallback on Apple file systems.
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
|
||||
|
||||
# rustix does not expose Apple's directory-search open mode. Only the named
|
||||
# constant is used; all descriptor operations remain in safe rustix APIs.
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
+111
-6
@@ -570,10 +570,82 @@ fn write_bundle_file(root: &Path, path: &Path, data: &[u8]) -> Result<()> {
|
||||
result
|
||||
}
|
||||
|
||||
fn remove_bundle_file(root: &Path, path: &Path) -> Result<()> {
|
||||
/// Keep the existing leaf/path validation and pin the actual unlink to opened
|
||||
/// directory handles on Unix. This closes the check-then-remove path-swap gap.
|
||||
fn remove_bundle_file(root: &Path, path: &Path, gc: &BundleGc) -> Result<()> {
|
||||
validate_bundle_file(root, path)?;
|
||||
std::fs::remove_file(path)?;
|
||||
Ok(())
|
||||
let relative = path.strip_prefix(root).map_err(|_| unsafe_bundle_entry(path))?;
|
||||
gc.remove(relative)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
struct BundleGc {
|
||||
root: rustix::fd::OwnedFd,
|
||||
tiles: rustix::fd::OwnedFd,
|
||||
blobs: rustix::fd::OwnedFd,
|
||||
composite: rustix::fd::OwnedFd,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn gc_directory_flags() -> rustix::fs::OFlags {
|
||||
use rustix::fs::OFlags;
|
||||
|
||||
// GC needs directory traversal, not permission to read a directory listing.
|
||||
// Both modes retain a descriptor for the directory opened here, so a later
|
||||
// pathname replacement cannot redirect descriptor-relative cleanup.
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
let access = OFlags::PATH;
|
||||
#[cfg(target_vendor = "apple")]
|
||||
let access = OFlags::from_bits_retain(libc::O_SEARCH.cast_unsigned());
|
||||
#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
|
||||
let access = OFlags::RDONLY;
|
||||
access | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl BundleGc {
|
||||
fn new(root: &Path) -> Result<Self> {
|
||||
use rustix::fs::{Mode, open, openat};
|
||||
|
||||
let flags = gc_directory_flags();
|
||||
let root = open(root, flags, Mode::empty()).map_err(std::io::Error::from)?;
|
||||
let tiles = openat(&root, "tiles", flags, Mode::empty()).map_err(std::io::Error::from)?;
|
||||
let blobs = openat(&root, "blobs", flags, Mode::empty()).map_err(std::io::Error::from)?;
|
||||
let composite = openat(&root, "composite", flags, Mode::empty()).map_err(std::io::Error::from)?;
|
||||
Ok(Self { root, tiles, blobs, composite })
|
||||
}
|
||||
|
||||
fn remove(&self, relative: &Path) -> Result<()> {
|
||||
let relative = relative.to_str().ok_or_else(|| unsafe_bundle_entry(relative))?;
|
||||
let (handle, name) = match relative {
|
||||
THUMB => (&self.root, THUMB),
|
||||
COMPOSITE => (&self.composite, "preview.png"),
|
||||
_ => match relative.split_once('/') {
|
||||
Some(("tiles", name)) if name.strip_suffix(".zst").is_some_and(is_valid_hash) => (&self.tiles, name),
|
||||
Some(("blobs", name)) if name.strip_suffix(".zst").is_some_and(is_valid_hash) => (&self.blobs, name),
|
||||
_ => return Err(FormatError::Unsupported(format!("invalid bundle cleanup target: {relative}"))),
|
||||
},
|
||||
};
|
||||
rustix::fs::unlinkat(handle, name, rustix::fs::AtFlags::empty()).map_err(std::io::Error::from)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
struct BundleGc {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
impl BundleGc {
|
||||
fn new(root: &Path) -> Result<Self> {
|
||||
Ok(Self { root: root.to_path_buf() })
|
||||
}
|
||||
|
||||
fn remove(&self, relative: &Path) -> Result<()> {
|
||||
std::fs::remove_file(self.root.join(relative))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn existing_object_is_valid(path: &Path, object: &Object, what: &str) -> Result<(bool, Option<FileSignature>)> {
|
||||
@@ -802,11 +874,14 @@ impl PcraftWriter {
|
||||
for (name, data) in &p.previews {
|
||||
write_bundle_file(dir, &dir.join(name), data)?;
|
||||
}
|
||||
// Pin all GC directories before removing stale previews or objects.
|
||||
// Unix cleanup then stays within these directories even if a pathname is swapped.
|
||||
let gc = BundleGc::new(dir)?;
|
||||
for stale in [THUMB, COMPOSITE] {
|
||||
if !p.previews.iter().any(|(n, _)| *n == stale) {
|
||||
let path = dir.join(stale);
|
||||
validate_bundle_file(dir, &path)?;
|
||||
match remove_bundle_file(dir, &path) {
|
||||
match remove_bundle_file(dir, &path, &gc) {
|
||||
Err(FormatError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
other => other?,
|
||||
}
|
||||
@@ -818,7 +893,7 @@ impl PcraftWriter {
|
||||
// complete save into a reported failure); a leftover is retried on the next save.
|
||||
for path in existing {
|
||||
if !p.objects.contains_key(&path) {
|
||||
if remove_bundle_file(dir, &dir.join(&path)).is_ok() {
|
||||
if remove_bundle_file(dir, &dir.join(&path), &gc).is_ok() {
|
||||
stats.objects_removed += 1;
|
||||
}
|
||||
if let Some(cache) = &mut self.verified_directory {
|
||||
@@ -866,6 +941,36 @@ impl PcraftWriter {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[test]
|
||||
fn gc_pinned_directory_handles_resist_subdirectory_swap() {
|
||||
use std::os::unix::fs::symlink;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = std::env::temp_dir().join(format!("pcraft-gc-swap-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let bundle = root.join("project.pcraft");
|
||||
let outside = root.join("outside");
|
||||
for sub in ["tiles", "blobs", "composite"] {
|
||||
std::fs::create_dir_all(bundle.join(sub)).unwrap();
|
||||
}
|
||||
std::fs::create_dir(&outside).unwrap();
|
||||
let filename = format!("{}.zst", "c".repeat(64));
|
||||
std::fs::write(bundle.join("tiles").join(&filename), b"stale bundle file").unwrap();
|
||||
std::fs::write(outside.join(&filename), b"outside file must survive").unwrap();
|
||||
|
||||
let gc = BundleGc::new(&bundle).unwrap();
|
||||
std::fs::rename(bundle.join("tiles"), bundle.join("old-tiles")).unwrap();
|
||||
symlink(&outside, bundle.join("tiles")).unwrap();
|
||||
|
||||
// Exercise the descriptor-relative unlink directly: the public save path
|
||||
// also validates the leaf, but that check itself cannot prevent a later swap.
|
||||
gc.remove(Path::new(&format!("tiles/{filename}"))).unwrap();
|
||||
assert!(!bundle.join("old-tiles").join(&filename).exists());
|
||||
assert_eq!(std::fs::read(outside.join(&filename)).unwrap(), b"outside file must survive");
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
fn list_objects(dir: &Path) -> Result<HashSet<String>> {
|
||||
let mut out = HashSet::new();
|
||||
for sub in ["tiles", "blobs"] {
|
||||
@@ -878,7 +983,7 @@ fn list_objects(dir: &Path) -> Result<HashSet<String>> {
|
||||
for e in rd {
|
||||
let e = e?;
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
if name.ends_with(".zst") {
|
||||
if name.strip_suffix(".zst").is_some_and(is_valid_hash) {
|
||||
let path = e.path();
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) if metadata.file_type().is_symlink() => return Err(unsafe_bundle_entry(&path)),
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Directory cleanup only owns content-addressed objects; unrelated files survive.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::temp_dir;
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_doc::Document;
|
||||
use photocraft_format::{PcraftWriter, SaveOptions};
|
||||
use photocraft_geom::Size;
|
||||
|
||||
fn empty_doc() -> Document {
|
||||
Document::new("clean", Size::new(1, 1), ColorMode::Rgb, SampleType::U8)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_cleanup_preserves_unrelated_zst_files() {
|
||||
let root = temp_dir("unrelated-object");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
|
||||
let unrelated = bundle.join("tiles/personal-notes.zst");
|
||||
let orphan = bundle.join("blobs").join(format!("{}.zst", "b".repeat(64)));
|
||||
std::fs::write(&unrelated, b"unrelated file").unwrap();
|
||||
std::fs::write(&orphan, b"unused content-addressed object").unwrap();
|
||||
|
||||
let stats = writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
assert_eq!(std::fs::read(&unrelated).unwrap(), b"unrelated file");
|
||||
assert!(!orphan.exists(), "a valid but unreferenced object is removed");
|
||||
assert_eq!(stats.objects_removed, 1);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
|
||||
mod permissions {
|
||||
use super::*;
|
||||
use photocraft_format::load_path;
|
||||
use photocraft_raster::Rgba8Image;
|
||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
struct RestoreMode {
|
||||
path: PathBuf,
|
||||
permissions: std::fs::Permissions,
|
||||
}
|
||||
|
||||
impl RestoreMode {
|
||||
fn set(path: &Path, mode: u32) -> Self {
|
||||
let permissions = std::fs::metadata(path).unwrap().permissions();
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
|
||||
Self { path: path.to_path_buf(), permissions }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RestoreMode {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::set_permissions(&self.path, self.permissions.clone());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_save_without_previews_does_not_require_composite_read_permission() {
|
||||
let root = temp_dir("composite-search-only");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
let restricted = RestoreMode::set(&bundle.join("composite"), 0o300);
|
||||
let mut changed = empty_doc();
|
||||
changed.name = "saved without previews".into();
|
||||
let result = writer.save_dir(&changed, &bundle, &SaveOptions::default());
|
||||
drop(restricted);
|
||||
result.expect("saving without previews does not read composite");
|
||||
assert_eq!(load_path(&bundle).unwrap(), changed);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_save_cleans_stale_previews_through_search_only_root_and_composite() {
|
||||
let root = temp_dir("bundle-search-only");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let link = root.join("linked.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
symlink(&bundle, &link).unwrap();
|
||||
std::fs::write(bundle.join("thumb.png"), b"stale thumbnail").unwrap();
|
||||
std::fs::write(bundle.join("composite/preview.png"), b"stale composite").unwrap();
|
||||
let orphan = bundle.join("blobs").join(format!("{}.zst", "a".repeat(64)));
|
||||
std::fs::write(&orphan, b"unreferenced object").unwrap();
|
||||
let composite_mode = RestoreMode::set(&bundle.join("composite"), 0o300);
|
||||
let root_mode = RestoreMode::set(&bundle, 0o300);
|
||||
let mut changed = empty_doc();
|
||||
changed.name = "saved through linked root".into();
|
||||
let result = writer.save_dir(&changed, &link, &SaveOptions::default());
|
||||
drop(root_mode);
|
||||
drop(composite_mode);
|
||||
let stats = result.expect("cleanup needs directory traversal and write permission, not read");
|
||||
assert_eq!(stats.objects_removed, 1);
|
||||
assert!(!orphan.exists());
|
||||
assert!(!bundle.join("thumb.png").exists());
|
||||
assert!(!bundle.join("composite/preview.png").exists());
|
||||
assert_eq!(load_path(&bundle).unwrap(), changed);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_save_writes_current_preview_without_composite_read_permission() {
|
||||
let root = temp_dir("preview-search-only");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
let restricted = RestoreMode::set(&bundle.join("composite"), 0o300);
|
||||
let mut changed = empty_doc();
|
||||
changed.name = "saved with preview".into();
|
||||
let opts = SaveOptions { composite: Some(Rgba8Image::new(2, 2)), ..Default::default() };
|
||||
let result = writer.save_dir(&changed, &bundle, &opts);
|
||||
drop(restricted);
|
||||
result.expect("writing a preview does not require listing its directory");
|
||||
assert!(std::fs::read(bundle.join("composite/preview.png")).unwrap().starts_with(b"\x89PNG\r\n\x1a\n"));
|
||||
assert_eq!(load_path(&bundle).unwrap(), changed);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denied_stale_preview_cleanup_preserves_the_previous_manifest() {
|
||||
let root = temp_dir("denied-preview-cleanup");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
let original = empty_doc();
|
||||
writer.save_dir(&original, &bundle, &SaveOptions::default()).unwrap();
|
||||
let preview = bundle.join("composite/preview.png");
|
||||
std::fs::write(&preview, b"stale composite").unwrap();
|
||||
let restricted = RestoreMode::set(&bundle.join("composite"), 0o500);
|
||||
let permission_probe = bundle.join("composite/permission-probe");
|
||||
if std::fs::write(&permission_probe, b"probe").is_ok() {
|
||||
// An elevated test process may bypass directory permissions.
|
||||
std::fs::remove_file(permission_probe).unwrap();
|
||||
drop(restricted);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
return;
|
||||
}
|
||||
let mut changed = empty_doc();
|
||||
changed.name = "must not commit".into();
|
||||
let result = writer.save_dir(&changed, &bundle, &SaveOptions::default());
|
||||
drop(restricted);
|
||||
assert!(result.is_err(), "a required pre-commit cleanup failure is reported");
|
||||
assert_eq!(std::fs::read(preview).unwrap(), b"stale composite");
|
||||
assert_eq!(load_path(&bundle).unwrap(), original);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denied_object_cleanup_remains_best_effort_after_manifest_commit() {
|
||||
let root = temp_dir("denied-object-cleanup");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
let orphan = bundle.join("tiles").join(format!("{}.zst", "d".repeat(64)));
|
||||
std::fs::write(&orphan, b"unreferenced object").unwrap();
|
||||
let restricted = RestoreMode::set(&bundle.join("tiles"), 0o500);
|
||||
let permission_probe = bundle.join("tiles/permission-probe");
|
||||
if std::fs::write(&permission_probe, b"probe").is_ok() {
|
||||
std::fs::remove_file(permission_probe).unwrap();
|
||||
drop(restricted);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
return;
|
||||
}
|
||||
let mut changed = empty_doc();
|
||||
changed.name = "committed despite housekeeping failure".into();
|
||||
let result = writer.save_dir(&changed, &bundle, &SaveOptions::default());
|
||||
drop(restricted);
|
||||
assert_eq!(result.unwrap().objects_removed, 0);
|
||||
assert!(orphan.exists());
|
||||
assert_eq!(load_path(&bundle).unwrap(), changed);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -845,6 +845,26 @@ impl Compositor {
|
||||
self.prefix.forget(doc);
|
||||
}
|
||||
|
||||
/// [`Self::forget_doc`] for every document `keep` rejects: what the compositor holds for
|
||||
/// documents that were closed, however their canvas entry went (#4529).
|
||||
pub fn retain_docs(&mut self, keep: impl Fn(DocId) -> bool) {
|
||||
let mut gone: Vec<DocId> =
|
||||
self.residents.values().map(|r| r.doc).chain(self.fx.values().map(|e| e.doc)).chain(self.prefix.doc()).filter(|d| !keep(*d)).collect();
|
||||
gone.sort_by_key(|d| d.0);
|
||||
gone.dedup();
|
||||
for d in gone {
|
||||
self.forget_doc(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Documents the compositor holds pages, effect maps or a lower-stack composite for.
|
||||
pub fn held_docs(&self) -> Vec<DocId> {
|
||||
let mut docs: Vec<DocId> = self.residents.values().map(|r| r.doc).chain(self.fx.values().map(|e| e.doc)).chain(self.prefix.doc()).collect();
|
||||
docs.sort_by_key(|d| d.0);
|
||||
docs.dedup();
|
||||
docs
|
||||
}
|
||||
|
||||
/// GPU memory held by cached effect maps (bytes).
|
||||
pub fn fx_cache_bytes(&self) -> usize {
|
||||
self.fx.values().map(FxEntry::bytes).sum()
|
||||
|
||||
@@ -85,6 +85,11 @@ impl Prefix {
|
||||
}
|
||||
}
|
||||
|
||||
/// The document the cached composite belongs to, if any.
|
||||
pub(crate) fn doc(&self) -> Option<photocraft_doc::DocId> {
|
||||
self.context.as_ref().map(|d| d.id)
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(&mut self, doc: &Document, plan: &Plan<'_>) -> Option<Checkpoint> {
|
||||
if self.budget == 0 {
|
||||
return None;
|
||||
|
||||
@@ -187,6 +187,27 @@ fn check(g: &mut Gpu, doc: &Document, what: &str) {
|
||||
diff_rect(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}"));
|
||||
}
|
||||
|
||||
/// Closing a document frees what the compositor holds for it, however its canvas entry went
|
||||
/// (#4529): `retain_docs` drops the resident pages, effect maps and lower-stack composite of
|
||||
/// documents that aren't open, and keeps the open ones.
|
||||
#[test]
|
||||
fn retain_docs_frees_closed_documents() {
|
||||
let Some(mut g) = gpu() else { return };
|
||||
let a = base_doc(64, 48);
|
||||
let mut b = base_doc(32, 32);
|
||||
b.id = photocraft_doc::DocId(a.id.0 + 1);
|
||||
for d in [&a, &b] {
|
||||
render_to_vec(&mut g.comp, &g.device, &g.queue, d, d.bounds()).expect("render");
|
||||
}
|
||||
assert_eq!(g.comp.held_docs(), vec![a.id, b.id]);
|
||||
g.comp.retain_docs(|d| d == b.id);
|
||||
assert_eq!(g.comp.held_docs(), vec![b.id], "only the open document is left");
|
||||
g.comp.retain_docs(|_| false);
|
||||
assert!(g.comp.held_docs().is_empty());
|
||||
assert_eq!(g.comp.composite_cache_bytes(), 0);
|
||||
check(&mut g, &a, "renders again after being forgotten");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_frame_renders() {
|
||||
// Regression: the first submission after device creation is dropped on some drivers
|
||||
|
||||
@@ -429,7 +429,12 @@ impl Mapper<'_> {
|
||||
}
|
||||
dual.mode = mask_mode(enum_value(db, "BlnM")).unwrap_or(MaskMode::Multiply);
|
||||
dual.flip = boolean(db, "Flip").unwrap_or(false);
|
||||
if let Some(v) = pct(db, "Spcn") {
|
||||
// The dual tip's own spacing (`Brsh › Spcn`) is what Photoshop's Dual Brush panel
|
||||
// shows. The `Spcn` beside it on the `dualBrush` object reads 100 % in Photoshop CC
|
||||
// presets whatever the panel says (#4809), so it only stands in for a tip without one.
|
||||
if obj(db, "Brsh").and_then(|t| pct(t, "Spcn")).is_none()
|
||||
&& let Some(v) = pct(db, "Spcn")
|
||||
{
|
||||
dual.spacing = v.clamp(0.01, 10.0);
|
||||
}
|
||||
dual.scatter = self.dynamic(obj(db, "scatterDynamics")).jitter;
|
||||
|
||||
@@ -399,3 +399,32 @@ fn low_depth_height_texture_brush_paints() {
|
||||
assert_eq!(covered, 36, "{mode}: the stroke painted {covered} of 36 pixels");
|
||||
}
|
||||
}
|
||||
|
||||
/// #4809: Photoshop CC presets store the dual tip's spacing in `dualBrush › Brsh › Spcn` and a
|
||||
/// `Spcn` of 100 % on the `dualBrush` object beside it; the tip's value is the panel's. A tip
|
||||
/// without one still takes the outer value.
|
||||
#[test]
|
||||
fn dual_brush_spacing_comes_from_its_tip() {
|
||||
let dual = |tip: Descriptor| {
|
||||
Descriptor::new("brushPreset")
|
||||
.with("Nm ", t("SPACING 10%"))
|
||||
.with("Brsh", Value::Descriptor(Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 30.0))))
|
||||
.with(
|
||||
"dualBrush",
|
||||
Value::Descriptor(
|
||||
Descriptor::new("dualBrush")
|
||||
.with("useDualBrush", Value::Boolean(true))
|
||||
.with("Brsh", Value::Descriptor(tip))
|
||||
.with("BlnM", en("BlnM", "Ovrl"))
|
||||
.with("Spcn", prc(100.0)),
|
||||
),
|
||||
)
|
||||
};
|
||||
let spacing = |preset: Descriptor| {
|
||||
let bytes = write_v6(2, &[], &[], &[preset], false).unwrap();
|
||||
read_abr(&bytes, "Test").unwrap().presets[0].brush.dual_brush.spacing
|
||||
};
|
||||
let tip = Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 40.0));
|
||||
assert!((spacing(dual(tip.clone().with("Spcn", prc(10.0)))) - 0.10).abs() < 1e-6, "the tip's 10 %, not the outer 100 %");
|
||||
assert!((spacing(dual(tip)) - 1.0).abs() < 1e-6, "no tip spacing: the outer value");
|
||||
}
|
||||
+30
-14
@@ -509,11 +509,12 @@ fn parse_black_white(d: &[u8]) -> Option<Adjustment> {
|
||||
/// (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<Adjustment> {
|
||||
@@ -527,11 +528,14 @@ fn parse_photo_filter(d: &[u8]) -> Option<Adjustment> {
|
||||
(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.
|
||||
|
||||
@@ -312,8 +312,10 @@ fn document_to_image_for(doc: &Document, warnings: &mut Vec<String>, 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<String>, 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).
|
||||
|
||||
@@ -508,7 +508,10 @@ pub fn merged_composite(file: &PsdFile) -> Result<Vec<[f32; 4]>, IoError> {
|
||||
}
|
||||
let l = doc.layers.first().ok_or_else(|| IoError::Unsupported("no merged image".into()))?;
|
||||
let s = l.surface().ok_or_else(|| IoError::Unsupported("no merged image".into()))?;
|
||||
Ok(photocraft_compose::surface_to_buffer(s, doc.bounds()).px)
|
||||
// CMYK reads through the file's own profile, as the compositor reads its layers, so a tagged
|
||||
// file's merged image and its composite are compared in the same colours.
|
||||
let cmyk = photocraft_compose::cmyk_space(&doc);
|
||||
Ok(photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || photocraft_compose::surface_to_buffer(s, doc.bounds()).px))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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<u32>,
|
||||
/// PSD ids assigned to document layers (kept from `psd_id` when unique).
|
||||
layer_ids: std::collections::HashMap<photocraft_doc::LayerId, u32>,
|
||||
/// 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<u32> = file.layers().iter().filter_map(|layer| layer.layer_id()).collect();
|
||||
let unique: std::collections::HashSet<u32> = 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<u32> = 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.
|
||||
|
||||
@@ -233,3 +233,37 @@ fn layered_tiff_keeps_its_existing_cmyk_psd_composite_path() {
|
||||
assert_eq!(tag(&result.bytes, 338), Some(2));
|
||||
assert!(image.to_normalized().as_chunks::<5>().0.iter().all(|px| (px[4] - 0.5).abs() < 0.0001));
|
||||
}
|
||||
|
||||
/// A tagged CMYK file's merged image reads through its own profile, as the compositor reads the
|
||||
/// layers, so the two are compared in the same colours (the oracle tests rely on it: psd-tools'
|
||||
/// tagged CMYK files were 95–100% off before).
|
||||
#[test]
|
||||
fn merged_composite_of_a_tagged_cmyk_file_reads_through_its_profile() {
|
||||
use photocraft_cms::synth::{CmykParams, cmyk_profile};
|
||||
use photocraft_color::convert::{CmykSpace, cmyk_to_rgb, with_cmyk_space};
|
||||
let mut doc = Document::new("tagged", Size::new(6, 4), ColorMode::Cmyk, SampleType::U8);
|
||||
let profile =
|
||||
cmyk_profile(&CmykParams { description: "Merged Test CMYK".into(), tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, grid_b2a: 9, ..Default::default() });
|
||||
doc.icc_profile = Some(profile.to_bytes());
|
||||
let mut surface = Surface::new(photocraft_color::PixelFormat::new(ColorMode::Cmyk, SampleType::U8, false));
|
||||
for x in 0..6 {
|
||||
for y in 0..4 {
|
||||
surface.write_pixel(x, y, &[x as f32 / 5.0, y as f32 / 3.0, 0.4, (x * y) as f32 / 15.0]);
|
||||
}
|
||||
}
|
||||
doc.layers.push(Layer::new("Background", LayerContent::Raster(surface)));
|
||||
let psd = export(&doc, "psd", &ExportOptions::default()).unwrap();
|
||||
let file = photocraft_psd::PsdFile::from_bytes(&psd.bytes).unwrap();
|
||||
let merged = photocraft_io::merged_composite(&file).unwrap();
|
||||
// The merged image's own inks (planar, 255 = no ink), shown through the file's profile.
|
||||
let raw = file.decode_merged().unwrap();
|
||||
let plane = 6 * 4;
|
||||
let space = CmykSpace::for_profile(doc.icc_profile.as_ref());
|
||||
assert!(space.is_some(), "a profile other than the built-in coated CMYK");
|
||||
let shown: Vec<[f32; 3]> =
|
||||
with_cmyk_space(space.as_ref(), || (0..plane).map(|i| cmyk_to_rgb(std::array::from_fn(|c| 1.0 - f32::from(raw[c * plane + i]) / 255.0))).collect());
|
||||
let builtin: Vec<[f32; 3]> = (0..plane).map(|i| cmyk_to_rgb(std::array::from_fn(|c| 1.0 - f32::from(raw[c * plane + i]) / 255.0))).collect();
|
||||
let apart = |a: &[[f32; 3]]| merged.iter().zip(a).flat_map(|(m, s)| (0..3).map(move |c| (m[c] - s[c]).abs())).fold(0.0f32, f32::max);
|
||||
assert!(apart(&shown) < 1e-4, "merged image read through its profile: {}", apart(&shown));
|
||||
assert!(apart(&builtin) > 0.01, "the built-in profile would show it differently");
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -27,7 +27,7 @@ fn png_with_unequal_axes_reports_the_dropped_vertical_resolution() {
|
||||
assert!((r.document.resolution_dpi - 300.0).abs() < 0.01, "{}", r.document.resolution_dpi);
|
||||
let notes = resolution_notes(&r);
|
||||
assert_eq!(notes.len(), 1, "{:?}", r.warnings);
|
||||
assert!(notes[0].contains("150.01") && notes[0].contains("300.00"), "{notes:?}");
|
||||
assert!(notes[0].contains("150.00") && notes[0].contains("300.00"), "{notes:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -41,9 +41,15 @@ impl ImageData {
|
||||
|
||||
/// Decodes and returns a single channel plane.
|
||||
pub fn decode_channel(&self, header: &Header, index: usize) -> Result<Vec<u8>> {
|
||||
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<Self> {
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -747,7 +747,8 @@ impl Surface {
|
||||
/// The surface moved by whole pixels: its encoded samples copied tile to tile (no float
|
||||
/// round trip, no intermediate buffer); moves by whole tiles share the tiles themselves, and
|
||||
/// a target tile read entirely from tiles of one single pixel value shares one such tile (the
|
||||
/// inside of a solid fill stays one copy-on-write tile however often it moves).
|
||||
/// inside of a solid fill stays one copy-on-write tile however often it moves). A tile it
|
||||
/// copies that ends up holding only the default pixel isn't stored.
|
||||
/// `content` must hold every pixel that isn't the default one (`content_bounds`, say): only
|
||||
/// tiles it reaches are kept.
|
||||
pub fn translated(&self, dx: i32, dy: i32, content: Rect) -> Surface {
|
||||
@@ -763,6 +764,8 @@ impl Surface {
|
||||
let targets: std::collections::BTreeSet<TileCoord> = sources().flat_map(|(c, _)| c.rect().translate(dx, dy).intersect(&moved).tiles()).collect();
|
||||
let mut uniform = UniformTiles::default();
|
||||
let zero = vec![0u8; bpp];
|
||||
// One tile row of the default pixel, to compare a finished tile with a row at a time.
|
||||
let default_row = self.default_pixel.repeat(TILE_SIZE.unsigned_abs() as usize);
|
||||
for dc in targets {
|
||||
let dr = dc.rect();
|
||||
let sr = dr.translate(dx.saturating_neg(), dy.saturating_neg());
|
||||
@@ -774,7 +777,10 @@ impl Surface {
|
||||
&& content.contains_rect(&sr)
|
||||
&& sr.tiles().all(|sc| self.tiles.contains_key(&sc));
|
||||
if covered && let Some(shared) = uniform.window(self, sr) {
|
||||
out.tiles.insert(dc, shared);
|
||||
// A tile of only the default pixel is left out, as `prune` would.
|
||||
if shared.data.get(..bpp) != Some(&*self.default_pixel) {
|
||||
out.tiles.insert(dc, shared);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A covered target is overwritten whole, so skip filling it with the default pixel.
|
||||
@@ -795,7 +801,11 @@ impl Surface {
|
||||
}
|
||||
}
|
||||
}
|
||||
out.tiles.insert(dc, Arc::new(tile));
|
||||
// A target that got only default pixels isn't stored, as `prune` would drop it. Checked
|
||||
// after the copy, a row at a time: a tile with content stops at its first such row.
|
||||
if tile.data.chunks(default_row.len()).any(|row| row != default_row) {
|
||||
out.tiles.insert(dc, Arc::new(tile));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1427,6 +1437,43 @@ mod tests {
|
||||
let _ = s.translated(i32::MIN + 1, 3, all);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translated_stores_no_tiles_of_only_the_default_pixel() {
|
||||
let only_default = |t: &Surface| {
|
||||
let dp = t.default_pixel();
|
||||
t.tiles().filter(|(c, _)| t.read_region(c.rect()).chunks_exact(dp.len()).all(|p| p == dp.as_slice())).count()
|
||||
};
|
||||
// Two blocks a few tiles apart, moved off the tile grid and back: the default-pixel edges
|
||||
// of their tiles land on tiles of their own, which aren't stored.
|
||||
for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] {
|
||||
for default in [0.0, 0.25] {
|
||||
let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]);
|
||||
s.fill_rect(Rect::new(0, 0, 300, 300), &vec![1.0; fmt.channels()]);
|
||||
s.fill_rect(Rect::new(2000, 1000, 2300, 1300), &vec![0.5; fmt.channels()]);
|
||||
let all = Rect::new(-600, -600, 3000, 2000);
|
||||
let mut t = s.clone();
|
||||
for (dx, dy) in [(100, 56), (-100, -56), (10, 7), (-3, 40), (130, -90), (-137, 43)] {
|
||||
let moved = t.translated(dx, dy, t.content_bounds());
|
||||
assert_eq!(moved.read_region(all), t.read_region(all.translate(-dx, -dy)), "{fmt:?} over {default} by ({dx}, {dy})");
|
||||
assert_eq!(only_default(&moved), 0, "{fmt:?} over {default} by ({dx}, {dy})");
|
||||
t = moved;
|
||||
}
|
||||
assert_eq!(t.read_region(all), s.read_region(all), "{fmt:?} over {default}: back where it started");
|
||||
assert_eq!(t.tile_count(), s.tile_count(), "{fmt:?} over {default}: back where it started");
|
||||
}
|
||||
}
|
||||
// Stored tiles of the default pixel inside `content`: the targets that would share one of
|
||||
// them (#4414's uniform windows) are left out too.
|
||||
let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]);
|
||||
s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.25]);
|
||||
s.write_pixel(600, 600, &[1.0]);
|
||||
let content = Rect::new(0, 0, 1024, 1024);
|
||||
let t = s.translated(10, 7, content);
|
||||
assert_eq!(only_default(&t), 0);
|
||||
assert_eq!(t.tile_count(), 1);
|
||||
assert_eq!(t.read_region(Rect::new(-20, -20, 1100, 1100)), s.read_region(Rect::new(-30, -27, 1090, 1093)));
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn region_write_read_roundtrip(x in -600i32..600, y in -600i32..600, w in 1u32..90, h in 1u32..90, seed in any::<u32>()) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -560,6 +560,51 @@ fn toggle_value(app: &PhotocraftApp, section: usize) -> bool {
|
||||
brush.pointer(path).and_then(Value::as_bool).expect("the checkbox has a boolean brush setting")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_jitter_amount_edits_keep_percentage_units_and_command_routing() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
|
||||
let mut h = harness(0, 5);
|
||||
h.state_mut()
|
||||
.session
|
||||
.execute(
|
||||
"tools.setBrush",
|
||||
json!({"brush": {"colorDynamics": {
|
||||
"enabled": true, "hueJitter": 0.37, "saturationJitter": 0.23, "brightnessJitter": 0.41, "purity": -0.16
|
||||
}}}),
|
||||
)
|
||||
.unwrap();
|
||||
let before = h.state().session.tools.brush.clone();
|
||||
h.run_steps(2);
|
||||
let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(37.0)).unwrap();
|
||||
let center = field.rect().center();
|
||||
field.click();
|
||||
h.key_press(egui::Key::ArrowUp);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.tools.brush.color_dynamics.hue_jitter, 0.38);
|
||||
h.key_press(egui::Key::Enter);
|
||||
// Click near the high end of the track, then beyond its right edge while dragging.
|
||||
let from = egui::pos2(center.x, center.y + 24.0);
|
||||
h.event(egui::Event::PointerMoved(from));
|
||||
h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
let to = from + vec2(200.0, 0.0);
|
||||
h.event(egui::Event::PointerMoved(to));
|
||||
h.run_steps(1);
|
||||
h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
let mut expected = before;
|
||||
expected.color_dynamics.hue_jitter = 1.0;
|
||||
assert_eq!(h.state().session.tools.brush, expected, "the amount clamps at 100% and preserves neighboring settings");
|
||||
assert_eq!(last_journal(h.state()).unwrap().0, "tools.setBrush");
|
||||
let mut replay = photocraft_engine::Session::new();
|
||||
for (id, params) in h.state().session.journal.clone() {
|
||||
replay.execute(&id, params).unwrap();
|
||||
}
|
||||
assert_eq!(replay.tools.brush, expected, "the edit remains replayable through the engine");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkbox_only_rows_toggle_without_changing_the_selected_controls() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
@@ -992,7 +1037,7 @@ fn app_harness_with_language(lang: crate::i18n::Lang) -> Harness<'static, Photoc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_sections_paint_simplified_chinese_labels_and_heading() {
|
||||
fn brush_sections_paint_simplified_chinese_labels() {
|
||||
fn collect_text(shape: &egui::Shape, out: &mut Vec<String>) {
|
||||
match shape {
|
||||
egui::Shape::Text(text) => out.push(text.galley.job.text.clone()),
|
||||
@@ -1017,8 +1062,27 @@ fn brush_sections_paint_simplified_chinese_labels_and_heading() {
|
||||
assert!(painted.iter().any(|s| s == translated), "{name} must paint as {translated}");
|
||||
assert!(!painted.iter().any(|s| s == name), "{name} must not paint in English");
|
||||
}
|
||||
let heading = crate::i18n::tr(zh, "Brush Tip Shape");
|
||||
assert_eq!(painted.iter().filter(|s| s.as_str() == heading).count(), 2, "both the section row and heading are translated");
|
||||
}
|
||||
|
||||
/// #3477: the options pane has no title of its own. The selected row in the section list is the
|
||||
/// only place the section's name is painted.
|
||||
#[test]
|
||||
fn options_pane_does_not_repeat_the_selected_sections_name() {
|
||||
fn collect_text(shape: &egui::Shape, out: &mut Vec<String>) {
|
||||
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]
|
||||
|
||||
@@ -512,10 +512,7 @@ fn color_dynamics(ui: &mut egui::Ui, b: &mut BrushSettings) {
|
||||
widgets::checkbox(ui, &mut c.per_tip, tl!("Apply Per Tip"));
|
||||
ui.add_space(6.0);
|
||||
dynamic(ui, "brush-fgbg-ctl", tl!("Foreground/Background Jitter"), &mut c.fg_bg, 1.0, None, false);
|
||||
let mut h = (c.hue_jitter * 100.0).round();
|
||||
if widgets::slider_row(ui, tl!("Hue Jitter"), &mut h, 0.0..=100.0, "%", Some(&widgets::hue_stops())).changed() {
|
||||
c.hue_jitter = (h.round() / 100.0).clamp(0.0, 1.0);
|
||||
}
|
||||
pct(ui, tl!("Hue Jitter"), &mut c.hue_jitter, 1.0);
|
||||
pct(ui, tl!("Saturation Jitter"), &mut c.saturation_jitter, 1.0);
|
||||
pct(ui, tl!("Brightness Jitter"), &mut c.brightness_jitter, 1.0);
|
||||
signed_pct(ui, tl!("Purity"), &mut c.purity, -1.0, 1.0);
|
||||
@@ -648,6 +645,29 @@ mod tests {
|
||||
h
|
||||
}
|
||||
|
||||
/// #3825: jitter is an amount, not a hue selector; it uses the themed amount track.
|
||||
#[test]
|
||||
fn hue_jitter_paints_an_amount_track_in_every_theme() {
|
||||
for kind in theme::ThemeKind::ALL {
|
||||
let mut b = BrushSettings::default();
|
||||
b.color_dynamics.hue_jitter = 0.37;
|
||||
let mut h = section_harness(5, b.clone());
|
||||
crate::PhotocraftApp::setup_context(&h.ctx, kind);
|
||||
h.run_steps(3);
|
||||
let label = h.get_by_label("Hue Jitter").rect();
|
||||
let t = Tokens::get(&h.ctx);
|
||||
assert!(
|
||||
h.output().shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Rect(r)
|
||||
if r.rect.width() > 150.0 && (r.rect.height() - 3.0).abs() < 0.1
|
||||
&& r.rect.top() > label.bottom() && r.rect.bottom() < label.bottom() + 30.0
|
||||
&& r.fill == t.field_border)),
|
||||
"{kind:?}: Hue Jitter paints the same neutral track as other percentage amounts"
|
||||
);
|
||||
assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.accesskit_node().numeric_value() == Some(37.0)));
|
||||
assert_eq!(h.state(), &b, "rendering does not change saved brush settings");
|
||||
}
|
||||
}
|
||||
|
||||
fn set_controls(b: &mut BrushSettings, control: Control) {
|
||||
for d in [
|
||||
&mut b.shape_dynamics.size,
|
||||
|
||||
@@ -475,6 +475,22 @@ fn darker(c: Color32, f: f32) -> Color32 {
|
||||
Color32::from_rgba_unmultiplied((r as f32 * f).round() as u8, (g as f32 * f).round() as u8, (b as f32 * f).round() as u8, a)
|
||||
}
|
||||
|
||||
/// Where a card's tip thumbnail goes in its `cell`. `number_h` is the height of the size number
|
||||
/// under it, `None` on compact cards (no number: the tip takes the cell whole). Otherwise the
|
||||
/// number keeps a band at the bottom of the cell and the tip is centred in what's left above it,
|
||||
/// at [`CARD_TIP_BASE`] × `scale` or that room's side, whichever is smaller, times the preset's
|
||||
/// [`crate::brush_sections::thumb_scale`]: big brushes still read bigger than small ones, and
|
||||
/// none of them reaches down over the number.
|
||||
fn card_tip_rect(cell: egui::Rect, number_h: Option<f32>, size: f32, scale: f32) -> egui::Rect {
|
||||
let Some(number_h) = number_h else {
|
||||
return egui::Rect::from_center_size(cell.center(), egui::Vec2::splat((cell.width().min(cell.height()) - 2.0).max(1.0)));
|
||||
};
|
||||
// The number sits 1 pt off the cell's bottom, with a 1 pt gap above it.
|
||||
let room = egui::Rect::from_min_max(cell.min, pos2(cell.right(), (cell.bottom() - number_h - 2.0).max(cell.top())));
|
||||
let side = (CARD_TIP_BASE * scale).min(room.width().min(room.height())).max(0.0) * crate::brush_sections::thumb_scale(size);
|
||||
egui::Rect::from_center_size(room.center(), egui::Vec2::splat(if side.is_finite() { side.max(1.0) } else { 1.0 }))
|
||||
}
|
||||
|
||||
/// One preset in the Brush Preset picker: a 2 × 2 grid whose bottom row (the name) spans both
|
||||
/// columns — tip at the top left, stroke preview at the top right. A part that's off loses its
|
||||
/// cell (the other takes the room): with only the tip and the name on, the name moves into the
|
||||
@@ -545,18 +561,13 @@ fn preset_card(
|
||||
let tip_w = if tip_only { top.width() } else { (CARD_TIP_W * scale).min(top.width() * 0.5) };
|
||||
let cell = egui::Rect::from_min_size(top.left_top(), vec2(tip_w, top_h));
|
||||
let tip = brush_preview::tip_texture(ui.ctx(), &format!("brushes-tip:{}", p.name), &pb.tip, (pb.hardness, pb.angle, pb.roundness), 36, t.text);
|
||||
let side = if compact { (cell.width().min(cell.height()) - 2.0).max(1.0) } else { CARD_TIP_BASE * scale * crate::brush_sections::thumb_scale(pb.size) };
|
||||
let center = if compact { cell.center() } else { pos2(cell.center().x, cell.center().y - 2.0 * scale_h) };
|
||||
let tr = egui::Rect::from_center_size(center, vec2(side, side));
|
||||
let number =
|
||||
(!compact).then(|| ui.painter().layout_no_wrap(format!("{}", pb.size.round() as i64), egui::FontId::proportional(CARD_NUM_FONT), t.text_faint));
|
||||
let tr = card_tip_rect(cell, number.as_ref().map(|g| g.size().y), pb.size, scale);
|
||||
ui.painter().image(tip.id(), tr, full_uv(), Color32::WHITE);
|
||||
if !compact {
|
||||
ui.painter().text(
|
||||
pos2(cell.center().x, cell.bottom() - 1.0),
|
||||
egui::Align2::CENTER_BOTTOM,
|
||||
format!("{}", pb.size.round() as i64),
|
||||
egui::FontId::proportional(CARD_NUM_FONT),
|
||||
t.text_faint,
|
||||
);
|
||||
if let Some(g) = number {
|
||||
let at = pos2(cell.center().x - g.size().x / 2.0, cell.bottom() - 1.0 - g.size().y);
|
||||
ui.painter().galley(at, g, t.text_faint);
|
||||
}
|
||||
x = cell.right();
|
||||
}
|
||||
|
||||
@@ -265,3 +265,56 @@ fn the_brushes_tab_grid_is_centred_past_its_indent() {
|
||||
h.run_steps(6);
|
||||
rows_are_centred(&h, PANEL_LIST.indent, 2);
|
||||
}
|
||||
|
||||
/// #4454: a card's size number sat under the tip thumbnail of any medium or large brush (the
|
||||
/// tip took up to 44.8 pt of a 42 pt cell, the number anchored to the cell's bottom), so the
|
||||
/// "30" of Hard Round and the "45" of Soft Round couldn't be read. At every footer scale that
|
||||
/// shows numbers, in each card kind, the tip now stays above the number, and bigger brushes still
|
||||
/// get bigger tips.
|
||||
#[test]
|
||||
fn card_tips_never_cover_their_size_number() {
|
||||
let number_h = std::rc::Rc::new(std::cell::Cell::new(0.0_f32));
|
||||
let seen = number_h.clone();
|
||||
let mut h = Harness::new_ui(move |ui| {
|
||||
let g = ui.painter().layout_no_wrap("45".into(), egui::FontId::proportional(CARD_NUM_FONT), Color32::WHITE);
|
||||
seen.set(g.size().y);
|
||||
});
|
||||
PhotocraftApp::setup_context(&h.ctx, Default::default());
|
||||
h.run();
|
||||
let number_h = number_h.get();
|
||||
assert!(number_h > 8.0, "the number has a real height: {number_h}");
|
||||
let mut scale = CARD_COMPACT_SCALE + 0.01;
|
||||
while scale <= *crate::brush_picker::SCALE_RANGE.end() + 1e-3 {
|
||||
let scale_h = scale.max(CARD_MIN_H_SCALE);
|
||||
// The tip cell of a full card (name row under it), a tip-and-name card and a tip-only one,
|
||||
// as [`preset_card`] sizes them in a wide column.
|
||||
let cells = [
|
||||
vec2(CARD_TIP_W * scale, (CARD_MAX_H - CARD_PAD * 2.0 - CARD_NAME_H) * scale_h),
|
||||
vec2(CARD_TIP_W * scale, (CARD_TIP_NAME_H - CARD_PAD * 2.0) * scale_h),
|
||||
vec2((CARD_TIP_ONLY_W - 16.0) * scale, (CARD_TIP_ONLY_H - CARD_PAD * 2.0) * scale_h),
|
||||
];
|
||||
for size in cells {
|
||||
let cell = Rect::from_min_size(egui::pos2(10.0, 20.0), size);
|
||||
let number_top = cell.bottom() - 1.0 - number_h;
|
||||
let mut last = 0.0;
|
||||
for brush in [1.0, 5.0, 13.0, 30.0, 45.0, 100.0, 2500.0] {
|
||||
let tip = card_tip_rect(cell, Some(number_h), brush, scale);
|
||||
assert!(tip.bottom() <= number_top + 1e-3, "scale {scale}, cell {size:?}, {brush} px: tip {tip:?} reaches the number at {number_top}");
|
||||
assert!(cell.expand(1e-3).contains_rect(tip), "scale {scale}, {brush} px: tip {tip:?} leaves its cell {cell:?}");
|
||||
assert!(tip.width() >= last, "scale {scale}, {brush} px: a bigger brush gets a smaller tip");
|
||||
last = tip.width();
|
||||
}
|
||||
}
|
||||
scale += 0.05;
|
||||
}
|
||||
// The tip-only grid's cells are tall enough for the number: a big brush's tip still spans
|
||||
// the cell's width.
|
||||
let cell = Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(CARD_TIP_ONLY_W - 16.0, CARD_TIP_ONLY_H - CARD_PAD * 2.0));
|
||||
assert!((card_tip_rect(cell, Some(number_h), 45.0, 1.0).width() - cell.width()).abs() < 1e-3);
|
||||
// Compact cards: no number, the tip fills the cell; nonsense never makes a non-finite rect.
|
||||
assert_eq!(card_tip_rect(cell, None, 45.0, 0.5).width(), cell.width() - 2.0);
|
||||
for (n, size, scale) in [(f32::NAN, 30.0, 1.0), (500.0, f32::NAN, 1.0), (12.0, 30.0, f32::INFINITY), (12.0, -5.0, 0.0)] {
|
||||
let r = card_tip_rect(cell, Some(n), size, scale);
|
||||
assert!(r.min.is_finite() && r.max.is_finite(), "{n} {size} {scale}: {r:?}");
|
||||
}
|
||||
}
|
||||
+113
-13
@@ -944,8 +944,10 @@ pub fn doc_point_at(app: &PhotocraftApp, pos: Pos2) -> Option<[f64; 2]> {
|
||||
pub fn fit_view(view: &mut View, doc: &Document, area: Vec2, ppp: f32, aspect: f32) {
|
||||
let (w, h) = (doc.size.width as f32, doc.size.height as f32);
|
||||
let shown_w = w * if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 };
|
||||
let points = ((area.x - 40.0) / shown_w).min((area.y - 40.0) / h).min(1.0);
|
||||
let zoom = crate::zoom_levels::clamp(points * ppp, [doc.size.width, doc.size.height]);
|
||||
// Fit never magnifies past 100%: one image pixel per *physical* pixel, so the cap applies
|
||||
// after the points → device pixels conversion (a 150% display would otherwise open at 150%).
|
||||
let fit = ((area.x - 40.0) / shown_w).min((area.y - 40.0) / h) * ppp;
|
||||
let zoom = crate::zoom_levels::clamp(fit.min(1.0), [doc.size.width, doc.size.height]);
|
||||
view.zoom = zoom;
|
||||
view.center = [w / 2.0, h / 2.0];
|
||||
view.fit_pending = false;
|
||||
@@ -1254,6 +1256,14 @@ pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz
|
||||
Some(tex.id())
|
||||
}
|
||||
|
||||
/// The CPU canvas texture's sampling (#4810). Zoomed in, a full-resolution texture shows each
|
||||
/// document pixel as a crisp square, as the GPU canvas's sharp nearest filter and Photoshop do;
|
||||
/// zoomed out it is still filtered. A reduced texture (`factor` > 1) stays bilinear: its texels
|
||||
/// are averages of several pixels, and squares of them would be blocks the image doesn't have.
|
||||
fn canvas_texture_options(factor: u32) -> TextureOptions {
|
||||
if factor > 1 { TextureOptions::LINEAR } else { TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR } }
|
||||
}
|
||||
|
||||
/// Make sure the canvas texture for document `idx` on `display` is current; returns (texture
|
||||
/// id, scale).
|
||||
pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, display: Option<u32>) -> Option<(egui::TextureId, f32)> {
|
||||
@@ -1298,7 +1308,7 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize,
|
||||
let r = buf.rect;
|
||||
if !r.is_empty() {
|
||||
let t1 = crate::gpu_canvas::now_ms();
|
||||
t.set_partial([r.x0 as usize, r.y0 as usize], display_image(display.as_deref(), &buf), TextureOptions::LINEAR);
|
||||
t.set_partial([r.x0 as usize, r.y0 as usize], display_image(display.as_deref(), &buf), canvas_texture_options(factor));
|
||||
let px = (r.width() as u64 * r.height() as u64).saturating_mul(u64::from(factor).pow(2));
|
||||
app.perf.record("rect", px, t1 - t0, crate::gpu_canvas::now_ms() - t1);
|
||||
}
|
||||
@@ -1308,8 +1318,8 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize,
|
||||
let t1 = crate::gpu_canvas::now_ms();
|
||||
let (img, scale) = (display_image(display.as_deref(), &full), 1.0 / factor as f32);
|
||||
match cache.texture.as_mut() {
|
||||
Some(t) if t.size() == img.size => t.set(img, TextureOptions::LINEAR),
|
||||
_ => cache.texture = Some(ctx.load_texture(format!("canvas-{}-{}", id.0, cache_key(id, output).1), img, TextureOptions::LINEAR)),
|
||||
Some(t) if t.size() == img.size => t.set(img, canvas_texture_options(factor)),
|
||||
_ => cache.texture = Some(ctx.load_texture(format!("canvas-{}-{}", id.0, cache_key(id, output).1), img, canvas_texture_options(factor))),
|
||||
}
|
||||
cache.scale = scale;
|
||||
app.perf.record("full", doc.size.width as u64 * doc.size.height as u64, t1 - t0, crate::gpu_canvas::now_ms() - t1);
|
||||
@@ -3253,7 +3263,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
(buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false);
|
||||
}
|
||||
// Zoom tool drags: scrubby zoom or a zoom rectangle (zoom_tool.rs); clicks step below.
|
||||
if tool == Tool::Zoom && crate::zoom_tool::drag(app, &ctx, &mut view, &xf, &buttons, response.interact_pointer_pos()) {
|
||||
// Like the Hand, the selected Zoom yields to an open Free Transform box (#4799).
|
||||
if tool == Tool::Zoom && !transform_owns_pointer && crate::zoom_tool::drag(app, &ctx, &mut view, &xf, &buttons, response.interact_pointer_pos()) {
|
||||
(buttons.started, buttons.dragged, buttons.stopped) = (false, false, false);
|
||||
}
|
||||
// A drag is only recognised once the pointer has moved past egui's click distance: the
|
||||
@@ -3387,7 +3398,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods);
|
||||
let d = xf.to_doc(p);
|
||||
match tool {
|
||||
Tool::Zoom => {
|
||||
Tool::Zoom if !transform_owns_pointer => {
|
||||
let nz = crate::zoom_levels::step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }, view.doc_size);
|
||||
let center = app.session.prefs().tools.zoom_clicked_point_to_center;
|
||||
zoom_about(&mut view, &xf, p, nz, center, ppp);
|
||||
@@ -5850,6 +5861,46 @@ mod tests {
|
||||
assert_eq!((app.canvases[&(id, 1)].tex_revision, app.canvases[&(id, 4)].tex_revision), (rev, rev));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_canvas_shows_crisp_pixels_when_zoomed_in() {
|
||||
// #4810: above 100% the CPU canvas shows each pixel as a square, like the GPU canvas's
|
||||
// sharp nearest filter; below 100% it still filters. Both the first upload and a
|
||||
// damage-rect update carry the sampling, since the renderer takes it from each delta.
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 2, "height": 2})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let tex = ensure_texture(&mut app, &ctx, 0, None).unwrap().0;
|
||||
let uploads = |ctx: &egui::Context| {
|
||||
let mut delta = ctx.tex_manager().write().take_delta();
|
||||
let seen = delta.set.get(&tex).into_iter().flatten().map(|d| (d.pos.is_some(), d.options)).collect::<Vec<_>>();
|
||||
delta.clear();
|
||||
seen
|
||||
};
|
||||
let crisp = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR };
|
||||
assert_eq!(uploads(&ctx), vec![(false, crisp)]);
|
||||
app.run("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap();
|
||||
ensure_texture(&mut app, &ctx, 0, None).unwrap();
|
||||
uploads(&ctx);
|
||||
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
|
||||
assert_eq!(ensure_texture(&mut app, &ctx, 0, None).unwrap().0, tex);
|
||||
assert_eq!(uploads(&ctx), vec![(true, crisp)], "a partial update keeps the crisp sampling");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_canvas_of_a_reduced_document_stays_bilinear() {
|
||||
// Over MAX_TEXTURE the texture holds one texel per `factor` pixels: a texel is not a
|
||||
// document pixel, so showing it as a square would draw blocks that aren't in the image.
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": MAX_TEXTURE + 1, "height": 2})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let (tex, scale) = ensure_texture(&mut app, &ctx, 0, None).unwrap();
|
||||
assert!(scale < 1.0);
|
||||
let mut delta = ctx.tex_manager().write().take_delta();
|
||||
let uploads: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| d.options).collect();
|
||||
delta.clear();
|
||||
assert_eq!(uploads, vec![TextureOptions::LINEAR]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_display_luts_are_per_display() {
|
||||
let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else {
|
||||
@@ -7210,6 +7261,46 @@ mod tests {
|
||||
assert!(app.style_preview.is_none());
|
||||
}
|
||||
|
||||
/// Layer Style opened while Free Transform is open applies the box first, as Photoshop does,
|
||||
/// so the dialog previews on the transformed layer (#4821): a dropped file (placed in the box,
|
||||
/// untouched) and a box opened by hand and moved.
|
||||
#[test]
|
||||
fn layer_style_opened_during_free_transform_applies_the_box_and_previews() {
|
||||
for placed in [true, false] {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
app.run("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap();
|
||||
app.run("edit.fill", json!({"color": "#0000ff"})).unwrap();
|
||||
app.run("select.deselect", json!({})).unwrap();
|
||||
app.sync_views();
|
||||
let ctx = egui::Context::default();
|
||||
let dx = if placed {
|
||||
crate::transform_tool::begin_placed(&mut app, &ctx).unwrap();
|
||||
0
|
||||
} else {
|
||||
crate::transform_tool::begin(&mut app, &ctx).unwrap();
|
||||
app.ui.transform.as_mut().unwrap().quad = [[28.0, 8.0], [44.0, 8.0], [44.0, 24.0], [28.0, 24.0]];
|
||||
20
|
||||
};
|
||||
crate::layer_style::open(&mut app, Some("dropShadow")).unwrap();
|
||||
assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "placed {placed}: the box is applied");
|
||||
let (shown, _) = display_doc(&mut app, 0);
|
||||
let rect = photocraft_geom::Rect::new(0, 0, 64, 64);
|
||||
let with = photocraft_compose::render(&shown, rect);
|
||||
let without = photocraft_compose::render(&app.session.documents()[0].doc, rect);
|
||||
assert!(
|
||||
with.get(16 + dx, 16)[0] < 0.1 && with.get(16 + dx, 16)[2] > 0.9,
|
||||
"placed {placed}: the blue block where the box left it, not the white under it"
|
||||
);
|
||||
// The shadow darkens the white around the block, which the document doesn't have yet.
|
||||
let block = |x: i32, y: i32| (8 + dx..24 + dx).contains(&x) && (8..24).contains(&y);
|
||||
let shadow =
|
||||
(0..64).flat_map(|y| (0..64).map(move |x| (x, y))).filter(|&(x, y)| !block(x, y) && without.get(x, y)[0] - with.get(x, y)[0] > 0.05).count();
|
||||
assert!(shadow > 20, "placed {placed}: the Drop Shadow is previewed ({shadow} px)");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_view_covers_the_canvas_and_centres_the_document() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
@@ -7228,13 +7319,22 @@ mod tests {
|
||||
fill_view(&mut view, &doc, vec2(600.0, 600.0), 2.0, 1.0);
|
||||
assert_eq!(view.zoom, 6.0);
|
||||
|
||||
// Fit never magnifies past the 1 point-per-pixel cap; on a scaled display the cap is 2.
|
||||
// Fit never magnifies past 100% = one image pixel per physical pixel, at any display
|
||||
// scale (it used to cap at one per *point*, so a 150% display opened images at 150%).
|
||||
for ppp in [1.0f32, 1.5, 2.0] {
|
||||
let mut view = View { fit_pending: true, ..View::default() };
|
||||
fit_view(&mut view, &doc, vec2(600.0, 600.0), ppp, 1.0);
|
||||
assert_eq!(view.zoom, 1.0, "ppp {ppp}: a small image opens at 100%");
|
||||
}
|
||||
// A large image still shrinks to fit: 1000×500 into 440 points is 0.44 pt/px, so 0.66
|
||||
// physical at ppp 1.5.
|
||||
let big = {
|
||||
app.run("file.new", json!({"width": 1000, "height": 500})).unwrap();
|
||||
app.session.active().unwrap().doc.clone()
|
||||
};
|
||||
let mut view = View { fit_pending: true, ..View::default() };
|
||||
fit_view(&mut view, &doc, vec2(600.0, 600.0), 1.0, 1.0);
|
||||
assert_eq!(view.zoom, 1.0);
|
||||
let mut view = View { fit_pending: true, ..View::default() };
|
||||
fit_view(&mut view, &doc, vec2(600.0, 600.0), 2.0, 1.0);
|
||||
assert_eq!(view.zoom, 2.0);
|
||||
fit_view(&mut view, &big, vec2(480.0, 480.0), 1.5, 1.0);
|
||||
assert!((view.zoom - 0.66).abs() < 1e-5, "{}", view.zoom);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -686,7 +686,7 @@ fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, now: &Compo
|
||||
ui.memory_mut(|m| m.request_focus(id));
|
||||
}
|
||||
let typing = if ui.memory(|m| m.has_focus(id)) { ui.data(|d| d.get_temp::<String>(id)) } else { None };
|
||||
let mut h = typing.unwrap_or_else(|| hex(rgb).trim_start_matches('#').to_string());
|
||||
let mut h = typing.unwrap_or_else(|| hex(rgb).trim_start_matches('#').to_ascii_uppercase());
|
||||
let r = crate::widgets::text_field_ex(ui, id, &mut h, "", 64.0, true, Some(6));
|
||||
if r.gained_focus() {
|
||||
crate::field_tab::select_all(ui.ctx(), id, &h);
|
||||
@@ -859,6 +859,13 @@ mod tests {
|
||||
h.state().get("color").and_then(Value::as_str).unwrap().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_field_shows_uppercase_without_rewriting_the_selected_color() {
|
||||
let h = picker("#12abef");
|
||||
assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("12ABEF"));
|
||||
assert_eq!(color(&h), "#12abef", "casing is presentation only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_field_takes_typed_digits() {
|
||||
let mut h = picker("#000000");
|
||||
|
||||
@@ -14,6 +14,11 @@ fn rects(ctx: &egui::Context) -> Vec<egui::Rect> {
|
||||
ctx.data(|m| m.get_temp(egui::Id::new(RECTS))).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The window drag target must not cover a dialog which has been moved into the title bar.
|
||||
pub(crate) fn titlebar_drag_area_is_clear(ctx: &egui::Context, area: egui::Rect) -> bool {
|
||||
rects(ctx).iter().all(|dialog| !dialog.intersects(area))
|
||||
}
|
||||
|
||||
/// With a dialog open the rest of the window is inert (egui's modal layer), but like Photoshop the
|
||||
/// image can still be panned and zoomed under it. The pointer position when it is over `canvas`
|
||||
/// and not over a dialog or one of its popups.
|
||||
@@ -338,7 +343,14 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 10.0;
|
||||
if matches!(d.kind, DialogKind::About | DialogKind::Error) {
|
||||
if dialog_buttons(ui, &[DialogButton::new(ButtonRole::Default, tl!("OK"), 84.0)]).is_some() {
|
||||
// ↩ is OK too, as on every other dialog (#4872), from the frame after the
|
||||
// alert appeared: the ↩ that raised it (committing a locked layer's Free
|
||||
// Transform, say) must not close it again at once.
|
||||
let seen = id.with("alert-seen");
|
||||
let shown_before = ui.ctx().data(|m| m.get_temp::<bool>(seen).unwrap_or(false));
|
||||
ui.ctx().data_mut(|m| m.insert_temp(seen, true));
|
||||
let enter = interactive && shown_before && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
if dialog_buttons(ui, &[DialogButton::new(ButtonRole::Default, tl!("OK"), 84.0)]).is_some() || enter {
|
||||
outcome = Some(false);
|
||||
}
|
||||
} else {
|
||||
@@ -795,6 +807,32 @@ mod tests {
|
||||
assert_eq!(harness.state().ui.dialogs.len(), 1, "dragging must not close the dialog");
|
||||
}
|
||||
|
||||
/// #4872: an alert (Error, About) closes with ↩ as with OK, but not on the ↩ that raised it.
|
||||
#[test]
|
||||
fn enter_closes_an_alert_but_not_the_enter_that_opened_it() {
|
||||
let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 600.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app);
|
||||
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
|
||||
h.run_steps(2);
|
||||
let alert = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>| {
|
||||
h.state_mut().ui.open_dialog(DialogKind::Error, json!({"message": crate::move_lock::MESSAGE}).as_object().cloned().unwrap_or_default())
|
||||
};
|
||||
// Raised in the frame its own ↩ arrives: that ↩ leaves it open.
|
||||
alert(&mut h);
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.dialogs.len(), 1, "the ↩ that raised the alert doesn't close it");
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.dialogs.is_empty(), "↩ is OK");
|
||||
// A new alert starts over, and Esc still closes it.
|
||||
alert(&mut h);
|
||||
h.run_steps(2);
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.dialogs.is_empty(), "Esc too");
|
||||
}
|
||||
|
||||
fn dialog_harness(size: egui::Vec2, command: &str) -> egui_kittest::Harness<'static, PhotocraftApp> {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! canvas to marquee-select anchors, click empty canvas to deselect.
|
||||
//! * Drag selected anchors to move them, a direction handle to turn it (a smooth point keeps its
|
||||
//! handles collinear; ⌥ breaks them apart), or a segment to bend it (straight segments move).
|
||||
//! The arrow keys nudge the selected anchors 1 px (⇧ 10 px), one history step per press.
|
||||
//! * Convert Point (the tool, or Pen + ⌥): click an anchor to make it a corner, drag from it to
|
||||
//! pull out smooth handles, drag a handle to move it alone. The tool selects the anchor it
|
||||
//! converts, so its handles show; a press on empty canvas or a segment does nothing, and ⌘/Ctrl
|
||||
@@ -346,6 +347,37 @@ fn marquee(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2], add: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Arrow keys with Direct Selection and selected anchors (#4486), as in Photoshop: nudge them
|
||||
/// 1 px (⇧ 10 px) through `path.moveAnchors`, one history step per press. Not while a drag is
|
||||
/// in progress. Returns true when a key was used.
|
||||
pub fn arrow_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
let ds = &app.ui.direct_selection;
|
||||
let Some(target) = ds.target.filter(|_| app.ui.tool == Tool::DirectSelection && !ds.anchors.is_empty() && ds.drag.is_none()) else {
|
||||
return false;
|
||||
};
|
||||
let anchors = ds.anchors.clone();
|
||||
use egui::Key;
|
||||
let keys = [(Key::ArrowLeft, -1.0, 0.0), (Key::ArrowRight, 1.0, 0.0), (Key::ArrowUp, 0.0, -1.0), (Key::ArrowDown, 0.0, 1.0)];
|
||||
for (key, ux, uy) in keys {
|
||||
// ⇧ first: `consume_key` ignores an extra ⇧.
|
||||
for mods in [Modifiers::SHIFT, Modifiers::NONE] {
|
||||
if ctx.input_mut(|i| i.consume_key(mods, key)) {
|
||||
let k = if mods.shift { 10.0 } else { 1.0 };
|
||||
let mut params = json!({"anchors": anchors, "move": [ux * k, uy * k]});
|
||||
if let (Some(p), Some(t)) = (params.as_object_mut(), target.params().as_object()) {
|
||||
p.extend(t.clone());
|
||||
}
|
||||
if let Err(e) = app.run("path.moveAnchors", params) {
|
||||
app.ui.status = e;
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Paths with their anchors (selected ones filled), the shown handles, the drag's preview in
|
||||
/// place of its path, and the marquee. `paths` false (View › Show › Target Path off) leaves only
|
||||
/// the marquee.
|
||||
|
||||
@@ -225,3 +225,39 @@ fn the_convert_point_tool_shows_the_path_overlay() {
|
||||
assert!(!super::shows(&app, Modifiers::NONE));
|
||||
assert!(super::shows(&app, Modifiers::COMMAND));
|
||||
}
|
||||
|
||||
/// One key press through the canvas arrow keys, as egui delivers it.
|
||||
fn press(app: &mut PhotocraftApp, key: egui::Key, mods: Modifiers) -> bool {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.input_mut(|i| {
|
||||
i.modifiers = mods;
|
||||
i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: mods });
|
||||
});
|
||||
crate::move_mods::arrow_keys(app, &ctx)
|
||||
}
|
||||
|
||||
/// #4486: the arrow keys nudge the selected anchors 1 px (⇧ 10 px), one history step per press,
|
||||
/// as in Photoshop. With no anchor selected they leave the path alone.
|
||||
#[test]
|
||||
fn arrow_keys_nudge_the_selected_anchors() {
|
||||
let mut app = app(Tool::DirectSelection);
|
||||
with_path(&mut app);
|
||||
// The path stays targeted after a click on empty canvas, but no anchor is selected.
|
||||
click(&mut app, [40.0, 120.0], Modifiers::NONE);
|
||||
click(&mut app, [80.0, 80.0], Modifiers::NONE);
|
||||
assert_eq!(app.ui.direct_selection.target, Some(PathRef::Work));
|
||||
let n = steps(&app);
|
||||
assert!(!press(&mut app, egui::Key::ArrowRight, Modifiers::NONE), "no anchor selected: not Direct Selection's key");
|
||||
assert_eq!(steps(&app), n);
|
||||
click(&mut app, [40.0, 120.0], Modifiers::NONE);
|
||||
click(&mut app, [120.0, 120.0], Modifiers::SHIFT);
|
||||
let (before, n) = (work(&app), steps(&app));
|
||||
assert!(press(&mut app, egui::Key::ArrowRight, Modifiers::NONE));
|
||||
assert_eq!((anchor(&app, 2), anchor(&app, 3)), (Point::new(121.0, 120.0), Point::new(41.0, 120.0)));
|
||||
assert!(press(&mut app, egui::Key::ArrowDown, Modifiers::SHIFT));
|
||||
assert_eq!((anchor(&app, 2), anchor(&app, 3)), (Point::new(121.0, 130.0), Point::new(41.0, 130.0)), "⇧ nudges 10 px");
|
||||
assert_eq!(anchor(&app, 0), Point::new(40.0, 40.0), "unselected anchors stay");
|
||||
assert_eq!(steps(&app), n + 2, "one history step per press");
|
||||
assert!(app.session.undo() && app.session.undo());
|
||||
assert_eq!(work(&app), before);
|
||||
}
|
||||
@@ -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())
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -385,6 +385,36 @@ fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map<S
|
||||
if command == "view.proofSetup" {
|
||||
proof_setup_defaults(app, fields);
|
||||
}
|
||||
if command == "edit.assignProfile" {
|
||||
assign_profile_defaults(app, fields);
|
||||
}
|
||||
}
|
||||
|
||||
/// Assign Profile offers only the profiles the document's colour mode can take (#4951): the
|
||||
/// command refuses one of another colour space. `__profiles` lists them for the `profile` menu,
|
||||
/// and a remembered choice that doesn't fit this document falls back to the working space.
|
||||
fn assign_profile_defaults(app: &PhotocraftApp, fields: &mut Map<String, Value>) {
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let Some(spec) = photocraft_engine::commands::find("edit.assignProfile") else { return };
|
||||
let space = photocraft_engine::color_cmds::mode_space(st.doc.mode);
|
||||
let fits = |name: &str| name == "none" || app.session.color.resolve(name, Some(&st.doc), None).is_ok_and(|p| p.color_space == space);
|
||||
let builtin: Vec<String> = parse_spec(spec.params)
|
||||
.into_iter()
|
||||
.filter(|p| p.key == "profile")
|
||||
.flat_map(|p| match p.kind {
|
||||
Kind::Choice { options, .. } => options,
|
||||
_ => Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
let installed: Vec<_> = photocraft_engine::installed_profiles::installed().into_iter().filter(|i| i.is_destination()).collect();
|
||||
let allowed: Vec<String> =
|
||||
builtin.iter().filter(|name| fits(name)).cloned().chain(installed.iter().filter(|i| i.color_space == space).map(|i| i.path.clone())).collect();
|
||||
// A path nobody lists (typed by an agent) is left alone: the command decides about it.
|
||||
let listed = |cur: &str| builtin.iter().any(|name| name == cur) || installed.iter().any(|i| i.path == cur);
|
||||
if fields.get("profile").and_then(Value::as_str).is_some_and(|cur| listed(cur) && !allowed.iter().any(|name| name == cur)) {
|
||||
fields.insert("profile".into(), json!("working"));
|
||||
}
|
||||
fields.insert("__profiles".into(), json!(allowed));
|
||||
}
|
||||
|
||||
/// Alt+Cancel (Reset): schema defaults + command hooks, without last-used remembered prefs.
|
||||
@@ -665,6 +695,12 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
|
||||
Vec::new()
|
||||
};
|
||||
opts.extend(installed.iter().map(|i| (i.path.clone(), i.description.as_str())));
|
||||
// Assign Profile: only what the document's colour mode can take (#4951).
|
||||
if p.key == "profile"
|
||||
&& let Some(allowed) = f.get("__profiles").and_then(Value::as_array)
|
||||
{
|
||||
opts.retain(|(v, _)| allowed.iter().any(|a| a.as_str() == Some(v.as_str())));
|
||||
}
|
||||
// A profile given by path that isn't listed (typed by an agent, or spelled with
|
||||
// different case) still shows, by its file name, instead of a blank menu.
|
||||
let stem = std::path::Path::new(&cur).file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
@@ -1931,6 +1967,61 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The profiles Assign Profile offers for a new document converted with `mode` (if any),
|
||||
/// and which of the command's built-in profiles the command itself accepts for it.
|
||||
fn assign_profile_offers(mode: Option<&str>) -> (Vec<String>, Vec<String>) {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
if let Some(mode) = mode {
|
||||
app.run(mode, json!({})).unwrap();
|
||||
}
|
||||
open(&mut app, "edit.assignProfile").unwrap();
|
||||
let offered: Vec<String> =
|
||||
app.ui.dialogs.last().unwrap().fields["__profiles"].as_array().unwrap().iter().filter_map(|v| v.as_str().map(str::to_owned)).collect();
|
||||
let spec = photocraft_engine::commands::find("edit.assignProfile").unwrap();
|
||||
let builtin = parse_spec(spec.params).into_iter().find(|p| p.key == "profile").unwrap();
|
||||
let Kind::Choice { options, .. } = builtin.kind else { panic!("profile is a menu") };
|
||||
let accepted = options.into_iter().filter(|name| app.session.execute("edit.assignProfile", json!({"profile": name})).is_ok()).collect();
|
||||
(offered, accepted)
|
||||
}
|
||||
|
||||
/// #4951: Assign Profile lists the profiles the command accepts for the document's colour
|
||||
/// mode, and none of the others.
|
||||
#[test]
|
||||
fn assign_profile_offers_only_profiles_of_the_documents_colour_mode() {
|
||||
for mode in [None, Some("image.mode.cmyk"), Some("image.mode.grayscale")] {
|
||||
let (offered, accepted) = assign_profile_offers(mode);
|
||||
for name in &accepted {
|
||||
assert!(offered.contains(name), "{mode:?}: {name} can be assigned, so it is offered");
|
||||
}
|
||||
for name in ["srgb", "coated-cmyk", "sgray"] {
|
||||
assert_eq!(offered.iter().any(|o| o == name), accepted.iter().any(|a| a == name), "{mode:?}: {name}");
|
||||
}
|
||||
assert!(offered.iter().any(|o| o == "working") && offered.iter().any(|o| o == "none"), "{mode:?}: working space and none always fit");
|
||||
}
|
||||
let (rgb, _) = assign_profile_offers(None);
|
||||
assert!(rgb.iter().any(|o| o == "srgb") && !rgb.iter().any(|o| o == "coated-cmyk"), "an RGB document gets RGB profiles");
|
||||
let (cmyk, _) = assign_profile_offers(Some("image.mode.cmyk"));
|
||||
assert!(cmyk.iter().any(|o| o == "coated-cmyk") && !cmyk.iter().any(|o| o == "srgb"), "a CMYK document gets CMYK profiles");
|
||||
}
|
||||
|
||||
/// #4951: a profile remembered from a document of another colour mode isn't preselected.
|
||||
#[test]
|
||||
fn assign_profile_drops_a_remembered_profile_that_does_not_fit() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
app.session.prefs.edit(|prefs| {
|
||||
prefs.dialogs.insert("edit.assignProfile".into(), json!({"profile": "coated-cmyk"}));
|
||||
});
|
||||
open(&mut app, "edit.assignProfile").unwrap();
|
||||
assert_eq!(app.ui.dialogs.last().unwrap().fields["profile"], json!("working"));
|
||||
app.session.prefs.edit(|prefs| {
|
||||
prefs.dialogs.insert("edit.assignProfile".into(), json!({"profile": "display-p3"}));
|
||||
});
|
||||
open(&mut app, "edit.assignProfile").unwrap();
|
||||
assert_eq!(app.ui.dialogs.last().unwrap().fields["profile"], json!("display-p3"), "one that fits is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_dialogs_respect_explicit_dropdown_defaults() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
|
||||
@@ -638,14 +638,14 @@ impl GpuCanvas {
|
||||
let mut renderer = self.rs.renderer.write();
|
||||
let Some(res) = renderer.callback_resources.get_mut::<Resources>() else { return };
|
||||
if res.docs.keys().any(|k| !live.contains(k)) {
|
||||
let gone: Vec<u64> = res.docs.keys().filter(|k| !live.contains(k)).copied().collect();
|
||||
if let Some(c) = res.compositor.as_mut() {
|
||||
for k in &gone {
|
||||
c.forget_doc(photocraft_doc::DocId(*k));
|
||||
}
|
||||
}
|
||||
res.docs.retain(|k, _| live.contains(k));
|
||||
}
|
||||
// Everything the compositor holds for documents that aren't open, also when their
|
||||
// texture entry was dropped earlier (over budget, a failed render), which used to leave
|
||||
// their pages and effect maps resident after closing (#4529).
|
||||
if let Some(c) = res.compositor.as_mut() {
|
||||
c.retain_docs(|d| live.contains(&d.0));
|
||||
}
|
||||
// LUTs and identity-transform signatures can outlive document textures. Prune both,
|
||||
// or a preserved-ID reopen can skip rebuilding a missing LUT.
|
||||
res.luts.retain(|k, _| live.contains(&k.0));
|
||||
|
||||
@@ -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<u64>) {
|
||||
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");
|
||||
|
||||
@@ -157,6 +157,10 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,
|
||||
let color = rgb(color).ok_or("invalid guide color")?;
|
||||
let hex = format!("#{:02x}{:02x}{:02x}", color.r(), color.g(), color.b());
|
||||
let result = app.run(COMMAND, params(f))?;
|
||||
// The preview is visible even when guides were hidden. Keep a committed layout visible too.
|
||||
app.ui.view.extras = true;
|
||||
app.ui.view.show.canvas_guides = true;
|
||||
app.ui.extras.guides = true;
|
||||
app.session.prefs.edit(|prefs| prefs.guides_grid_and_slices.guide_color = hex);
|
||||
let mut remembered = f.clone();
|
||||
for key in [MARK, "__command", "__label", "__document", "__previewGuides", "__previewParams", "__previewSource"] {
|
||||
|
||||
@@ -1,5 +1,56 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn applying_a_previewed_layout_reveals_hidden_guides() {
|
||||
for hidden in ["extras", "canvas", "guides"] {
|
||||
let mut app = app();
|
||||
match hidden {
|
||||
"extras" => app.ui.view.extras = false,
|
||||
"canvas" => app.ui.view.show.canvas_guides = false,
|
||||
_ => app.ui.extras.guides = false,
|
||||
}
|
||||
let id = open(&mut app);
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
assert!(preview(&app, doc).is_some(), "the dialog shows a preview despite hidden {hidden}");
|
||||
crate::dialogs::confirm(&mut app, id).unwrap();
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
assert!(!doc.guides.vertical.is_empty(), "the layout was actually created");
|
||||
assert!(preview(&app, doc).is_none(), "the temporary preview is gone");
|
||||
assert!(app.ui.view.shows(app.ui.view.show.canvas_guides) && app.ui.extras.guides, "applied guides must remain visible when {hidden} was hidden");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_invalid_and_empty_layouts_keep_guides_hidden() {
|
||||
for action in ["cancel", "invalid", "empty"] {
|
||||
let mut app = app();
|
||||
app.ui.view.extras = false;
|
||||
app.ui.view.show.canvas_guides = false;
|
||||
app.ui.extras.guides = false;
|
||||
let id = open(&mut app);
|
||||
match action {
|
||||
"cancel" => {
|
||||
crate::dialogs::cancel(&mut app, id).unwrap();
|
||||
}
|
||||
"invalid" => {
|
||||
app.ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("invalid"));
|
||||
assert!(crate::dialogs::confirm(&mut app, id).is_err());
|
||||
}
|
||||
_ => {
|
||||
let f = &mut app.ui.dialog_mut(id).unwrap().fields;
|
||||
for key in ["__columnsEnabled", "__rowsEnabled", "__marginEnabled"] {
|
||||
f.insert(key.into(), json!(false));
|
||||
}
|
||||
f.insert("clearExisting".into(), json!(true));
|
||||
assert!(crate::dialogs::confirm(&mut app, id).is_err(), "an empty layout is rejected");
|
||||
}
|
||||
}
|
||||
let guides = &app.session.active().unwrap().doc.guides;
|
||||
assert!(guides.vertical.is_empty() && guides.horizontal.is_empty(), "{action}");
|
||||
assert!(!app.ui.view.extras && !app.ui.view.show.canvas_guides && !app.ui.extras.guides, "{action} must not change visibility");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_includes_optional_sizes_and_shift_tab_selects_their_text() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -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"));
|
||||
});
|
||||
}
|
||||
@@ -388,7 +389,8 @@ fn czech_status_notices_and_navigator_draw_translated_text() {
|
||||
});
|
||||
h.run_steps(4);
|
||||
let text = drawn_text(&h);
|
||||
for want in ["Zvětšení", "Soubor English file.psd se nepodařilo otevřít: disk full", "Předvolby nelze uložit"] {
|
||||
// The Navigator's own text is its tab title now: its zoom row has no label (#4840).
|
||||
for want in ["Navigátor", "Soubor English file.psd se nepodařilo otevřít: disk full", "Předvolby nelze uložit"] {
|
||||
assert!(text.iter().any(|text| text == want), "missing {want}: {text:?}");
|
||||
}
|
||||
// Czech text must be drawable by the bundled fonts, including the new notices.
|
||||
|
||||
@@ -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`).
|
||||
|
||||
@@ -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 Длина
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -503,6 +503,14 @@ pub fn initial_fields(layer: &Layer, select: Option<&str>, light: f32) -> Map<St
|
||||
}
|
||||
|
||||
pub fn open(app: &mut PhotocraftApp, select: Option<&str>) -> Option<u64> {
|
||||
// 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;
|
||||
|
||||
@@ -1840,6 +1840,9 @@ impl eframe::App for PhotocraftApp {
|
||||
notices::show(self, &ctx);
|
||||
gpu_status::show_fallback(self, &ctx);
|
||||
kys_import::show_offer(self, &ctx);
|
||||
if chrome && self.ui.panels.menu_bar && self.custom_titlebar && !self.ui.dialogs.is_empty() {
|
||||
titlebar::modal_drag_overlay(&ctx);
|
||||
}
|
||||
if self.custom_titlebar {
|
||||
titlebar::resize_zones(ui);
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ pub fn arrow_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
use egui::{Key, Modifiers};
|
||||
let cmd = ctx.input(|i| i.modifiers.command) && crate::hold_keys::cmd_nudges(app);
|
||||
if app.ui.tool != Tool::Move && app.ui.transform.is_none() && !cmd {
|
||||
return selection_arrow_keys(app, ctx) || brush_arrow_keys(app, ctx);
|
||||
return selection_arrow_keys(app, ctx) || crate::direct_select::arrow_keys(app, ctx) || brush_arrow_keys(app, ctx);
|
||||
}
|
||||
// `consume_key` never ignores an extra ⌘, so it is part of every pattern while it moves.
|
||||
let base = if cmd { Modifiers::COMMAND } else { Modifiers::NONE };
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The Layers panel New Layer button: a click makes a layer at once, ⌥-click opens the New Layer
|
||||
//! dialog first, as in Photoshop.
|
||||
//! dialog first, as in Photoshop. Its shortcut is the same pair the other way round: ⇧⌘N asks
|
||||
//! first, ⌥⇧⌘N makes the layer at once (#4794).
|
||||
|
||||
use egui::Modifiers;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
@@ -41,3 +42,46 @@ fn alt_click_opens_the_new_layer_dialog() {
|
||||
crate::dialogs::confirm(h.state_mut(), id).unwrap();
|
||||
assert_eq!(layers(&h), 2);
|
||||
}
|
||||
|
||||
fn dialog_open(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> bool {
|
||||
h.state().ui.dialogs.iter().any(|d| crate::new_layer_ui::owns(&d.fields))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shortcut_asks_first_and_alt_shortcut_makes_a_layer_at_once() {
|
||||
let mut h = panel();
|
||||
h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, egui::Key::N);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layers(&h), 1, "⇧⌘N asks first");
|
||||
assert!(dialog_open(&h), "the New Layer dialog");
|
||||
|
||||
let mut h = panel();
|
||||
h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT | Modifiers::ALT, egui::Key::N);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layers(&h), 2, "⌥⇧⌘N makes the layer");
|
||||
assert!(!dialog_open(&h));
|
||||
h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT | Modifiers::ALT, egui::Key::N);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layers(&h), 3, "once per press");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alt_shortcut_follows_a_custom_new_layer_shortcut_and_yields_to_a_bound_command() {
|
||||
// Rebound to F2: ⌥F2 makes the layer at once.
|
||||
let mut h = panel();
|
||||
h.state_mut().session.prefs.edit(|p| p.shortcuts.insert("layer.new.layer".into(), "F2".into()));
|
||||
h.key_press_modifiers(Modifiers::ALT, egui::Key::F2);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layers(&h), 2);
|
||||
assert!(!dialog_open(&h));
|
||||
// A command bound to ⌥⇧⌘N itself keeps the key.
|
||||
let mut h = panel();
|
||||
h.state_mut().session.prefs.edit(|p| p.shortcuts.insert("layer.new.layerViaCopy".into(), "Cmd+Alt+Shift+N".into()));
|
||||
h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT | Modifiers::ALT, egui::Key::N);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layers(&h), 2);
|
||||
assert!(!dialog_open(&h));
|
||||
let doc = &h.state().session.active().unwrap().doc;
|
||||
let top = doc.layers.last().unwrap().surface().unwrap();
|
||||
assert!(!top.content_bounds().is_empty(), "Layer via Copy ran (the white background copied), not New Layer");
|
||||
}
|
||||
+115
-25
@@ -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::<egui::Id>(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 {
|
||||
@@ -580,6 +587,7 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let span_id = ui.id().with("titledrag-span");
|
||||
let (gap_l, gap_r) = ui.ctx().data(|d| d.get_temp::<(f32, f32)>(span_id)).unwrap_or((full.right(), full.right()));
|
||||
let gap = egui::Rect::from_x_y_ranges(gap_l.max(full.left())..=gap_r.min(full.right()).max(gap_l), full.y_range());
|
||||
ui.ctx().data_mut(|d| d.insert_temp(crate::titlebar::modal_drag_area_id(), gap));
|
||||
let drag = ui.interact(gap, ui.id().with("titledrag"), Sense::click_and_drag());
|
||||
if drag.drag_started() {
|
||||
ui.ctx().send_viewport_cmd(egui::ViewportCommand::StartDrag);
|
||||
@@ -1257,7 +1265,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::<u64>(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.
|
||||
@@ -1908,29 +1926,38 @@ fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let c = pos2(rect.min.x + v.center[0] * s, rect.min.y + v.center[1] * s);
|
||||
let vr = Rect::from_center_size(c, vec2(vw, vh)).intersect(frame.shrink(1.0));
|
||||
ui.painter().rect_stroke(vr, 2.0, Stroke::new(1.5, Color32::from_rgb(255, 84, 84)), StrokeKind::Middle);
|
||||
// Photoshop's one row under the preview (#4840): the zoom, typed in percent, then Zoom Out,
|
||||
// the slider and Zoom In.
|
||||
let controls = ui.vertical(|ui| {
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
label(ui, crate::i18n::tr_ctx(crate::i18n::current(), "navigator", "Zoom"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
for (lbl, z) in [("200%", 2.0), ("100%", 1.0)] {
|
||||
if widgets::pill_tab(ui, lbl, (v.zoom - z).abs() < 1e-3).clicked() {
|
||||
app.ui.views[idx].zoom = z;
|
||||
app.ui.views[idx].fit_pending = false;
|
||||
}
|
||||
}
|
||||
if widgets::pill_tab(ui, tl!("Fit"), false).clicked() {
|
||||
app.ui.views[idx].fit_pending = true;
|
||||
}
|
||||
});
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
let set = |app: &mut PhotocraftApp, zoom: f32| {
|
||||
app.ui.views[idx].zoom = crate::zoom_levels::clamp(zoom, v.doc_size);
|
||||
app.ui.views[idx].fit_pending = false;
|
||||
};
|
||||
let mut pct = v.zoom * 100.0;
|
||||
let field = widgets::compact_wrapping_value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[idx]), "%", vec2(64.0, NAV_ROW_H));
|
||||
if field.changed() {
|
||||
set(app, pct / 100.0);
|
||||
}
|
||||
let out = crate::brush_picker::named(icons::button(ui, "minus", NAV_ROW_H, false, tl!("Zoom Out")), "Zoom Out");
|
||||
if out.clicked() {
|
||||
set(app, crate::zoom_levels::step(v.zoom, -1, v.doc_size));
|
||||
}
|
||||
// The whole zoom range, and always the current zoom: a narrower slider would pull it back.
|
||||
let (lo, hi) = (crate::zoom_levels::min(v.doc_size).min(v.zoom).log2(), crate::zoom_levels::MAX.max(v.zoom).log2());
|
||||
let mut lz = v.zoom.log2();
|
||||
let slider_w = (ui.available_width() - NAV_ROW_H - 4.0).max(60.0);
|
||||
let slid = ui.allocate_ui(vec2(slider_w, NAV_ROW_H), |ui| lz.is_finite() && widgets::slider(ui, &mut lz, lo..=hi, None).changed()).inner;
|
||||
if slid {
|
||||
set(app, 2f32.powf(lz));
|
||||
}
|
||||
let zin = crate::brush_picker::named(icons::button(ui, "plus", NAV_ROW_H, false, tl!("Zoom In")), "Zoom In");
|
||||
if zin.clicked() {
|
||||
set(app, crate::zoom_levels::step(v.zoom, 1, v.doc_size));
|
||||
}
|
||||
});
|
||||
// The whole zoom range, and always the current zoom: a narrower slider would pull it back.
|
||||
let (lo, hi) = (crate::zoom_levels::min(v.doc_size).min(v.zoom).log2(), crate::zoom_levels::MAX.max(v.zoom).log2());
|
||||
let mut lz = v.zoom.log2();
|
||||
if lz.is_finite() && widgets::slider(ui, &mut lz, lo..=hi, None).changed() {
|
||||
app.ui.views[idx].zoom = crate::zoom_levels::clamp(2f32.powf(lz), v.doc_size);
|
||||
app.ui.views[idx].fit_pending = false;
|
||||
}
|
||||
});
|
||||
// From the preview's bottom, so the spacing above the controls counts too.
|
||||
let controls = Rect::from_min_max(pos2(frame.left(), frame.bottom()), pos2(frame.right(), controls.response.rect.bottom()));
|
||||
@@ -1940,6 +1967,9 @@ fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Height of the Navigator's zoom row: its field, buttons and slider.
|
||||
const NAV_ROW_H: f32 = 22.0;
|
||||
|
||||
/// The document's `w` × `h` fitted inside the Navigator's `frame` with an 8 pt inset, centred and
|
||||
/// keeping its aspect.
|
||||
fn navigator_fit(frame: Rect, w: u32, h: u32) -> Rect {
|
||||
@@ -2010,6 +2040,33 @@ mod navigator_wheel_tests {
|
||||
frame(&mut app, &ctx, below, 1.0);
|
||||
assert!((app.ui.views[0].zoom - 1.0).abs() < 1e-4, "wheel outside preview leaves zoom unchanged");
|
||||
}
|
||||
|
||||
/// #4840: under the preview, one row as in Photoshop: the zoom in percent, Zoom Out, the
|
||||
/// slider and Zoom In. The buttons step the zoom like View › Zoom In / Out.
|
||||
#[test]
|
||||
fn navigator_zoom_row_is_one_line_and_its_buttons_step_the_zoom() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
app.sync_views();
|
||||
app.ui.views[0].zoom = 1.0;
|
||||
app.ui.views[0].fit_pending = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 300.0)).build_ui_state(|ui, app: &mut PhotocraftApp| navigator(app, ui), app);
|
||||
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
|
||||
h.run_steps(4);
|
||||
let row = last_navigator_controls(&h.ctx).expect("the zoom row");
|
||||
assert!(row.height() <= NAV_ROW_H + 14.0, "one row (with the gap above it): {row:?}");
|
||||
let zoom = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.state().ui.views[0].zoom;
|
||||
h.get_by_label("Zoom In").click();
|
||||
h.run_steps(2);
|
||||
assert!((zoom(&h) - crate::zoom_levels::step(1.0, 1, [200, 100])).abs() < 1e-4, "{}", zoom(&h));
|
||||
h.get_by_label("Zoom Out").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Zoom Out").click();
|
||||
h.run_steps(2);
|
||||
assert!((zoom(&h) - crate::zoom_levels::step(1.0, -1, [200, 100])).abs() < 1e-4, "{}", zoom(&h));
|
||||
assert!(!h.state().ui.views[0].fit_pending);
|
||||
}
|
||||
}
|
||||
|
||||
fn empty(ui: &mut egui::Ui, s: &str) {
|
||||
@@ -2382,7 +2439,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!({}) };
|
||||
@@ -2837,6 +2901,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();
|
||||
@@ -4901,6 +4966,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 +4990,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 +5013,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]
|
||||
|
||||
@@ -146,7 +146,10 @@ fn dragging_on_the_first_anchor_closes_with_its_handles_in_one_step() {
|
||||
click(&mut h, [120.0, 20.0]);
|
||||
click(&mut h, [120.0, 100.0]);
|
||||
click(&mut h, [20.0, 20.0]);
|
||||
let sp = h.state().session.active().unwrap().doc.work_path.clone().unwrap().subpaths.remove(0);
|
||||
// The second path joins the Work Path as its last subpath (#4721).
|
||||
let subs = h.state().session.active().unwrap().doc.work_path.clone().unwrap().subpaths;
|
||||
assert_eq!(subs.len(), 2, "the first path stays");
|
||||
let sp = subs.last().unwrap();
|
||||
let k = &sp.knots[0];
|
||||
assert!(sp.closed && sp.knots.len() == 3);
|
||||
assert!(near([k.in_ctrl.x, k.in_ctrl.y], [0.0, 20.0]) && near([k.out_ctrl.x, k.out_ctrl.y], [40.0, 20.0]), "{k:?}");
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -162,6 +162,31 @@ pub fn consume(ctx: &egui::Context, sc: &KeyboardShortcut) -> bool {
|
||||
pub const NAV_COMMANDS: [&str; 4] = ["view.zoomIn", "view.zoomOut", "view.fitOnScreen", "view.actualPixels"];
|
||||
|
||||
/// ⌘+ / ⌘- / ⌘0 / ⌘1 (or their Edit › Keyboard Shortcuts overrides). Returns true when one ran.
|
||||
/// Layer › New › Layer's shortcut with ⌥ added (⌥⇧⌘N by default) makes the layer at once, as in
|
||||
/// Photoshop: the plain shortcut asks with the New Layer dialog first, like the menu item, and
|
||||
/// the Layers panel button's click and ⌥-click are the same pair the other way round (#4794).
|
||||
/// A command bound to that key itself keeps it.
|
||||
fn new_layer_without_dialog(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
const NEW_LAYER: &str = crate::new_layer_ui::COMMAND;
|
||||
let Some(mut sc) = effective_shortcut(app, NEW_LAYER, default_shortcut(NEW_LAYER).as_deref()).and_then(|s| parse(&s)) else {
|
||||
return false;
|
||||
};
|
||||
if sc.modifiers.alt {
|
||||
return false;
|
||||
}
|
||||
sc.modifiers.alt = true;
|
||||
let pressed =
|
||||
ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key, pressed: true, modifiers, .. } if key_matches(&sc, *key, *modifiers))));
|
||||
if !pressed || crate::shortcut_dispatch::bindings(app).iter().any(|(_, b)| *b == sc) || !consume(ctx, &sc) {
|
||||
return false;
|
||||
}
|
||||
if let Err(e) = app.run(NEW_LAYER, json!({})) {
|
||||
app.ui.status = e;
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn nav_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
for id in NAV_COMMANDS {
|
||||
let sc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).and_then(|c| parse(app.session.prefs().shortcut(id, c.3)?));
|
||||
@@ -480,6 +505,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
// Inline type editing eats text and navigation keys; ⌘-shortcuts still reach the menus.
|
||||
let editing = crate::type_tool::handle_keys(app, ctx);
|
||||
// ⌥⇧⌘N: a new layer at once, without the New Layer dialog ⇧⌘N opens (#4794).
|
||||
if new_layer_without_dialog(app, ctx) {
|
||||
return;
|
||||
}
|
||||
// Registry, UI and menu-catalogue shortcuts (see [`crate::shortcut_dispatch::bindings`]).
|
||||
if dispatch_pressed(app, ctx, focus, editing) {
|
||||
return;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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<LayerId>) -> Option<FilterDrag> {
|
||||
let (layer, filter) = ctx.data(|d| d.get_temp::<FilterDrag>(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::<FilterDrag>(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::<FilterDrag>(drag_key())) else { return };
|
||||
|
||||
@@ -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)");
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -22,6 +22,7 @@ pub const BUTTON_WIDTH: f32 = 46.0;
|
||||
/// (#1581); 8 pt is about a native resize border, and only trims the toolbar buttons' outer 3 pt.
|
||||
const EDGE: f32 = 8.0;
|
||||
const CORNER: f32 = 12.0;
|
||||
const MODAL_DRAG_AREA: &str = "titlebar-modal-drag-area";
|
||||
/// Breeze's Close button on hover and press (KDE's Breeze decoration colours).
|
||||
const BREEZE_CLOSE_HOVER: Color32 = Color32::from_rgb(0xff, 0x98, 0xa2);
|
||||
const BREEZE_CLOSE_PRESSED: Color32 = Color32::from_rgb(0x6d, 0x22, 0x29);
|
||||
@@ -50,6 +51,32 @@ pub enum CaptionFamily {
|
||||
Generic,
|
||||
}
|
||||
|
||||
/// The title bar's unused gap, saved by `panels::title_bar` for drags that begin while a modal
|
||||
/// backdrop is on top of the normal title-bar widgets.
|
||||
pub(crate) fn modal_drag_area_id() -> Id {
|
||||
Id::new(MODAL_DRAG_AREA)
|
||||
}
|
||||
|
||||
/// Restore window dragging over the title bar's empty gap after a modal has blocked the normal
|
||||
/// title-bar layer. The hit target stays limited to the same gap, so menus and caption controls
|
||||
/// remain owned by their widgets.
|
||||
pub(crate) fn modal_drag_overlay(ctx: &egui::Context) {
|
||||
let Some(area) = ctx.data(|d| d.get_temp::<Rect>(modal_drag_area_id())) else { return };
|
||||
if !area.is_positive() || egui::Popup::is_any_open(ctx) || !crate::dialogs::titlebar_drag_area_is_clear(ctx, area) {
|
||||
return;
|
||||
}
|
||||
egui::Area::new(Id::new("titlebar-modal-drag-overlay")).order(Order::Tooltip).fixed_pos(area.min).movable(false).sense(Sense::hover()).show(ctx, |ui| {
|
||||
let response = ui.allocate_rect(area, Sense::click_and_drag());
|
||||
if response.drag_started() {
|
||||
ctx.send_viewport_cmd(ViewportCommand::StartDrag);
|
||||
}
|
||||
if response.double_clicked() {
|
||||
let max = ctx.input(|i| i.viewport().maximized.unwrap_or(false));
|
||||
ctx.send_viewport_cmd(ViewportCommand::Maximized(!max));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
impl CaptionFamily {
|
||||
/// `windows`, `adwaita`, `breeze` or `generic`, in any case.
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
@@ -530,6 +557,10 @@ mod tests {
|
||||
}
|
||||
|
||||
fn frame(&mut self, events: Vec<Event>) -> egui::FullOutput {
|
||||
self.frame_with_modal(events, false)
|
||||
}
|
||||
|
||||
fn frame_with_modal(&mut self, events: Vec<Event>, modal: bool) -> egui::FullOutput {
|
||||
self.time += 0.05;
|
||||
let mut input =
|
||||
RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, 600.0))), time: Some(self.time), events, ..Default::default() };
|
||||
@@ -541,6 +572,12 @@ mod tests {
|
||||
let app = &mut self.app;
|
||||
let mut out = self.ctx.run_ui(input, |ui| {
|
||||
crate::panels::title_bar(app, ui);
|
||||
if modal {
|
||||
egui::Modal::new(Id::new("titlebar-drag-test-modal")).backdrop_color(Color32::TRANSPARENT).show(ui.ctx(), |ui| {
|
||||
ui.label("Modal dialog");
|
||||
});
|
||||
modal_drag_overlay(ui.ctx());
|
||||
}
|
||||
resize_zones(ui);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
@@ -550,10 +587,17 @@ mod tests {
|
||||
/// Frames for a pointer gesture: move to `path[0]`, press, move along `path`, release. The
|
||||
/// viewport commands the frames sent.
|
||||
fn gesture(&mut self, path: &[Pos2]) -> Vec<ViewportCommand> {
|
||||
self.gesture_with_modal(path, false)
|
||||
}
|
||||
|
||||
fn gesture_with_modal(&mut self, path: &[Pos2], modal: bool) -> Vec<ViewportCommand> {
|
||||
let mut events = vec![vec![Event::PointerMoved(path[0])], vec![button(path[0], true)]];
|
||||
events.extend(path[1..].iter().map(|p| vec![Event::PointerMoved(*p)]));
|
||||
events.push(vec![button(*path.last().unwrap_or(&path[0]), false)]);
|
||||
events.into_iter().flat_map(|e| self.frame(e).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default()).collect()
|
||||
events
|
||||
.into_iter()
|
||||
.flat_map(|e| self.frame_with_modal(e, modal).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn click(&mut self, p: Pos2) -> Vec<ViewportCommand> {
|
||||
@@ -675,6 +719,31 @@ mod tests {
|
||||
assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_bar_space_still_drags_with_a_modal_open() {
|
||||
let mut w = Win::new(1440.0);
|
||||
w.frame(vec![]);
|
||||
w.frame_with_modal(vec![], true);
|
||||
let empty = pos2(980.0, 16.0);
|
||||
let drag_area = w.ctx.data(|d| d.get_temp::<Rect>(modal_drag_area_id()));
|
||||
assert!(drag_area.is_some_and(|r| r.contains(empty)), "the test point must be in the current title-bar gap: {drag_area:?}");
|
||||
assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space");
|
||||
let cmds = w.gesture_with_modal(&[empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)], true);
|
||||
assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modal_drag_overlay_does_not_cover_a_dialog_moved_into_the_gap() {
|
||||
let mut w = Win::new(1440.0);
|
||||
w.frame(vec![]);
|
||||
w.frame_with_modal(vec![], true);
|
||||
let area = w.ctx.data(|d| d.get_temp::<Rect>(modal_drag_area_id())).unwrap_or(Rect::NOTHING);
|
||||
assert!(area.contains(pos2(980.0, 16.0)), "the probe point must be in the gap: {area:?}");
|
||||
w.ctx.data_mut(|d| d.insert_temp(Id::new("pc-dialog-rects"), vec![area]));
|
||||
let cmds = w.gesture_with_modal(&[area.center(), area.center() + vec2(12.0, 4.0)], true);
|
||||
assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}");
|
||||
}
|
||||
|
||||
/// #1581: KDE Wayland keeps the button release of an OS resize. egui then kept the edge
|
||||
/// pressed (no hover until the next click) and egui-winit never re-sent the resize cursor that
|
||||
/// the compositor had replaced: the cursor came back only on every other press.
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -463,3 +463,30 @@ fn font_menu_rows_search_both_names_and_sort_by_label() {
|
||||
assert_eq!(rows(Some(&labels), "雅黑"), [("Microsoft YaHei".to_string(), "微软雅黑".to_string())]);
|
||||
assert!(rows(Some(&labels), "nothing").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wheel_over_the_closed_font_button_steps_through_the_families() {
|
||||
let mut h = harness();
|
||||
let button = h.query_all_by_role(Role::ComboBox).next().unwrap().rect().center();
|
||||
h.hover_at(button);
|
||||
h.run();
|
||||
let wheel = |h: &mut Harness<'static, State>, y: f32| {
|
||||
h.event(egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, y), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE });
|
||||
h.run();
|
||||
};
|
||||
wheel(&mut h, -2.0);
|
||||
assert_eq!(h.state().current, "Family 02", "two notches down pick the second next family");
|
||||
assert!(popup_rect(&h).is_none(), "the list stays closed");
|
||||
wheel(&mut h, 1.0);
|
||||
assert_eq!(h.state().current, "Family 01");
|
||||
wheel(&mut h, 5.0);
|
||||
assert_eq!(h.state().current, "Family 00", "stops at the first family");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wheel_family_index_clamps_to_the_ends() {
|
||||
assert_eq!(super::wheel_family_index(0, 3, -5.0), Some(2));
|
||||
assert_eq!(super::wheel_family_index(1, 3, 1.0), Some(0));
|
||||
assert_eq!(super::wheel_family_index(1, 3, 0.0), None);
|
||||
assert_eq!(super::wheel_family_index(0, 0, -1.0), None);
|
||||
}
|
||||
@@ -1529,6 +1529,26 @@ pub(crate) fn family_picker_in(
|
||||
press.after(&response.response);
|
||||
let hovered_font = response.inner.unwrap_or_default();
|
||||
|
||||
// The wheel over the closed button steps through the families, a notch each, like Photoshop's
|
||||
// options-bar font menu: no need to open the list (#3350).
|
||||
if !egui::ComboBox::is_open(ui.ctx(), response.response.id) && ui.is_enabled() {
|
||||
let hovered = response.response.hovered();
|
||||
if hovered {
|
||||
ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO);
|
||||
}
|
||||
let notches = crate::widgets::wheel_notches_of(ui, response.response.id.with("family-wheel"), hovered, 1.0);
|
||||
let rows = font_menu_rows(families, labels, "");
|
||||
if let Some(i) = rows.iter().position(|(f, _)| *f == current)
|
||||
&& let Some(n) = wheel_family_index(i, rows.len(), notches)
|
||||
&& let Some((f, _)) = rows.get(n)
|
||||
&& **f != *current
|
||||
{
|
||||
current.clone_from(f);
|
||||
photocraft_text::served::request(f);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if salt == "type-font" {
|
||||
let hover_id = egui::Id::new("type-font-hover");
|
||||
if let Some(f) = hovered_font {
|
||||
@@ -1541,6 +1561,17 @@ pub(crate) fn family_picker_in(
|
||||
changed
|
||||
}
|
||||
|
||||
/// The row `notches` wheel notches from row `index` of `len` (down, negative, is the next one),
|
||||
/// stopping at the ends; none when the wheel did not move.
|
||||
fn wheel_family_index(index: usize, len: usize, notches: f32) -> Option<usize> {
|
||||
let steps = notches.abs().min(len as f32) as usize;
|
||||
if steps == 0 || len == 0 {
|
||||
return None;
|
||||
}
|
||||
let last = len - 1;
|
||||
Some(if notches < 0.0 { index.saturating_add(steps).min(last) } else { index.saturating_sub(steps) })
|
||||
}
|
||||
|
||||
/// Representative for the displayed properties: the edit layer, else a selected type layer.
|
||||
pub(crate) fn target(app: &PhotocraftApp) -> Option<(u64, Option<[usize; 2]>)> {
|
||||
if let Some(ed) = &app.ui.text_edit {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -389,8 +389,16 @@ fn commit_path(app: &mut PhotocraftApp, pen: &PenPath, closed: bool) {
|
||||
}
|
||||
app.run("layer.vectorMask.edit", json!({"layer": id, "path": p}))
|
||||
} else {
|
||||
// The drawn work path is selected in the Paths panel, as in Photoshop.
|
||||
app.run("path.set", json!({"name": "work", "path": path})).inspect(|_| app.ui.selected_path = Some("work".into()))
|
||||
// Photoshop adds the new subpath to the path selected in the Paths panel, which is the
|
||||
// Work Path right after drawing one, so path after path builds up there (#4721). With no
|
||||
// path selected, a new Work Path replaces the old one. The drawn path ends up selected.
|
||||
let target = app.ui.selected_path.clone().filter(|n| app.session.active().is_some_and(|st| path_exists(&st.doc, n)));
|
||||
let name = target.clone().unwrap_or_else(|| "work".into());
|
||||
let mut params = json!({"name": name, "path": path});
|
||||
if target.is_some() {
|
||||
params["op"] = json!("combine");
|
||||
}
|
||||
app.run("path.set", params).inspect(|_| app.ui.selected_path = Some(name))
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.ui.status = e;
|
||||
@@ -398,6 +406,11 @@ fn commit_path(app: &mut PhotocraftApp, pen: &PenPath, closed: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `doc` have the path the Paths panel calls `name`: "work", or a saved path's name?
|
||||
fn path_exists(doc: &Document, name: &str) -> bool {
|
||||
if name == "work" { doc.work_path.is_some() } else { doc.paths.iter().any(|p| p.name == name) }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Freeform Pen and Curvature Pen
|
||||
|
||||
@@ -2048,6 +2061,51 @@ mod tests {
|
||||
assert_eq!((wp.subpaths[0].knots[0].anchor.x, wp.subpaths[0].knots[0].anchor.y), (30.0, 25.0));
|
||||
}
|
||||
|
||||
/// #4721: a second Pen path joins the Work Path it was drawn after (still selected), as a new
|
||||
/// subpath, instead of replacing it; a saved path that is selected takes it instead; with no
|
||||
/// path selected, the new path replaces the Work Path, as in Photoshop.
|
||||
#[test]
|
||||
fn a_new_pen_path_joins_the_selected_path() {
|
||||
let mut app = app();
|
||||
app.ui.tool = Tool::Pen;
|
||||
let draw = |app: &mut PhotocraftApp, x: f64| {
|
||||
for (dx, dy) in [(0.0, 0.0), (40.0, 0.0), (40.0, 40.0)] {
|
||||
pen_down(app, x + dx, 20.0 + dy);
|
||||
pen_up(app);
|
||||
}
|
||||
pen_down(app, x + 0.5, 20.5); // close
|
||||
pen_up(app);
|
||||
};
|
||||
let work = |app: &PhotocraftApp| app.session.active().unwrap().doc.work_path.clone().unwrap();
|
||||
draw(&mut app, 20.0);
|
||||
assert_eq!(app.ui.selected_path.as_deref(), Some("work"));
|
||||
draw(&mut app, 120.0);
|
||||
let wp = work(&app);
|
||||
assert_eq!(wp.subpaths.len(), 2, "the first path stays");
|
||||
assert!(wp.subpaths.iter().all(|s| s.closed && s.knots.len() == 3));
|
||||
assert_eq!(wp.subpaths[0].knots[0].anchor.x, 20.0);
|
||||
assert_eq!(wp.subpaths[1].knots[0].anchor.x, 120.0);
|
||||
// One History step per path.
|
||||
app.session.undo();
|
||||
assert_eq!(work(&app).subpaths.len(), 1, "undo takes back only the second path");
|
||||
app.session.redo();
|
||||
// A selected saved path takes the next one.
|
||||
app.run("path.set", json!({"name": "Saved", "path": {"subpaths": [{"knots": [[2, 2], [12, 2], [12, 8]]}]}})).unwrap();
|
||||
app.ui.selected_path = Some("Saved".into());
|
||||
draw(&mut app, 220.0);
|
||||
let saved = app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Saved").unwrap().path.clone();
|
||||
assert_eq!(saved.subpaths.len(), 2);
|
||||
assert_eq!(work(&app).subpaths.len(), 2, "the Work Path is left alone");
|
||||
assert_eq!(app.ui.selected_path.as_deref(), Some("Saved"));
|
||||
// No path selected: a new Work Path replaces the old one.
|
||||
app.ui.selected_path = None;
|
||||
draw(&mut app, 320.0);
|
||||
let wp = work(&app);
|
||||
assert_eq!(wp.subpaths.len(), 1);
|
||||
assert_eq!(wp.subpaths[0].knots[0].anchor.x, 320.0);
|
||||
assert_eq!(app.ui.selected_path.as_deref(), Some("work"));
|
||||
}
|
||||
|
||||
/// #4596: the close-path pointer shows where a click would close the path, and only there:
|
||||
/// over the first anchor once the Pen has two anchors (the Curvature Pen three), not while an
|
||||
/// anchor is being dragged.
|
||||
|
||||
@@ -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::<f64>(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::<f64>(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)];
|
||||
|
||||
@@ -856,7 +856,7 @@ fn wheel_notches(ui: &Ui, resp: &Response) -> f32 {
|
||||
}
|
||||
|
||||
/// [`wheel_notches`] of widget `id` while `hovered`, a notch with Shift counting `shift_notches`.
|
||||
fn wheel_notches_of(ui: &Ui, id: egui::Id, hovered: bool, shift_notches: f32) -> f32 {
|
||||
pub(crate) fn wheel_notches_of(ui: &Ui, id: egui::Id, hovered: bool, shift_notches: f32) -> f32 {
|
||||
if !hovered {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Brush and painting parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
Painting is where Photoshop users notice differences first, so it gets its own checklist: the
|
||||
brush engine (`crates/paint/src/brush.rs`), the Brush Settings UI
|
||||
@@ -24,6 +24,7 @@ tablets against Photoshop side by side.
|
||||
| Texture (pattern, scale, brightness, contrast, mode, depth, each tip) | done | |
|
||||
| Dual Brush | done | |
|
||||
| Color Dynamics (FG/BG, hue/sat/brightness jitter, purity, per tip) | done | |
|
||||
| Hue Jitter uses a standard percentage-amount track instead of a hue spectrum | done | #3825 (Hue Jitter appearance only); rendered track checked in all 14 themes; numeric and pointer edits retain percentage units and engine command routing. |
|
||||
| Transfer (opacity/flow/wetness/mix jitter and controls) | done | |
|
||||
| Shape Dynamics and Transfer minimum fields disabled when their Control is Off, retaining their values | done | #3825 (minimum-field interaction only); `brush_sections.rs` UI regressions cover all six fields, reactivation and disabled input |
|
||||
| Brush Pose (tilt, rotation, pressure overrides) | done | |
|
||||
@@ -119,3 +120,4 @@ tablets against Photoshop side by side.
|
||||
| 2026-10-12 | minor | Five Brush Settings switch rows toggle without selecting a properties pane; Smoothing has a default-on switch and retains its settings while disabled (#4283). No brush-feel estimate changed. |
|
||||
| 2026-10-12 | minor | A shaped tip's cursor outline turns and flips with a rotated or flipped view, and follows pixel aspect correction |
|
||||
| 2026-10-13 | minor | Shape Dynamics and Transfer minimum inputs follow their Control and retain their values while disabled (#3825, partial). No brush-feel estimate changed. |
|
||||
| 2026-10-13 | minor | Hue Jitter uses the same themed amount slider as other jitter controls (#3825, partial). No brush-feel estimate changed. |
|
||||
+6
-2
@@ -1,6 +1,6 @@
|
||||
# Where PhotoCraft falls short of Photoshop
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact
|
||||
on the way to beta. This is the work list agents pick from: take the highest-ranked entry that
|
||||
@@ -47,7 +47,7 @@ what an agent can't finish alone.
|
||||
within the corpus. Smart-filter re-render matches 5/30. User reports: a PSD with text layers
|
||||
re-saved unmodified would not reopen (#2374, closed 2026-10-10), Photoshop 26.6 cannot reopen our files (#1281), "PSD not
|
||||
opening in Photoshop" (#2469), a CS2-era smart object unavailable (#2465, fixed 2026-10-12), PSB smart object
|
||||
blank (#1764), perspective placed layers flattened (#579), PSB > 4 GB fails on Windows (#375).
|
||||
blank (#1764), perspective placed layers flattened (#579, fixed by #426), PSB > 4 GB fails on Windows (#375).
|
||||
No test opens our exports in a third-party editor (FILE-216-4).
|
||||
- **Impact:** PSD is the format professionals exchange. Beta requires it to be reliable.
|
||||
- **Estimate:** 150–250 h. **Human:** opening exports in Photoshop on the owner's Mac (or a
|
||||
@@ -151,6 +151,9 @@ what an agent can't finish alone.
|
||||
- **Estimate:** 250–400 h (many overlap with other gaps; count each fix once).
|
||||
|
||||
### G4. Brush feel
|
||||
- **Progress (2026-10-13, #3825 partial):** Hue Jitter shows a standard themed
|
||||
percentage-amount track rather than a hue spectrum. Other Brush Settings layout
|
||||
and brush-behaviour gaps remain open.
|
||||
- **Progress (2026-10-13, #3825 partial):** Shape Dynamics' Minimum Diameter / Minimum
|
||||
Roundness and Transfer's four Minimum rows disable editing when their Control is Off,
|
||||
retaining the configured values. The other layout and control gaps in #3825 remain open.
|
||||
@@ -255,6 +258,7 @@ what an agent can't finish alone.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-13 | minor | G4: Hue Jitter amount-track appearance (#3825, partial); no readiness percentage or estimate changed |
|
||||
| 2026-10-13 | minor | G4: minimum inputs in Shape Dynamics and Transfer follow their Control (#3825, partial); no readiness percentage or estimate changed |
|
||||
| 2026-10-12 | minor | G5: Free Transform options bar H/V skew fields done |
|
||||
| 2026-10-12 | minor | G11: `.atn` import maps 112 events (Select and Mask, Spatter, Ripple, Crystallize, Pattern Fill, mask targeting, Step Backward, points, Bitmap) |
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
|
||||
| Area | Done | Partial | Missing | Key numbers |
|
||||
|---|---:|---:|---:|---|
|
||||
| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) |
|
||||
| [File compatibility](#file-compatibility) | 6 | 13 | 8 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 |
|
||||
| [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 |
|
||||
| [Tools](#tools) | 28 | 14 | 1 | |
|
||||
| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 156 (target 0) |
|
||||
| [Type](#type) | 4 | 3 | 2 | |
|
||||
@@ -103,7 +103,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
|
||||
| FILE-215-3 | Filter mask can be painted directly, with undo | missing | [#215](https://github.com/storytold/photocraft/issues/215) | smart_cmds.rs:382 mask only from the selection |
|
||||
| FILE-215-4 | Adjustments (Hue/Sat + Colorize, Curves, Levels, Shadows/Highlights) apply as Smart Filters | done | [#215](https://github.com/storytold/photocraft/issues/215) | Image › Adjustments on a smart object records image.adjustments.<kind> as a smart filter (adjust_cmds.rs adjust_as_smart_filter; the selection becomes the filter mask), re-rendered from the source by adjust_as_filter and re-editable with layer.smartFilter.setParams; PSD maps Levels/Curves/Shadows-Highlights both ways (smart_map.rs). Opening the editor from the smart-filter row is FILE-215-5's row work |
|
||||
| FILE-215-5 | Smart Filter rows: collapse, mask thumb, blend icon, drag reorder, context menu, live preview | partial | [#215](https://github.com/storytold/photocraft/issues/215) | smart_ui.rs:31 rows + visibility + editor; no collapse, drag or context menu |
|
||||
| FILE-215-6 | Smart Object corner skew and perspective (quad or homography transform) | missing | [#215](https://github.com/storytold/photocraft/issues/215) | doc lib.rs:312 SmartObject.transform is an Affine |
|
||||
| FILE-215-6 | Smart Object corner skew and perspective (quad or homography transform) | done | [#215](https://github.com/storytold/photocraft/issues/215) | #426: SmartObject.perspective holds the projective map (transform keeps its affine approximation); Distort / Perspective on a smart object set it (transform_cmds.rs, smart_cmds::set_placement), it re-renders from the source through the homography, Warp composes with it, and the PSD placement reads and writes nonAffineTransform / Trnf (io/blocks.rs placed_projective, smart_map.rs); tests distort_survives_edit_contents, warp_on_a_distorted_smart_object_follows_the_corners, placement survives the save |
|
||||
| FILE-215-7 | Layered TIFF read and write (tag 37724), honouring the ask-before-saving pref | partial | [#215](https://github.com/storytold/photocraft/issues/215) | psd tiff.rs (ImageSourceData, both byte orders), io tiff_layers.rs, ui tiff_options_ui.rs (Discard Layers and Save a Copy); extra alpha channels and a Quick Mask are not written (the TIFF codec holds one transparency sample) |
|
||||
| FILE-215-8 | Large and BigTIFF import with banded decode across all IFDs | done | [#215](https://github.com/storytold/photocraft/issues/215) | codecs tiff_ifd.rs (bounds-checked IFD chain + SubIFD walk, classic and BigTIFF, cycle-safe; tiff_info / decode_tiff_page), tiff.rs banded parallel strip/tile decode, planar 1 and 2, BigTIFF write (tiff_bigtiff or > 4 GiB); io import_tiff_page; 30 MP RGB8 Deflate 345 -> 32 ms; no page picker in the UI yet |
|
||||
| FILE-215-9 | SVG opens and places as shape layers or a vector Smart Object | done | [#215](https://github.com/storytold/photocraft/issues/215) | io svg.rs: paths, groups, text outlines as shape layers (gradients approximated; clip/mask/filter/pattern/image subtrees rasterised); smart_cmds.rs renders an SVG source at its placement scale |
|
||||
|
||||
+1
-1
@@ -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.
|
||||
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ Dispatch order matches `dialogs::show` in `dialogs.rs` (check earlier rows befor
|
||||
| `__stroke` | `stroke_ui.rs` | Edit › Stroke… |
|
||||
| `__createShape` | `shape_dialog.rs` | Click-with-shape-tool creation (rectangle, ellipse, …) |
|
||||
| `__deleteLayer` | `delete_layer_prompt.rs` | Layers panel trash confirmation |
|
||||
| `__newLayer` | `new_layer_ui.rs` | Layer › New › Layer… (⇧⌘N) |
|
||||
| `__newLayer` | `new_layer_ui.rs` | Layer › New › Layer… (⇧⌘N; ⌥⇧⌘N makes the layer without it) |
|
||||
| `__rasterize` | `rasterize_prompt.rs` | Rasterize-before-paint prompt |
|
||||
| `__resetAllTools` | `tool_reset.rs` | Reset All Tools confirmation |
|
||||
| `__cropPresetNew` / `__cropPresetDelete` | `crop_presets.rs` | New / delete crop preset |
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
# UI parity: tools, handles, modifiers and feel
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the
|
||||
handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,
|
||||
@@ -78,7 +78,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
|
||||
| Locked layer refused before the drag | missing | fails only at commit (#2585) |
|
||||
| Transform a copy (⌥⌘T), step and repeat (⌥⇧⌘T) | done | 2026-10-07 |
|
||||
| Transform a targeted alpha channel | missing | BUG-207-4 |
|
||||
| Smart object perspective (non-affine) | missing | FILE-215-6, #579 |
|
||||
| Smart object perspective (non-affine) | done | FILE-215-6; #579 fixed by #426: Distort / Perspective keep a projective placement, re-rendered from the source, read and written as the PSD `nonAffineTransform` |
|
||||
| Type-layer transform while editing (⌘ held), no ⌘-corner distort on type | done | `ui-design.md` |
|
||||
| Puppet Warp mesh follows the outline | missing | block grid (TOOL-214-6) |
|
||||
|
||||
@@ -216,6 +216,7 @@ Paragraph; the rest open as in-app floating windows.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-13 | minor | Smart object perspective (non-affine) corrected to done: #426 landed four-corner placements with PSD round trip; scorecard FILE-215-6 flipped |
|
||||
| 2026-10-10 | major | First version, from a source audit against Photoshop 2026 27.11.0's shortcuts file and the open issues |
|
||||
| 2026-10-10 | minor | Fixed Crop live resize snapping feedback and outdated-camera rendering, applied ratios immediately to centred inscribed previews, and removed two-point options-bar overflow; added pointer, rendering, dropdown/Enter, Swap/X and scrolling regressions |
|
||||
| 2026-10-11 | minor | Flick panning done: releasing a moving Hand drag (tool, Space or middle button) glides and decays, gated by Enable Flick Panning |
|
||||
|
||||
@@ -43,9 +43,9 @@ note = "smart_ui.rs:31 rows + visibility + editor; no collapse, drag or context
|
||||
[[item]]
|
||||
id = "FILE-215-6"
|
||||
target = "Smart Object corner skew and perspective (quad or homography transform)"
|
||||
status = "missing"
|
||||
status = "done"
|
||||
issue = 215
|
||||
note = "doc lib.rs:312 SmartObject.transform is an Affine"
|
||||
note = "#426: SmartObject.perspective holds the projective map (transform keeps its affine approximation); Distort / Perspective on a smart object set it (transform_cmds.rs, smart_cmds::set_placement), it re-renders from the source through the homography, Warp composes with it, and the PSD placement reads and writes nonAffineTransform / Trnf (io/blocks.rs placed_projective, smart_map.rs); tests distort_survives_edit_contents, warp_on_a_distorted_smart_object_follows_the_corners, placement survives the save"
|
||||
|
||||
[[item]]
|
||||
id = "FILE-215-7"
|
||||
|
||||
Reference in new issue
Block a user