mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge pull request #16529 from davidmann4/batch-19-prs-restored
Batch: 19 PRs with fix-ups (#12219, #11835, #14491, #15187, #8222, #15796, #15085, #15308, #15311, #15435, #14650, #15921, #15515, #15632, #15948, #15653, #14493, #14492, #14748)
This commit is contained in:
91 files changed
+5109
-210
No files matched your search
@@ -92,6 +92,15 @@ success-output = "immediate"
|
||||
# All cases and the 60-second warning remain unchanged.
|
||||
threads-required = 2
|
||||
|
||||
# The slowest UI GPU tests start together (priority below) and redraw the whole app per frame on
|
||||
# the Windows software GPU. Four at once starve one frame past egui_kittest's 10-second device
|
||||
# poll (`PollError: ... Wait timed out`, live_stroke_canvas part_0, twice in a row in #16529).
|
||||
# Two slots each keep at most two of them on the adapter at a time; no case or timeout changes.
|
||||
[[profile.ci.overrides]]
|
||||
platform = 'cfg(target_os = "windows")'
|
||||
filter = 'package(photocraft-ui-egui) & test(/gpu_tests::(live_stroke_canvas::the_canvas_shows_the_committed_stroke_part_|checker_canvas::pixel_grid_is_solid_and_visible_|full_res_preview::)/)'
|
||||
threads-required = 2
|
||||
|
||||
# Slowest tests start first. nextest starts higher-priority tests first, so a long test no longer
|
||||
# begins at the end of the run and extends the job. Every test that took over 60 s on the Windows
|
||||
# runner in the cold run of #15474 (unit and integration legs); the same tests are the slowest on
|
||||
|
||||
Generated
+1
@@ -6935,6 +6935,7 @@ dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-print",
|
||||
"craft-psd",
|
||||
"craft-xml",
|
||||
"eframe",
|
||||
"egui",
|
||||
"egui_extras",
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Seeds for failure cases proptest has generated in the past. It is
|
||||
# automatically read and these particular cases re-run before any
|
||||
# novel cases are generated.
|
||||
#
|
||||
# It is recommended to check this file in to source control so that
|
||||
# everyone who runs the test benefits from these saved cases.
|
||||
cc 9cd32fd3b0d418f70a3535174d06eccab73fdd2345cf51e50b53c9f2e006043e # shrinks to s = Spec { w: 2, h: 2, layers: [Group { children: [Pixels { kind: Solid, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.54360455, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }, Pixels { kind: Adjust(Curves { channel: 2, points: [(0.4490113, 1.0), (1.0, 0.0)] }), blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.6871668, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] }
|
||||
@@ -17,8 +17,8 @@ mod tone;
|
||||
#[cfg(test)]
|
||||
use channels::lab_denorm;
|
||||
pub use channels::{
|
||||
LAB_NEUTRAL, LabOp, apply_cmy, cmy_adjustment, cmyk_channel_adjustment, ink_brightness_contrast_lut, ink_luma, ink_through, lab_channel_adjustment,
|
||||
lab_stored_op, stored_channel_adjustment, stored_channels, threshold_white,
|
||||
LAB_NEUTRAL, LabOp, apply_cmy, cmy_adjustment, cmyk_channel_adjustment, cmyk_mixer, ink_brightness_contrast_lut, ink_luma, ink_through,
|
||||
lab_channel_adjustment, lab_stored_op, mix_inks, stored_channel_adjustment, stored_channels, threshold_white,
|
||||
};
|
||||
use channels::{apply_lab, gray_from_srgb_lightness, legacy_brightness_contrast, legacy_brightness_contrast_hdr};
|
||||
use color::gradient;
|
||||
@@ -32,7 +32,8 @@ use tone::LUT_SIZE;
|
||||
pub(crate) use tone::apply_tone;
|
||||
pub use tone::{
|
||||
TONE_SLOPE_SPAN, contour_curve_lut, curve_lut, curve_lut_mode, curve_map_lut, curve_samples, float_tone_extrapolates, float_tone_identity, levels,
|
||||
levels_float, levels_gamma, levels_q, modern_brightness, modern_contrast, modern_lut, posterize, posterize_in, tone_luts, tone_luts_depth, tone_luts_q,
|
||||
levels_float, levels_gamma, levels_q, modern_brightness, modern_contrast, modern_lut, posterize, posterize_in, tone_luts, tone_luts_depth,
|
||||
tone_luts_depth_in, tone_luts_q,
|
||||
};
|
||||
use tone::{lut, map_rgb};
|
||||
|
||||
@@ -200,7 +201,25 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept
|
||||
let hi = if depth == Some(SampleType::F32) { f32::INFINITY } else { 1.0 };
|
||||
map_rgb(buf, |c| vibrance_px(c, v, s, transfer, hi))
|
||||
}
|
||||
Adjustment::ChannelMixer { matrix, monochrome } if depth == Some(SampleType::F32) => {
|
||||
Adjustment::ChannelMixer { cmyk: Some(rows), monochrome, .. } => {
|
||||
// A CMYK mixer outside a CMYK document: on the screen colour's separation.
|
||||
use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk};
|
||||
// In a 32-bit document the change is added as a difference of two round trips, as
|
||||
// [`tone::tone_in_space`] does, so samples past 0..1 the separation clips keep their
|
||||
// magnitude (an identity mixer leaves an HDR highlight as it is).
|
||||
let float = depth == Some(SampleType::F32);
|
||||
map_rgb(buf, |c| {
|
||||
let ink = rgb_to_cmyk(c);
|
||||
let mut mixed = ink;
|
||||
mix_inks(rows, *monochrome, &mut mixed);
|
||||
if !float {
|
||||
return cmyk_to_rgb(mixed);
|
||||
}
|
||||
let (before, after) = (cmyk_to_rgb(ink), cmyk_to_rgb(mixed));
|
||||
std::array::from_fn(|i| c[i] + after[i] - before[i])
|
||||
})
|
||||
}
|
||||
Adjustment::ChannelMixer { matrix, monochrome, .. } if depth == Some(SampleType::F32) => {
|
||||
// 32-bit: each source percentage is cut to 1/1024 (toward zero), the constant counts
|
||||
// 255/512 of its value, and nothing clips (photoshop corpus rgb32 channel-mixer.psd:
|
||||
// pure red, green, blue, black and white all exact).
|
||||
@@ -211,7 +230,7 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept
|
||||
if *monochrome { [mix(&m[0]); 3] } else { [mix(&m[0]), mix(&m[1]), mix(&m[2])] }
|
||||
})
|
||||
}
|
||||
Adjustment::ChannelMixer { matrix, monochrome } => map_rgb(buf, |c| {
|
||||
Adjustment::ChannelMixer { matrix, monochrome, .. } => map_rgb(buf, |c| {
|
||||
let mix = |row: &[f32; 4]| (row[0] * c[0] + row[1] * c[1] + row[2] * c[2] + row[3]).clamp(0.0, 1.0);
|
||||
if *monochrome { [mix(&matrix[0]); 3] } else { [mix(&matrix[0]), mix(&matrix[1]), mix(&matrix[2])] }
|
||||
}),
|
||||
@@ -408,6 +427,8 @@ mod lookup_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod curves_channel_composite_tests;
|
||||
#[cfg(test)]
|
||||
mod gradient_map_grayscale_tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -71,12 +71,40 @@ pub fn lab_channel_adjustment(adj: &Adjustment) -> bool {
|
||||
/// Whether a CMYK document evaluates `adj` on its inks rather than on the screen colour: Invert
|
||||
/// and Posterize (each ink, black included, so paper inverts to 400% ink), Threshold (paper or
|
||||
/// 100% black ink alone) and Brightness/Contrast (each ink's stored value, 1 - ink, through the
|
||||
/// tone curve; see [`ink_through`]). Photoshop corpus cmyk8 and cmyk16 invert, posterize-4,
|
||||
/// tone curve; see [`ink_through`]), and a Channel Mixer with CMYK outputs ([`mix_inks`]).
|
||||
/// Photoshop corpus cmyk8 and cmyk16 invert, posterize-4,
|
||||
/// threshold-128 and brightness-contrast(-legacy) follow these rules on the files' own inks on
|
||||
/// every pixel; here the inks are the screen colour separated through the document's CMYK
|
||||
/// profile, so neutrals carry the black that profile generates rather than the file's.
|
||||
pub fn cmyk_channel_adjustment(adj: &Adjustment) -> bool {
|
||||
stored_channel_adjustment(adj) || cmy_adjustment(adj) || matches!(adj, Adjustment::BrightnessContrast { .. })
|
||||
stored_channel_adjustment(adj) || cmy_adjustment(adj) || cmyk_mixer(adj) || matches!(adj, Adjustment::BrightnessContrast { .. })
|
||||
}
|
||||
|
||||
/// Whether `adj` is a Channel Mixer with CMYK outputs ([`mix_inks`]).
|
||||
pub fn cmyk_mixer(adj: &Adjustment) -> bool {
|
||||
matches!(adj, Adjustment::ChannelMixer { cmyk: Some(_), .. })
|
||||
}
|
||||
|
||||
/// A CMYK Channel Mixer on one pixel's inks (C, M, Y, K; 0 none): each output ink is its row's
|
||||
/// mix of the four ink amounts plus the constant, clipped to 0..1, so a positive constant adds
|
||||
/// ink. Photoshop corpus cmyk8 and cmyk16 channel-mixer.psd follow this on every pixel (within
|
||||
/// 0.8 and 0.4 of a level of 255), black output included: its all-zero record leaves no black
|
||||
/// ink. Mixing the stored values (1 - ink) instead misses by up to 255 levels there. With
|
||||
/// `monochrome` the first row's mix goes to the black ink alone and cyan, magenta and yellow are
|
||||
/// cleared (no Photoshop sample of a monochrome CMYK mixer yet).
|
||||
pub fn mix_inks(rows: &[[f32; 5]; 4], monochrome: bool, ink: &mut [f32]) {
|
||||
let inks: [f32; 4] = std::array::from_fn(|i| {
|
||||
let v = ink.get(i).copied().unwrap_or(0.0);
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
|
||||
});
|
||||
let mix = |r: &[f32; 5]| {
|
||||
let v = r[0] * inks[0] + r[1] * inks[1] + r[2] * inks[2] + r[3] * inks[3] + r[4];
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
|
||||
};
|
||||
let out: [f32; 4] = if monochrome { [0.0, 0.0, 0.0, mix(&rows[0])] } else { std::array::from_fn(|j| mix(&rows[j])) };
|
||||
for (v, o) in ink.iter_mut().zip(out) {
|
||||
*v = o;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a CMYK document evaluates `adj` on C, M and Y as the complement of an RGB colour,
|
||||
@@ -125,7 +153,7 @@ pub fn stored_channel_adjustment(adj: &Adjustment) -> bool {
|
||||
matches!(adj, Adjustment::Invert | Adjustment::Posterize { .. } | Adjustment::Threshold { .. })
|
||||
}
|
||||
|
||||
/// Invert, Posterize or Threshold on one pixel's own channels in a Lab or CMYK document of
|
||||
/// Invert, Posterize or Threshold (or, in CMYK, a CMYK Channel Mixer: [`mix_inks`]) on one pixel's own channels in a Lab or CMYK document of
|
||||
/// `depth` (`None`: unknown, treated as 8-bit): `ch` holds L, a, b normalised as [`lab_norm`]
|
||||
/// gives them, or the C, M, Y, K inks (0: none). Lab Invert turns 8-bit bytes `v` into `255 - v`
|
||||
/// (a becomes -1 - a) and mirrors a and b around neutral at 16 bits (photoshop corpus lab16
|
||||
@@ -156,6 +184,7 @@ pub fn stored_channels(adj: &Adjustment, mode: ColorMode, depth: Option<SampleTy
|
||||
};
|
||||
ch.iter_mut().zip(out).for_each(|(v, o)| *v = o);
|
||||
}
|
||||
Adjustment::ChannelMixer { cmyk: Some(rows), monochrome, .. } if mode == ColorMode::Cmyk => mix_inks(rows, *monochrome, ch),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
//! #14446: in an 8-bit document a Curves channel curve lands on a whole level before the
|
||||
//! composite (master) curve is applied to it, as Levels' steps do (see [`super::levels_q`]).
|
||||
//! The values below are the reference application the issue measures, Red `0,0 128,64 255,255`
|
||||
//! with composite `0,0 128,200 255,255`. 16-bit, float, CMYK and Lab curves are marked *not
|
||||
//! measured* there and keep today's continuous chain.
|
||||
|
||||
use super::*;
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
/// One Photoshop level as a sample.
|
||||
fn level(v: u32) -> f32 {
|
||||
v as f32 / 255.0
|
||||
}
|
||||
|
||||
/// Curve points given in Photoshop's 0..255 units.
|
||||
fn pts(p: &[(u32, u32)]) -> Vec<CurvePoint> {
|
||||
p.iter().map(|&(i, o)| CurvePoint { input: level(i), output: level(o) }).collect()
|
||||
}
|
||||
|
||||
/// The measured pair: a red channel curve that halves the midtones and a composite curve that
|
||||
/// lifts them.
|
||||
const RED: &[(u32, u32)] = &[(0, 0), (128, 64), (255, 255)];
|
||||
const COMPOSITE: &[(u32, u32)] = &[(0, 0), (128, 200), (255, 255)];
|
||||
const STRAIGHT: &[(u32, u32)] = &[(0, 0), (255, 255)];
|
||||
|
||||
fn measured() -> Adjustment {
|
||||
Adjustment::Curves {
|
||||
master: pts(COMPOSITE),
|
||||
per_channel: [pts(RED), pts(STRAIGHT), pts(STRAIGHT)],
|
||||
space: ToneSpace::Rgb,
|
||||
black: Vec::new(),
|
||||
pencil: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One gray through the compositor's real adjustment path in an 8-bit document, as whole levels.
|
||||
fn gray8(adj: &Adjustment, g: u32) -> [u32; 3] {
|
||||
let mut b = Buffer::filled(Rect::new(0, 0, 1, 1), [level(g), level(g), level(g), 1.0]);
|
||||
apply_depth(adj, &mut b, Transfer::Srgb, Some(SampleType::U8));
|
||||
[0, 1, 2].map(|i| (b.px[0][i] * 255.0 + 0.5).floor() as u32)
|
||||
}
|
||||
|
||||
/// Round half up to a whole level (both for the reference and for the rendered result).
|
||||
fn whole(v: f32) -> f32 {
|
||||
(v * 255.0 + 0.5).floor()
|
||||
}
|
||||
|
||||
/// The measured grays: 128 -> 64 -> 114, so the channel curve's output is a whole level on its
|
||||
/// way to the composite curve.
|
||||
#[test]
|
||||
fn measured_grays_round_the_channel_before_the_composite() {
|
||||
let adj = measured();
|
||||
for (g, want) in [(64u32, [37, 114, 114]), (128, [114, 200, 200]), (192, [217, 241, 241])] {
|
||||
assert_eq!(gray8(&adj, g), want, "gray {g}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every level of an 8-bit ramp: the red output equals the composite curve applied to the channel
|
||||
/// curve rounded to a whole level, each curve the natural spline through its points.
|
||||
#[test]
|
||||
fn the_eight_bit_ramp_is_the_composite_of_the_rounded_channel_curve() {
|
||||
let adj = measured();
|
||||
let red = curve_samples::<256>(&pts(RED));
|
||||
let master = curve_samples::<256>(&pts(COMPOSITE));
|
||||
let mut b = Buffer { rect: Rect::new(0, 0, 256, 1), px: (0..256).map(|x| [level(x), level(x), level(x), 1.0]).collect() };
|
||||
apply_depth(&adj, &mut b, Transfer::Srgb, Some(SampleType::U8));
|
||||
let bad: Vec<String> = (0..256)
|
||||
.filter_map(|x| {
|
||||
let (got, want) = (whole(b.px[x][0]), whole(master[whole(red[x]) as usize]));
|
||||
(got != want).then(|| format!("{x}: {got} vs {want}"))
|
||||
})
|
||||
.collect();
|
||||
assert!(bad.is_empty(), "{} of 256 red levels differ from composite(round(red(x))): {bad:?}", bad.len());
|
||||
}
|
||||
|
||||
/// Not measured, so unchanged: at 16 bits, in float documents and without a depth the channel
|
||||
/// LUT still goes into the composite LUT unrounded (an 8-bit level is 1/255, far above the
|
||||
/// tolerance below).
|
||||
#[test]
|
||||
fn other_depths_keep_the_continuous_chain() {
|
||||
let adj = measured();
|
||||
let master_lut = curve_lut_mode(&pts(COMPOSITE), false);
|
||||
let continuous = |points: &[CurvePoint]| -> Vec<f32> { curve_lut_mode(points, false).iter().map(|&v| lut(&master_lut, v)).collect() };
|
||||
let rows = [continuous(&pts(RED)), continuous(&pts(STRAIGHT)), continuous(&pts(STRAIGHT)), continuous(&[])];
|
||||
for depth in [None, Some(SampleType::U16), Some(SampleType::F32)] {
|
||||
let built = tone_luts_depth(&adj, depth);
|
||||
for ch in 0..4 {
|
||||
let drift = built[ch].iter().zip(&rows[ch]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
|
||||
assert!(drift < 1e-6, "{depth:?} channel {ch}: {drift} off the continuous chain, a whole level is {}", 1.0 / 255.0);
|
||||
}
|
||||
}
|
||||
let eight = tone_luts_depth(&adj, Some(SampleType::U8));
|
||||
let stepped = eight[0].iter().zip(&rows[0]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
|
||||
assert!(stepped > 1e-4, "the 8-bit row must be the rounded chain, and is {stepped} off the unrounded one");
|
||||
}
|
||||
|
||||
/// Also not measured: CMYK and Lab curves keep today's chain at every depth.
|
||||
#[test]
|
||||
fn cmyk_and_lab_curves_keep_the_continuous_chain() {
|
||||
let straight = pts(STRAIGHT);
|
||||
let black = pts(RED);
|
||||
for space in [ToneSpace::Cmyk, ToneSpace::Lab] {
|
||||
let mut adj = measured();
|
||||
if let Adjustment::Curves { space: s, black: b, .. } = &mut adj {
|
||||
*s = space;
|
||||
*b = black.clone();
|
||||
}
|
||||
let master_lut = if space == ToneSpace::Lab { curve_lut(&[]) } else { curve_lut_mode(&pts(COMPOSITE), false) };
|
||||
let continuous = |points: &[CurvePoint]| -> Vec<f32> { curve_lut_mode(points, false).iter().map(|&v| lut(&master_lut, v)).collect() };
|
||||
// The fourth row is the black ink only in a CMYK curve; otherwise it is the unused identity.
|
||||
let ink: &[CurvePoint] = if space == ToneSpace::Cmyk { &black } else { &[] };
|
||||
let want = [continuous(&pts(RED)), continuous(&straight), continuous(&straight), continuous(ink)];
|
||||
for depth in [Some(SampleType::U8), Some(SampleType::U16), None] {
|
||||
let built = tone_luts_depth(&adj, depth);
|
||||
for ch in 0..4 {
|
||||
let drift = built[ch].iter().zip(&want[ch]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
|
||||
assert!(drift < 1e-6, "{space:?} {depth:?} channel {ch}: {drift} off the continuous chain");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Listing a curve's points in another order describes the same curve, and the rounding follows
|
||||
/// the curve, not the order its points were typed in.
|
||||
#[test]
|
||||
fn the_point_order_of_each_curve_does_not_change_the_result() {
|
||||
let mut adj = measured();
|
||||
if let Adjustment::Curves { master, per_channel, .. } = &mut adj {
|
||||
master.reverse();
|
||||
for c in per_channel.iter_mut() {
|
||||
c.reverse();
|
||||
}
|
||||
}
|
||||
for g in [64u32, 128, 192] {
|
||||
assert_eq!(gray8(&adj, g), gray8(&measured(), g), "gray {g} with the points listed in reverse");
|
||||
}
|
||||
}
|
||||
|
||||
/// A pencil channel step between levels 128 and 129 leaves level 128 at exactly zero on its way to
|
||||
/// the composite curve: read between two table entries it came out as a fraction that rounded to
|
||||
/// level 4, where the composite's own step turned it into 255.
|
||||
#[test]
|
||||
fn a_pencil_channel_step_reaches_the_composite_at_its_exact_level() {
|
||||
let adj = Adjustment::Curves {
|
||||
master: pts(&[(0, 0), (3, 0), (4, 255), (5, 0), (255, 0)]),
|
||||
per_channel: [pts(&[(0, 0), (128, 0), (129, 255), (255, 255)]), pts(STRAIGHT), pts(STRAIGHT)],
|
||||
space: ToneSpace::Rgb,
|
||||
black: Vec::new(),
|
||||
pencil: true,
|
||||
};
|
||||
assert_eq!(gray8(&adj, 128)[0], 0);
|
||||
assert_eq!(gray8(&adj, 4)[0], 0, "level 4 maps to 0 through the channel, then 0 through the composite");
|
||||
}
|
||||
@@ -38,6 +38,12 @@ pub fn tone_luts(adj: &Adjustment) -> [Vec<f32>; 4] {
|
||||
/// [`tone_luts`] for samples with `quantum` steps per unit (Levels works on whole levels; see
|
||||
/// [`levels_q`]).
|
||||
pub fn tone_luts_q(adj: &Adjustment, quantum: Option<f32>) -> [Vec<f32>; 4] {
|
||||
tone_luts_qc(adj, quantum, true)
|
||||
}
|
||||
|
||||
/// [`tone_luts_q`]; `curve_levels` false leaves an 8-bit RGB Curves channel's output where the
|
||||
/// spline put it instead of on a whole level (see [`tone_luts_depth_in`]).
|
||||
fn tone_luts_qc(adj: &Adjustment, quantum: Option<f32>, curve_levels: bool) -> [Vec<f32>; 4] {
|
||||
let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32;
|
||||
match adj {
|
||||
Adjustment::Levels { master, per_channel, space, black } => {
|
||||
@@ -48,8 +54,37 @@ pub fn tone_luts_q(adj: &Adjustment, quantum: Option<f32>) -> [Vec<f32>; 4] {
|
||||
}
|
||||
Adjustment::Curves { master, per_channel, space, black, pencil } => {
|
||||
let m = if *space == ToneSpace::Lab { curve_lut(&[]) } else { curve_lut_mode(master, *pencil) };
|
||||
let row = |c: &[CurvePoint]| curve_lut_mode(c, *pencil).iter().map(|&v| lut(&m, v)).collect();
|
||||
[row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &[] })]
|
||||
// In an 8-bit document the channel curve's output sits on a whole level before the
|
||||
// composite curve is applied to it, as every Levels step is above (#14446, measured:
|
||||
// Red 0,0 128,64 255,255 with composite 0,0 128,200 255,255 gives gray 192 as 217,
|
||||
// 128 as 114 and 64 as 37). The channel's input is snapped to its level as well, so
|
||||
// the row is flat across a level and the table cannot blend two levels' results at a
|
||||
// document sample - the way [`levels_q`] is exact at every level. 16-bit and float
|
||||
// documents were not measured, nor CMYK and Lab curves, so only the 8-bit quantum.
|
||||
let level = (curve_levels && *space == ToneSpace::Rgb && quantum == Some(EIGHT_BIT_LEVELS)).then_some(EIGHT_BIT_LEVELS);
|
||||
// Both curves are evaluated at the 256 exact levels, not read between two entries of
|
||||
// the 4096-entry table: a pencil step between levels 128 and 129 would otherwise give
|
||||
// level 128 a small fraction that rounds up to level 4 and wakes a composite step there.
|
||||
let master_levels = if *space == ToneSpace::Lab { curve_samples::<LEVELS>(&[]) } else { curve_samples_mode::<LEVELS>(master, *pencil) };
|
||||
let row = |c: &[CurvePoint], level: Option<f32>| match level {
|
||||
Some(q) => {
|
||||
let channel = curve_samples_mode::<LEVELS>(c, *pencil);
|
||||
let index = |v: f32| (whole_levels(v, Some(q)) * q).round().clamp(0.0, q) as usize;
|
||||
(0..LUT_SIZE)
|
||||
.map(|k| {
|
||||
let ch = channel.get(index(x(k))).copied().unwrap_or(0.0);
|
||||
master_levels.get(index(ch)).copied().unwrap_or(0.0)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
None => curve_lut_mode(c, *pencil).iter().map(|&v| lut(&m, v)).collect(),
|
||||
};
|
||||
[
|
||||
row(&per_channel[0], level),
|
||||
row(&per_channel[1], level),
|
||||
row(&per_channel[2], level),
|
||||
row(if *space == ToneSpace::Cmyk { black } else { &[] }, None),
|
||||
]
|
||||
}
|
||||
_ => std::array::from_fn(|_| (0..LUT_SIZE).map(x).collect()),
|
||||
}
|
||||
@@ -59,13 +94,34 @@ pub fn tone_luts_q(adj: &Adjustment, quantum: Option<f32>) -> [Vec<f32>; 4] {
|
||||
/// [`levels_float`], sampled on 0..1 and kept in 0..1 for LUT consumers. Float RGB rendering
|
||||
/// evaluates the formula directly instead, so samples and results outside that domain survive.
|
||||
pub fn tone_luts_depth(adj: &Adjustment, depth: Option<SampleType>) -> [Vec<f32>; 4] {
|
||||
tone_luts_depth_in(adj, depth, true)
|
||||
}
|
||||
|
||||
/// [`tone_luts_depth`]; `curve_levels` false for the RGB Curves that stand in for a CMYK
|
||||
/// document's ink curves on the split route (`cmyk_split`): the exact ink path doesn't put CMYK
|
||||
/// curves on whole levels, so neither may their stand-ins, or the two routes part by a level.
|
||||
pub fn tone_luts_depth_in(adj: &Adjustment, depth: Option<SampleType>, curve_levels: bool) -> [Vec<f32>; 4] {
|
||||
match (adj, depth) {
|
||||
(Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. }, Some(SampleType::F32)) => {
|
||||
let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32;
|
||||
let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_float(master, levels_float(c, x(k))).clamp(0.0, 1.0)).collect();
|
||||
[row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), (0..LUT_SIZE).map(x).collect()]
|
||||
}
|
||||
_ => tone_luts_q(adj, depth.and_then(crate::adjustment_quantum)),
|
||||
_ => tone_luts_qc(adj, depth.and_then(crate::adjustment_quantum), curve_levels),
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's quantum in whole 8-bit levels: [`crate::adjustment_quantum`]'s 8-bit step (see
|
||||
/// [`levels_q`], which rounds each of its three steps to these).
|
||||
const EIGHT_BIT_LEVELS: f32 = 255.0;
|
||||
|
||||
/// [`levels_q`]'s round-half-up to a whole level, for a Curves channel's output; `None` (any other
|
||||
/// depth) leaves the sample where the spline put it.
|
||||
#[inline]
|
||||
fn whole_levels(v: f32, quantum: Option<f32>) -> f32 {
|
||||
match quantum {
|
||||
Some(q) => (v * q + 0.5).floor() / q,
|
||||
None => v,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,13 +429,26 @@ pub fn curve_lut_mode(points: &[CurvePoint], pencil: bool) -> Vec<f32> {
|
||||
/// A pencil-drawn Curves map (see [`photocraft_doc::adjust::curve_map`]): straight segments
|
||||
/// between its entries, constant outside the first/last, clamped to 0..=1, sampled into a LUT.
|
||||
pub fn curve_map_lut(points: &[CurvePoint]) -> Vec<f32> {
|
||||
curve_map_samples::<LUT_SIZE>(points)
|
||||
}
|
||||
|
||||
/// Whole 8-bit levels: the sample count [`tone_luts_qc`] evaluates an 8-bit RGB Curves at.
|
||||
const LEVELS: usize = 256;
|
||||
|
||||
/// [`curve_lut_mode`] sampled at `N` evenly spaced inputs including both end points.
|
||||
fn curve_samples_mode<const N: usize>(points: &[CurvePoint], pencil: bool) -> Vec<f32> {
|
||||
if pencil { curve_map_samples::<N>(points) } else { curve_samples::<N>(points) }
|
||||
}
|
||||
|
||||
/// [`curve_map_lut`] sampled at `N` evenly spaced inputs including both end points.
|
||||
fn curve_map_samples<const N: usize>(points: &[CurvePoint]) -> Vec<f32> {
|
||||
let mut pts: Vec<(f32, f32)> = points.iter().filter(|p| p.input.is_finite() && p.output.is_finite()).map(|p| (p.input, p.output)).collect();
|
||||
pts.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);
|
||||
let ident = |k: usize| k as f32 / (LUT_SIZE - 1) as f32;
|
||||
let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return (0..LUT_SIZE).map(ident).collect() };
|
||||
let ident = |k: usize| k as f32 / N.saturating_sub(1).max(1) as f32;
|
||||
let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return (0..N).map(ident).collect() };
|
||||
let mut seg = 0;
|
||||
(0..LUT_SIZE)
|
||||
(0..N)
|
||||
.map(|k| {
|
||||
let xv = ident(k);
|
||||
if xv <= first.0 {
|
||||
|
||||
@@ -109,7 +109,7 @@ fn thirty_two_bit_adjustments_match_photoshop_unclipped() {
|
||||
// brightness-contrast-legacy.psd
|
||||
assert!(near(hdr(&bc, [0.4910, 0.0009, 0.9301]), [0.6280, -0.0721, 1.2553], 2e-4), "{:?}", hdr(&bc, [0.4910, 0.0009, 0.9301]));
|
||||
// channel-mixer.psd: pure red, green, blue and black, exactly.
|
||||
let mixer = Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false };
|
||||
let mixer = Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false, cmyk: None };
|
||||
for (c, want) in [
|
||||
([1.0, 0.0, 0.0], [0.7998047, 0.1245117, 0.0]),
|
||||
([0.0, 1.0, 0.0], [0.2998047, 0.9243164, 0.1992188]),
|
||||
@@ -857,6 +857,84 @@ fn lab_gradient_map_follows_l() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A CMYK Channel Mixer mixes the ink amounts (#8047): identity keeps the pixel, a mix moves
|
||||
/// only the ink it targets (a positive constant adds ink), monochrome puts its mix in the black
|
||||
/// ink alone, and odd values never panic.
|
||||
#[test]
|
||||
fn cmyk_channel_mixer_mixes_the_inks() {
|
||||
let identity = photocraft_doc::adjust::CMYK_MIXER_IDENTITY;
|
||||
let ink = [0.2, 0.4, 0.6, 0.1];
|
||||
let mut same = ink;
|
||||
mix_inks(&identity, false, &mut same);
|
||||
assert!(same.iter().zip(&ink).all(|(g, w)| (g - w).abs() < 1e-6), "{same:?}");
|
||||
let mut rows = identity;
|
||||
rows[2] = [0.0, 0.0, 1.0, 0.0, 0.25];
|
||||
let mut more_yellow = ink;
|
||||
mix_inks(&rows, false, &mut more_yellow);
|
||||
let want = [0.2, 0.4, 0.85, 0.1];
|
||||
assert!(more_yellow.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{more_yellow:?}");
|
||||
let mut mono = ink;
|
||||
mix_inks(&identity, true, &mut mono);
|
||||
assert!(mono[..3] == [0.0; 3] && (mono[3] - 0.2).abs() < 1e-6, "{mono:?}");
|
||||
let mut odd = [f32::NAN, f32::INFINITY, -3.0, 9.0];
|
||||
mix_inks(&[[f32::MAX; 5]; 4], false, &mut odd);
|
||||
assert!(odd.iter().all(|v| (0.0..=1.0).contains(v)), "{odd:?}");
|
||||
mix_inks(&identity, false, &mut [0.5]);
|
||||
|
||||
// In a CMYK document the mixer works on the screen colour's separation: identity is
|
||||
// the round trip through the inks alone; elsewhere it's the same.
|
||||
let mixer =
|
||||
Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false, cmyk: Some(identity) };
|
||||
assert!(cmyk_channel_adjustment(&mixer) && cmyk_mixer(&mixer));
|
||||
let c = [0.3, 0.5, 0.7, 1.0];
|
||||
let round_trip = {
|
||||
use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk};
|
||||
cmyk_to_rgb(rgb_to_cmyk([c[0], c[1], c[2]]))
|
||||
};
|
||||
for mode in [ColorMode::Cmyk, ColorMode::Rgb] {
|
||||
let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), c);
|
||||
apply_in(&mixer, &mut b, Transfer::Srgb, Some(SampleType::U8), mode);
|
||||
assert!((0..3).all(|i| (b.px[0][i] - round_trip[i]).abs() < 1e-5) && b.px[0][3] == 1.0, "{mode:?}: {:?}", b.px[0]);
|
||||
}
|
||||
let mut more_cyan = identity;
|
||||
more_cyan[0][4] = 0.3;
|
||||
let more_cyan =
|
||||
Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false, cmyk: Some(more_cyan) };
|
||||
for mode in [ColorMode::Cmyk, ColorMode::Rgb] {
|
||||
let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), c);
|
||||
apply_in(&more_cyan, &mut b, Transfer::Srgb, Some(SampleType::U8), mode);
|
||||
assert!(b.px[0][0] < round_trip[0] - 0.05, "{mode:?}: more cyan ink takes red away: {:?}", b.px[0]);
|
||||
}
|
||||
// In a 32-bit document an identity mixer keeps samples past 0..1, and an edit still applies.
|
||||
let hdr = [2.0, 0.5, 0.25, 1.0];
|
||||
let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), hdr);
|
||||
apply_in(&mixer, &mut b, Transfer::Gamma(1.0), Some(SampleType::F32), ColorMode::Rgb);
|
||||
assert!((0..3).all(|i| (b.px[0][i] - hdr[i]).abs() < 1e-5), "identity keeps the HDR highlight: {:?}", b.px[0]);
|
||||
let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), hdr);
|
||||
apply_in(&more_cyan, &mut b, Transfer::Gamma(1.0), Some(SampleType::F32), ColorMode::Rgb);
|
||||
assert!(b.px[0][0] > 1.0 && b.px[0][0] < hdr[0] - 0.05, "more cyan takes red away and keeps it HDR: {:?}", b.px[0]);
|
||||
}
|
||||
|
||||
/// Photoshop's own CMYK Channel Mixer (photoshop corpus cmyk16 channel-mixer.psd, made with
|
||||
/// cyan 80/30/-10, magenta 10/90/0 +5, yellow 0/20/70 and an all-zero black record) on three of
|
||||
/// its pixels: each output ink is the mix of the ink amounts, and the empty black record leaves no
|
||||
/// black ink. Values are the file's 16-bit samples (stored as 1 - ink).
|
||||
#[test]
|
||||
fn cmyk_channel_mixer_matches_photoshop_pixels() {
|
||||
let rows = [[0.8, 0.3, -0.1, 0.0, 0.0], [0.1, 0.9, 0.0, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0, 0.0], [0.0; 5]];
|
||||
let ink = |v: [u16; 4]| v.map(|x| 1.0 - f32::from(x) / 65535.0);
|
||||
for (before, after) in [
|
||||
([65535, 8738, 0, 65535], [55035, 11188, 8396, 65535]),
|
||||
([31612, 37007, 37007, 60395], [32692, 33233, 39905, 65535]),
|
||||
([16448, 21074, 21588, 6426], [17322, 17392, 25950, 65535]),
|
||||
] {
|
||||
let mut got = ink(before);
|
||||
mix_inks(&rows, false, &mut got);
|
||||
let want = ink(after);
|
||||
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1.0 / 255.0), "{before:?}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_modes_and_adjustments_keep_the_screen_colour_path() {
|
||||
let c = [0.2, 0.5, 0.7, 1.0];
|
||||
|
||||
@@ -316,8 +316,8 @@ fn combine(cmy: &Buffer, k: &Buffer) -> CmykBuffer {
|
||||
pub(super) fn render_bands<E>(doc: &Document, rect: Rect, band_rows: i32, tile: i32, mut sink: impl FnMut(CmykBuffer) -> Result<(), E>) -> Result<(), E> {
|
||||
let (cmy, k) = (stand_in(doc, CMY), stand_in(doc, K));
|
||||
let no_patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
|
||||
let a = StandIn { doc: &cmy, cx: Ctx::for_doc(&cmy, &no_patterns) };
|
||||
let b = StandIn { doc: &k, cx: Ctx::for_doc(&k, &no_patterns) };
|
||||
let a = StandIn { doc: &cmy, cx: Ctx { curve_levels: false, ..Ctx::for_doc(&cmy, &no_patterns) } };
|
||||
let b = StandIn { doc: &k, cx: Ctx { curve_levels: false, ..Ctx::for_doc(&k, &no_patterns) } };
|
||||
let rows = crate::band_rows_for(rect.width(), band_rows);
|
||||
let mut y = rect.y0;
|
||||
while y < rect.y1 {
|
||||
@@ -336,7 +336,7 @@ pub(super) fn render_bands<E>(doc: &Document, rect: Rect, band_rows: i32, tile:
|
||||
pub(super) fn render_planes(doc: &Document, rect: Rect, planes: Planes) -> Buffer {
|
||||
let d = stand_in(doc, planes);
|
||||
let no_patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
|
||||
let s = StandIn { doc: &d, cx: Ctx::for_doc(&d, &no_patterns) };
|
||||
let s = StandIn { doc: &d, cx: Ctx { curve_levels: false, ..Ctx::for_doc(&d, &no_patterns) } };
|
||||
s.prepare(rect);
|
||||
s.tile(rect)
|
||||
}
|
||||
|
||||
@@ -60,6 +60,9 @@ pub(crate) struct Ctx<'a> {
|
||||
pub(crate) doc: Option<&'a Document>,
|
||||
/// Effect-map identities of this render's document layers (see [`LayerKeys`]).
|
||||
pub(crate) layer_keys: LayerKeys,
|
||||
/// Whether 8-bit RGB Curves put each channel's output on a whole level
|
||||
/// ([`adjust::tone_luts_depth_in`]); false for the split route's CMYK stand-ins.
|
||||
pub(crate) curve_levels: bool,
|
||||
}
|
||||
|
||||
/// Memo of [`layer_identity`] for the layers of the document being rendered. The identity depends
|
||||
@@ -130,6 +133,7 @@ impl<'a> Ctx<'a> {
|
||||
fx_over_budget: fx_over_budget(&doc.layers, doc.bounds()),
|
||||
layer_keys: Default::default(),
|
||||
tone_luts: prepare_tones(&doc.layers, 0),
|
||||
curve_levels: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,16 +147,28 @@ impl<'a> Ctx<'a> {
|
||||
}
|
||||
|
||||
pub(crate) fn apply_adjustment(&self, adj: &photocraft_doc::Adjustment, buf: &mut Buffer) {
|
||||
let cached = self.tone_luts.iter().find(|(a, _)| std::ptr::eq(*a, adj));
|
||||
// Without a cached table, only a stand-in's tables (unrounded Curves) are built here;
|
||||
// other documents take `apply_in`, which builds the same tables as `for_doc` would.
|
||||
if let photocraft_doc::Adjustment::Levels { space, .. } | photocraft_doc::Adjustment::Curves { space, .. } = adj
|
||||
&& !matches!(adj, photocraft_doc::Adjustment::Levels { space: photocraft_doc::adjust::ToneSpace::Rgb, .. } if self.depth == photocraft_color::SampleType::F32)
|
||||
&& let Some((_, luts)) = self.tone_luts.iter().find(|(a, _)| std::ptr::eq(*a, adj))
|
||||
&& (cached.is_some() || !self.curve_levels)
|
||||
{
|
||||
let identity = adjust::float_tone_identity(adj, Some(self.depth));
|
||||
if identity == [true; 3] {
|
||||
return;
|
||||
}
|
||||
let extrapolate = adjust::float_tone_extrapolates(adj, Some(self.depth), self.mode);
|
||||
adjust::apply_tone(buf, *space, luts.get_or_init(|| adjust::tone_luts_depth(adj, Some(self.depth))), identity, extrapolate);
|
||||
let tables = || adjust::tone_luts_depth_in(adj, Some(self.depth), self.curve_levels);
|
||||
let built;
|
||||
let luts = match cached {
|
||||
Some((_, luts)) => luts.get_or_init(tables),
|
||||
None => {
|
||||
built = tables();
|
||||
&built
|
||||
}
|
||||
};
|
||||
adjust::apply_tone(buf, *space, luts, identity, extrapolate);
|
||||
} else {
|
||||
adjust::apply_in(adj, buf, self.transfer, Some(self.depth), self.mode);
|
||||
}
|
||||
|
||||
@@ -249,13 +249,20 @@ impl FxMaps {
|
||||
#[cfg(test)]
|
||||
mod inner_shadow_anti_alias_tests;
|
||||
#[cfg(test)]
|
||||
mod outer_glow_noise_tests;
|
||||
mod inner_shadow_size_one_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod inner_shadow_noise_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod outer_glow_noise_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod outer_glow_range_one_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod satin_invert_contour_tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -229,21 +229,35 @@ fn the_off_path_is_bit_for_bit_unchanged() {
|
||||
/// The review's first break: the issue's document with SIZE 1 (Angle 0, Distance 0, Choke 0,
|
||||
/// Gaussian, Anti-aliased on). `spread_split(1, 0)` is `(0, 1)`, so `dilate` no-ops at a radius of
|
||||
/// 0 and `blur(m, 1.0)` is the identity (`tent_kernel(1).0 == 0`, and `tent` returns at once): the
|
||||
/// third-of-a-pixel source offset becomes the whole map. Coverage 1/3 through the Gaussian
|
||||
/// contour (0.30) then lands on the bottom and right inner edges only, G 90 where the layer reads
|
||||
/// its own 128, and nothing at the top and left - a one-sided black line that no measurement
|
||||
/// shows, because Size 1 was never measured with the flag on. Today's Size 1 map is empty and
|
||||
/// has to stay empty.
|
||||
/// third-of-a-pixel source offset would become the whole map. Coverage 1/3 through the Gaussian
|
||||
/// contour (0.30) would then land on the bottom and right inner edges only, G 90 where the layer
|
||||
/// reads its own 128, and nothing at the top and left - a one-sided black line that no measurement
|
||||
/// shows, because Size 1 was never measured with the flag on. So the offset stays off at Size 1.
|
||||
/// (Written when today's Size 1 map was empty; #14933 merged in after it and gave Size 1 the
|
||||
/// quarter-strength edge pixel the reference shows - with the flag off as with it on, so the
|
||||
/// invariant this test pins, that Anti-aliased does not move the Size 1 map, stands.)
|
||||
#[test]
|
||||
fn anti_aliased_size_one_keeps_todays_empty_map() {
|
||||
fn anti_aliased_size_one_leaves_the_map_the_other_pr_fixed() {
|
||||
let off = map(1.0, 0.0, 0.0, 0.0, gaussian(), false);
|
||||
assert!(off.v.iter().all(|v| *v == 0.0), "today's Size 1 inner shadow map is no longer empty");
|
||||
let on = map(1.0, 0.0, 0.0, 0.0, gaussian(), true);
|
||||
for (side, x, y) in [("bottom", 200i64, 224), ("right", 299, 150), ("top", 200, 75), ("left", 100, 150)] {
|
||||
let got = g(on.get(x, y));
|
||||
assert_eq!(got.round() as i32, 128, "Anti-aliased Size 1 painted the {side} inner edge: G {got:.1}");
|
||||
}
|
||||
assert_eq!(bit_hash(&on), bit_hash(&off), "the Size 1 inner shadow map moved with Anti-aliased on");
|
||||
// The map #14933 fixed: a darkened first pixel inside every edge, the same on all four sides
|
||||
// (the one-sided line the offset would paint is dark on two and clean on the other two), and
|
||||
// the layer's own 128 one pixel deeper. This file's contour is the Gaussian curve, so the
|
||||
// first pixel reads darker than the 96 the Size 1 test's default contour gives.
|
||||
let mut firsts = [0.0f32; 4];
|
||||
for (k, (side, x, y, dx, dy)) in
|
||||
[("bottom", 200i64, 224, 0, -1), ("right", 299, 150, -1, 0), ("top", 200, 75, 0, 1), ("left", 100, 150, 1, 0)].into_iter().enumerate()
|
||||
{
|
||||
let got = g(on.get(x, y));
|
||||
firsts[k] = got;
|
||||
assert!(got < 126.0, "Size 1 left the {side} inner edge clean: G {got:.1}");
|
||||
let deeper = g(on.get(x + dx, y + dy));
|
||||
assert!((deeper - 128.0).abs() <= 2.0, "Size 1 beyond the first pixel at the {side} inner edge: G {deeper:.1}");
|
||||
}
|
||||
for pair in [(0usize, 1usize), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] {
|
||||
assert!((firsts[pair.0] - firsts[pair.1]).abs() < 0.05, "the Size 1 inner shadow is not symmetric: {firsts:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The second degeneracy the review names: Size 2 with Choke 50 %. `spread_split(2, 0.5)` is
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
//! #14933 — BUG-LAYER-STYLE-INNER-SHADOW-SIZE-ONE.
|
||||
//!
|
||||
//! Measured on the issue's test document: 400 × 300 px, 72 ppi, RGB 8 bit, white Background, an
|
||||
//! orange (255, 128, 0) pixel layer covering x 100..299, y 75..224. Inner Shadow black, Normal,
|
||||
//! 100 %, Use Global Light off, Distance 0, Choke 0, Contour Linear, Anti-aliased off, Noise 0.
|
||||
//! The issue's table is the G channel of the flattened image read from a layer edge inwards:
|
||||
//! 128 is the layer's own orange (no shadow), 0 is full shadow.
|
||||
|
||||
use super::*;
|
||||
|
||||
const DOC_W: usize = 400;
|
||||
const DOC_H: usize = 300;
|
||||
|
||||
/// The layer's alpha over the whole document: solid over x 100..=299, y 75..=224.
|
||||
fn document_shape() -> Map {
|
||||
let mut m = Map::new(DOC_W, DOC_H, 0.0);
|
||||
for y in 75..=224 {
|
||||
for x in 100..=299 {
|
||||
m.v[y * DOC_W + x] = 1.0;
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// The issue's Inner Shadow settings: black, Normal, 100 %, global light off, Choke `spread`.
|
||||
fn shadow(size: f32, distance: f32, angle: f32, spread: f32) -> Shadow {
|
||||
Shadow {
|
||||
common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0),
|
||||
color: photocraft_color::Color::BLACK,
|
||||
angle,
|
||||
use_global_light: false,
|
||||
distance,
|
||||
spread,
|
||||
size,
|
||||
contour: Contour::Linear,
|
||||
anti_alias: false,
|
||||
noise: 0.0,
|
||||
knocks_out: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn map(size: f32, distance: f32, angle: f32, spread: f32) -> Map {
|
||||
shadow_map(&document_shape(), &shadow(size, distance, angle, spread), &GlobalLight::default(), true, (0, 0))
|
||||
}
|
||||
|
||||
/// The G channel of the orange layer under a black Normal inner shadow of coverage `c`.
|
||||
fn g(c: f32) -> f32 {
|
||||
128.0 * (1.0 - c)
|
||||
}
|
||||
|
||||
/// The twenty G values inwards from each of the four edges, in the order the issue reads them:
|
||||
/// top = column x 200 from y 75 down, left = row y 150 from x 100, bottom = column x 200 from
|
||||
/// y 224 up, right = row y 150 from x 299 left.
|
||||
fn ramps(m: &Map) -> [Vec<f32>; 4] {
|
||||
let line = |first: (i64, i64), step: (i64, i64)| (0..20).map(|k| g(m.get(first.0 + k * step.0, first.1 + k * step.1))).collect();
|
||||
[line((200, 75), (0, 1)), line((100, 150), (1, 0)), line((200, 224), (0, -1)), line((299, 150), (-1, 0))]
|
||||
}
|
||||
|
||||
/// Assert the ten-pixel G ramp of every edge against `want`, within 2 levels (the issue's
|
||||
/// tolerance) and the same on all four sides.
|
||||
fn assert_edges(m: &Map, want: &[f32], what: &str) {
|
||||
let [top, left, bottom, right] = ramps(m);
|
||||
for (side, r) in ["top", "left", "bottom", "right"].iter().zip([top.as_slice(), left.as_slice(), bottom.as_slice(), right.as_slice()]) {
|
||||
for (d, w) in want.iter().enumerate() {
|
||||
assert!((r[d] - *w).abs() <= 2.0, "{what}, {side} edge, {d} px in: {} vs measured {w}", r[d]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Done when: Size 1, Distance 0 puts G 96 (within 2 levels) on the first pixel inside every edge
|
||||
/// and leaves the second one at the layer's own 128. Today `shadow_map` blurs with a width-1 box,
|
||||
/// which is the identity, so the map is still the hard inverted alpha and the clip to the layer
|
||||
/// removes the shadow completely: every pixel stays 128.
|
||||
#[test]
|
||||
fn size_one_draws_the_measured_edge_pixel() {
|
||||
assert_edges(&map(1.0, 0.0, 0.0, 0.0), &[96.0, 128.0], "Size 1");
|
||||
// Outside the layer nothing changes: the map is still clipped to the shape, so white stays white
|
||||
// at y 74 and x 99.
|
||||
let m = map(1.0, 0.0, 0.0, 0.0);
|
||||
for (x, y) in [(200i64, 74), (99, 150), (200, 225), (300, 150)] {
|
||||
assert_eq!(m.get(x, y), 0.0, "no inner shadow outside the layer at ({x},{y})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Done when: Sizes 3, 10 and 20 keep the measured profiles (they already match today).
|
||||
#[test]
|
||||
fn sizes_three_ten_and_twenty_keep_the_measured_profiles() {
|
||||
let table: [(f32, &[f32]); 3] = [
|
||||
(3.0, &[85.0, 114.0, 128.0]),
|
||||
(10.0, &[70.0, 82.0, 92.0, 101.0, 109.0, 115.0, 120.0, 124.0, 126.0, 128.0]),
|
||||
(20.0, &[67.0, 73.0, 79.0, 84.0, 89.0, 94.0, 99.0, 103.0, 107.0, 110.0, 113.0, 116.0, 119.0, 121.0, 123.0, 125.0, 126.0, 127.0, 127.0, 128.0]),
|
||||
];
|
||||
for (size, want) in table {
|
||||
assert_edges(&map(size, 0.0, 0.0, 0.0), want, &format!("Size {size}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Done when: Size 0 keeps the hard band of Distance pixels. Measured: Size 0, Distance 5,
|
||||
/// Angle 90 reads 0 for five pixels from the top edge and 128 after that; the other edges stay 128.
|
||||
#[test]
|
||||
fn size_zero_keeps_the_hard_band_of_distance() {
|
||||
let m = map(0.0, 5.0, 90.0, 0.0);
|
||||
let col: Vec<f32> = (75..81).map(|y| g(m.get(200, y))).collect();
|
||||
assert_eq!(&col[..5], &[0.0f32; 5][..], "five dark pixels then 128: {col:?}");
|
||||
assert_eq!(col[5], 128.0, "the band ends after Distance pixels: {col:?}");
|
||||
// The other three edges read their own colour at the pixel the issue reads them from.
|
||||
for k in 0..6 {
|
||||
assert_eq!(g(m.get(100 + k, 150)), 128.0, "left edge keeps its own colour, x {}", 100 + k);
|
||||
assert_eq!(g(m.get(299 - k, 150)), 128.0, "right edge keeps its own colour, x {}", 299 - k);
|
||||
assert_eq!(g(m.get(200, 224 - k)), 128.0, "bottom edge keeps its own colour, y {}", 224 - k);
|
||||
}
|
||||
}
|
||||
|
||||
/// A hash over every coverage value of a map: the map is bit-for-bit unchanged iff this is.
|
||||
fn bit_hash(m: &Map) -> u64 {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for v in &m.v {
|
||||
h = (h ^ u64::from(v.to_bits())).wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// Every other Size 1 and every other size is bit-for-bit what it was: these are the coverage
|
||||
/// ramps and whole-map hashes `shadow_map` gave on upstream/main c162cb6d6 before the fix, copied
|
||||
/// out of the probe run. They pin that the Size 1 kernel is taken only by the Inner Shadow of
|
||||
/// Size 1 with Choke 0 — sub-1 and fractional sizes (which the issue leaves unmeasured), sizes
|
||||
/// 1.5..250, the Drop Shadow of the same size (#14880 keeps its own ticket) and a choked Size 1
|
||||
/// all keep today's map.
|
||||
#[test]
|
||||
fn other_sizes_are_unchanged() {
|
||||
let pin = |m: &Map, want: &[f64]| {
|
||||
let got: Vec<f32> = (75..87).map(|y| m.get(200, y)).collect();
|
||||
for (d, (g, w)) in got.iter().zip(want).enumerate() {
|
||||
assert!((f64::from(*g) - *w).abs() <= 1e-6, "{d} px in: {g:.8} vs {w:.8} on main");
|
||||
}
|
||||
};
|
||||
let sizes: [(f32, &[f64]); 8] = [
|
||||
(0.5, &[0.0; 12]),
|
||||
(1.5, &[0.25, 0.02777778, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
|
||||
(2.0, &[0.3125, 0.0625, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
|
||||
(3.0, &[0.33333334, 0.11111111, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
|
||||
(6.0, &[0.42361110, 0.28472221, 0.17361110, 0.09027778, 0.03472222, 0.00694444, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
|
||||
(10.0, &[0.45249999, 0.36250001, 0.28250000, 0.21250001, 0.15250000, 0.10250000, 0.06250000, 0.03250000, 0.01250000, 0.00250000, 0.0, 0.0]),
|
||||
(
|
||||
20.0,
|
||||
&[0.47562501, 0.42812499, 0.38312501, 0.34062499, 0.30062500, 0.26312500, 0.22812501, 0.19562501, 0.16562501, 0.13812500, 0.11312500, 0.09062500],
|
||||
),
|
||||
(
|
||||
250.0,
|
||||
&[0.45157880, 0.45233655, 0.45308408, 0.45382136, 0.45454839, 0.45526519, 0.45597175, 0.45666808, 0.45735416, 0.45802999, 0.45869559, 0.45935094],
|
||||
),
|
||||
];
|
||||
let hashes: [(f32, u64); 8] = [
|
||||
(0.5, 0xe94d_157b_1934_6225),
|
||||
(1.5, 0xbbca_5e75_8b9f_520d),
|
||||
(2.0, 0x6bd5_69ac_da8a_6225),
|
||||
(3.0, 0x3109_0d74_08b1_8c1d),
|
||||
(6.0, 0xe5dc_989a_bcfb_ed89),
|
||||
(10.0, 0x2200_2b2d_61bc_9c2d),
|
||||
(20.0, 0x8ba0_be17_19fa_7b25),
|
||||
(250.0, 0x460f_fa2e_3da8_0c4d),
|
||||
];
|
||||
for (size, want) in sizes {
|
||||
pin(&map(size, 0.0, 0.0, 0.0), want);
|
||||
}
|
||||
for (size, want) in hashes {
|
||||
let got = bit_hash(&map(size, 0.0, 0.0, 0.0));
|
||||
assert_eq!(got, want, "the whole Size {size} inner shadow map moved");
|
||||
}
|
||||
// A Drop Shadow of Size 1 keeps today's hard inverted alpha (#14880 is its own ticket).
|
||||
let drop = |size: f32| shadow_map(&document_shape(), &shadow(size, 0.0, 0.0, 0.0), &GlobalLight::default(), false, (0, 0));
|
||||
let one = drop(1.0);
|
||||
let got: Vec<f32> = (72..84).map(|y| one.get(200, y)).collect();
|
||||
assert_eq!(&got[..3], &[0.0f32; 3][..], "a Size 1 drop shadow still paints nothing outside the layer: {got:?}");
|
||||
assert_eq!(&got[3..], &[1.0f32; 9][..], "and stays hard inside it: {got:?}");
|
||||
assert_eq!(bit_hash(&one), 0xa067_0cbe_8a34_6225, "the whole Size 1 drop shadow map moved");
|
||||
assert_eq!(bit_hash(&drop(3.0)), 0xc097_cc3a_25df_6ae5, "the whole Size 3 drop shadow map moved");
|
||||
// Size 1 with Choke 50 % is not measured either: today it is a hard 1 px band.
|
||||
let choked = map(1.0, 0.0, 0.0, 0.5);
|
||||
assert_eq!(choked.get(200, 74), 0.0);
|
||||
assert_eq!(choked.get(200, 75), 1.0, "a choked Size 1 inner shadow keeps its hard band");
|
||||
assert_eq!(choked.get(200, 76), 0.0);
|
||||
assert_eq!(bit_hash(&choked), 0xde5c_6e74_9734_6225, "the choked Size 1 map moved");
|
||||
}
|
||||
|
||||
/// The kernel is distance-independent, so a Size 1 inner shadow away from the light keeps the
|
||||
/// band of Distance pixels and gains the same ¾ / ¼ coverage where the band ends. That
|
||||
/// combination is not in the issue's measured table; it is spelled out here so the consequence of
|
||||
/// the kernel is visible rather than assumed.
|
||||
#[test]
|
||||
fn size_one_at_a_distance_adds_the_ramp_at_the_band_edge() {
|
||||
let m = map(1.0, 5.0, 90.0, 0.0);
|
||||
let col: Vec<f32> = (75..83).map(|y| g(m.get(200, y))).collect();
|
||||
assert_eq!(&col[..4], &[0.0f32; 4][..], "the band of Distance pixels: {col:?}");
|
||||
assert!((col[4] - 32.0).abs() <= 2.0 && (col[5] - 96.0).abs() <= 2.0, "the quarter ramp where the band ends: {col:?}");
|
||||
assert_eq!(&col[6..], &[128.0f32; 2][..], "and nothing deeper: {col:?}");
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//! #14958: the Outer Glow Range 1 % profile on the measured document.
|
||||
//!
|
||||
//! Test document: 400 x 300 px, 72 ppi, RGB 8 bit, white Background, pixel layer "Shape" with an
|
||||
//! orange (255,128,0) rectangle at x 100..299, y 75..224. Outer Glow black, Normal 100 %, Softer,
|
||||
//! Spread 0, Size 10, Contour Linear, Anti-aliased off, Noise 0. Profiles list the R channel of
|
||||
//! the flattened image from the layer edge outwards (255 = no glow, 0 = full black glow); the
|
||||
//! reference application gives `0 x8, 39, 255` at Range 1 % on all four edges (within 3 levels).
|
||||
//! Range 25/50/100 keep today's profiles (the measured values, within 4 levels). The cases the
|
||||
//! issue marks *not measured* (Range 2, other Sizes at Range 1, Precise at Range 1, Range 1 with
|
||||
//! Spread, a custom contour at Range 1, the Inner Glow Center source at Range 1) pin today's
|
||||
//! output. The last inner test mirrors #14929's measured Inner Glow Range-1 profile `0 x8, 19,
|
||||
//! 128` through the shared table as a cross-check; it does not claim that issue's item.
|
||||
|
||||
use super::{Contour, Effect, FxPaint, Glow, GlowSource, GlowTechnique, Rect};
|
||||
use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_doc::{Document, FxCommon, Layer};
|
||||
use photocraft_geom::Size;
|
||||
|
||||
/// The measured glow with `range` (0..=1): Size 10, Spread 0, Softer, Edge, Linear contour.
|
||||
fn glow(range: f32) -> Glow {
|
||||
Glow {
|
||||
common: FxCommon::new(BlendMode::Normal, 1.0),
|
||||
paint: FxPaint::Color(Color::BLACK),
|
||||
technique: GlowTechnique::Softer,
|
||||
spread: 0.0,
|
||||
size: 10.0,
|
||||
contour: Contour::Linear,
|
||||
anti_alias: false,
|
||||
range,
|
||||
jitter: 0.0,
|
||||
noise: 0.0,
|
||||
source: GlowSource::Edge,
|
||||
}
|
||||
}
|
||||
|
||||
/// The measured document with one glow effect on the orange rectangle; `inner` for an Inner Glow.
|
||||
fn measured_doc(g: Glow, inner: bool) -> Document {
|
||||
let mut d = Document::with_background("range one", Size::new(400, 300), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
let mut l = Layer::raster("Shape", PixelFormat::RGBA8);
|
||||
l.surface_mut().unwrap().fill_rect(Rect::new(100, 75, 300, 225), &[1.0, 128.0 / 255.0, 0.0, 1.0]);
|
||||
l.effects.items = vec![if inner { Effect::InnerGlow(g) } else { Effect::OuterGlow(g) }];
|
||||
d.layers.push(l);
|
||||
d
|
||||
}
|
||||
|
||||
/// The pixel `d` (1-based) out from edge `e` (0 top, 1 left, 2 bottom, 3 right) of the rectangle.
|
||||
fn out_point(e: usize, d: usize) -> (i32, i32) {
|
||||
let d = d as i32;
|
||||
match e {
|
||||
0 => (200, 75 - d),
|
||||
1 => (100 - d, 150),
|
||||
2 => (200, 224 + d),
|
||||
_ => (299 + d, 150),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixel `d` (1-based) in from edge `e`, for the inner-glow checks.
|
||||
fn in_point(e: usize, d: usize) -> (i32, i32) {
|
||||
let d = d as i32;
|
||||
match e {
|
||||
0 => (200, 74 + d),
|
||||
1 => (99 + d, 150),
|
||||
2 => (200, 225 - d),
|
||||
_ => (300 - d, 150),
|
||||
}
|
||||
}
|
||||
|
||||
/// The flattened 8-bit level of channel `ch` at `(x, y)` in the already-rendered buffer `b`.
|
||||
fn level(b: &crate::Buffer, x: i32, y: i32, ch: usize) -> i32 {
|
||||
let w = b.rect.width() as usize;
|
||||
(255.0 * b.px[(y - b.rect.y0) as usize * w + (x - b.rect.x0) as usize][ch]).round() as i32
|
||||
}
|
||||
|
||||
/// Compares the `want.len()` pixels from each of the four edges along channel `ch` (inwards for
|
||||
/// inner glows) against `want`, level by level, within `tol`.
|
||||
fn assert_all_edges(doc: &Document, ch: usize, inward: bool, want: &[i32], tol: i32, what: &str) {
|
||||
let b = crate::render(doc, doc.bounds());
|
||||
for e in 0..4 {
|
||||
for (d, &want) in want.iter().enumerate() {
|
||||
let (x, y) = if inward { in_point(e, d + 1) } else { out_point(e, d + 1) };
|
||||
let got = level(&b, x, y, ch);
|
||||
assert!(got - want <= tol && want - got <= tol, "{what}, edge {e}, {} px from the edge: expected {want}, got {got} (want {want:?})", d + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #14958 Done when 1: Range 1 % at Size 10 gives eight solid pixels, then 39, then no glow on
|
||||
/// all four edges, within 3 levels. Today (main) the glow reaches one pixel further with a much
|
||||
/// lighter last pixel: nine solid, then 191.
|
||||
#[test]
|
||||
fn outer_glow_range_one_gives_eight_solid_then_39_on_every_edge() {
|
||||
assert_all_edges(&measured_doc(glow(0.01), false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 39, 255, 255, 255], 3, "Range 1 %");
|
||||
}
|
||||
|
||||
/// #14958 Done when 2 (guard, passes before and after): Range 25 keeps today's profile, matching
|
||||
/// the measured `0 0 0 42 103 153 194 225 245 255` within 4 levels.
|
||||
#[test]
|
||||
fn outer_glow_range_25_keeps_the_measured_profile() {
|
||||
assert_all_edges(&measured_doc(glow(0.25), false), 0, false, &[0, 0, 0, 42, 103, 153, 194, 225, 245, 255, 255, 255], 4, "Range 25 %");
|
||||
}
|
||||
|
||||
/// #14958 Done when 2 (guard): Range 50 keeps today's measured `26 72 113 148 179 204 225 240
|
||||
/// 250 255` within 4 levels.
|
||||
#[test]
|
||||
fn outer_glow_range_50_keeps_the_measured_profile() {
|
||||
assert_all_edges(&measured_doc(glow(0.5), false), 0, false, &[26, 72, 113, 148, 179, 204, 225, 240, 250, 255, 255, 255], 4, "Range 50 %");
|
||||
}
|
||||
|
||||
/// #14958 Done when 2 (guard): Range 100 keeps today's measured `140 163 184 201 217 229 240
|
||||
/// 247 252 255` within 4 levels.
|
||||
#[test]
|
||||
fn outer_glow_range_100_keeps_the_measured_profile() {
|
||||
assert_all_edges(&measured_doc(glow(1.0), false), 0, false, &[140, 163, 184, 201, 217, 229, 240, 247, 252, 255, 255, 255], 4, "Range 100 %");
|
||||
}
|
||||
|
||||
/// The first pixel inside the edge stays the layer colour: the glow never covers the layer
|
||||
/// itself (guard, passes before and after).
|
||||
#[test]
|
||||
fn outer_glow_range_one_never_covers_the_layer_itself() {
|
||||
let d = measured_doc(glow(0.01), false);
|
||||
let b = crate::render(&d, d.bounds());
|
||||
let inside = [level(&b, 200, 75, 0), level(&b, 200, 75, 1), level(&b, 200, 75, 2)];
|
||||
assert_eq!(inside, [255, 128, 0], "(200, 75) stays the layer colour 255.128.0");
|
||||
}
|
||||
|
||||
/// Cross-check of the shared cause with #14929 (no claim on that item): its measured Inner Glow
|
||||
/// Range-1 profile is the mirror image `0 x8, 19, 128` on the G channel of the same document.
|
||||
/// Today the glow reaches one pixel further inwards (nine solid, then 96).
|
||||
#[test]
|
||||
fn inner_glow_range_one_mirrors_the_measured_profile() {
|
||||
assert_all_edges(&measured_doc(glow(0.01), true), 1, true, &[0, 0, 0, 0, 0, 0, 0, 0, 19, 128, 128, 128], 3, "inner Range 1 %");
|
||||
}
|
||||
|
||||
/// Not measured, keeps today's behaviour: a Precise glow at Range 1 % (its coverage stays above
|
||||
/// the range down to the last pixel of its falloff).
|
||||
#[test]
|
||||
fn outer_glow_range_one_precise_keeps_todays_profile() {
|
||||
let g = Glow { technique: GlowTechnique::Precise, ..glow(0.01) };
|
||||
assert_all_edges(&measured_doc(g, false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255], 1, "precise Range 1 %");
|
||||
}
|
||||
|
||||
/// Not measured, keeps today's behaviour: Range 1 % with Spread 20 % (dilate 2, tent 8: solid
|
||||
/// through 9 px, then 155, then no glow).
|
||||
#[test]
|
||||
fn outer_glow_range_one_with_spread_keeps_todays_profile() {
|
||||
let g = Glow { spread: 0.2, ..glow(0.01) };
|
||||
assert_all_edges(&measured_doc(g, false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 155, 255, 255], 1, "spread 20 % at Range 1 %");
|
||||
}
|
||||
|
||||
/// Not measured, keeps today's behaviour: another Size at Range 1 % (Size 20: solid through 17
|
||||
/// px, then 48, 175, 239, then no glow).
|
||||
#[test]
|
||||
fn outer_glow_range_one_other_sizes_keep_todays_profile() {
|
||||
let g = Glow { size: 20.0, ..glow(0.01) };
|
||||
assert_all_edges(&measured_doc(g, false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 175, 239, 255], 1, "size 20 at Range 1 %");
|
||||
}
|
||||
|
||||
/// Not measured, keeps today's behaviour: a whole-number Range next to 1 (2 %: solid through 8
|
||||
/// px, then 96, 223, then no glow).
|
||||
#[test]
|
||||
fn outer_glow_range_two_keeps_todays_profile() {
|
||||
assert_all_edges(&measured_doc(glow(0.02), false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 96, 223, 255, 255], 1, "Range 2 %");
|
||||
}
|
||||
|
||||
/// Not measured, keeps today's behaviour: a custom (flat) contour at Range 1 % keeps the
|
||||
/// #11361 reach-capped transfer (solid through 10 px, then no glow).
|
||||
#[test]
|
||||
fn outer_glow_range_one_custom_contour_keeps_todays_profile() {
|
||||
let g = Glow {
|
||||
contour: Contour::Custom {
|
||||
name: "flat".into(),
|
||||
points: [(0.0, 1.0), (1.0, 1.0)].iter().map(|&(input, output)| photocraft_doc::adjust::CurvePoint { input, output }).collect(),
|
||||
corners: vec![],
|
||||
},
|
||||
..glow(0.01)
|
||||
};
|
||||
assert_all_edges(&measured_doc(g, false), 0, false, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255], 1, "flat contour at Range 1 %");
|
||||
}
|
||||
|
||||
/// Not measured, keeps today's behaviour: an Inner Glow from the Center at Range 1 % (no glow
|
||||
/// for the first nine pixels in, one dim step at 10 px, full towards the middle).
|
||||
#[test]
|
||||
fn inner_glow_range_one_center_source_keeps_todays_profile() {
|
||||
let g = Glow { source: GlowSource::Center, ..glow(0.01) };
|
||||
assert_all_edges(&measured_doc(g, true), 1, true, &[128, 128, 128, 128, 128, 128, 128, 128, 128, 32, 0, 0], 1, "inner center at Range 1 %");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::blur::{blur, dilate};
|
||||
use super::blur::{blur, dilate, size_one_blur};
|
||||
use super::distance::{dist_inside, dist_outside};
|
||||
use super::{
|
||||
BlendMode, Buffer, Contour, Effect, FxPaint, GlobalLight, Glow, GlowSource, GlowTechnique, Gradient, GradientStyle, Map, Placement, PreparedPatterns, Rect,
|
||||
@@ -33,7 +33,32 @@ pub(super) fn lut_at(l: &[f32], v: f32) -> f32 {
|
||||
/// A glow's coverage transfer: its contour applied over the Range (Photoshop maps the glow's
|
||||
/// coverage `v` through `contour(min(v / range, 1))`, so the default 50 % doubles a blurred
|
||||
/// edge's 0.5 to full strength). `None` = identity.
|
||||
///
|
||||
/// One measured exception (#14958, and #14929 through this same table): at the Range-1 % test
|
||||
/// document (Softer, Size 10, Spread 0, Linear contour, Edge source) the reference application
|
||||
/// hardens the glow instead of amplifying the blur's tail to one pixel further: the coverage at
|
||||
/// the tent's last tap (its reach's outermost pixel, 0.0025 at Size 10) paints nothing, and the
|
||||
/// coverage one pixel inside it (0.0125) paints 0.85 - measured as 39 of 255 outside the layer
|
||||
/// and 19 of 128 inside. A linear ramp from that last tap to `range` plus 3/4 of it reproduces
|
||||
/// all four measured pixels within 1 level (outer 40, inner 20, both reaches exact); today's
|
||||
/// `min(v / range, 1)` there paints solid one pixel wider and leaves 191 (outer) / 96 (inner)
|
||||
/// at the pixel the reference stops at. Every other configuration - all other Ranges, Sizes
|
||||
/// and Spreads, Precise, the Center source, and custom contours - keeps `ranged_lut` exactly.
|
||||
pub fn glow_lut(g: &Glow) -> Option<Vec<f32>> {
|
||||
if matches!(g.contour, Contour::Linear)
|
||||
&& matches!(g.technique, GlowTechnique::Softer)
|
||||
&& g.source == GlowSource::Edge
|
||||
&& g.spread == 0.0
|
||||
&& g.size == 10.0
|
||||
&& (g.range - 0.01).abs() < 1e-6
|
||||
{
|
||||
// `tent_kernel` stores its weights from -r to r and never an empty list, so its last
|
||||
// entry is the tap at the reach's end (for Size 10: 1/400): the straight edge's
|
||||
// coverage at the reach's outermost pixel. `end` 0 (unreachable) leaves today's ramp.
|
||||
let end = super::blur::tent_kernel(g.size).1.last().copied().unwrap_or(0.0);
|
||||
let full = g.range + 0.75 * end;
|
||||
return Some((0..GLOW_LUT_LEN).map(|k| ((k as f32 / (GLOW_LUT_LEN - 1) as f32 - end) / full).clamp(0.0, 1.0)).collect());
|
||||
}
|
||||
ranged_lut(&g.contour, g.range)
|
||||
}
|
||||
|
||||
@@ -453,7 +478,15 @@ pub(super) fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bo
|
||||
let mut m = src.shifted(dx + aa, dy + aa, if inner { 1.0 } else { 0.0 });
|
||||
let (r, bw) = spread_split(s.size, s.spread);
|
||||
m = dilate(&m, r);
|
||||
blur(&mut m, bw);
|
||||
if inner && s.size == 1.0 && s.spread == 0.0 {
|
||||
// #14933: a Size 1 inner shadow with Choke 0. At that width the box blur is the identity
|
||||
// (`box_width` floors it at 1 px), so the map keeps the hard inverted alpha and the clip to
|
||||
// the layer below removes the shadow completely. The reference application keeps a
|
||||
// quarter-strength shadow on the first pixel inside every edge: `SIZE_ONE_TAPS`.
|
||||
size_one_blur(&mut m);
|
||||
} else {
|
||||
blur(&mut m, bw);
|
||||
}
|
||||
let mut m = apply_contour(m, &s.contour);
|
||||
noise(&mut m, s.noise, origin.0, origin.1);
|
||||
if inner {
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
//! it does there.
|
||||
//!
|
||||
//! Plain adjustment layers that Photoshop evaluates on the inks (Invert, Posterize, Threshold,
|
||||
//! Brightness/Contrast, Hue/Saturation, Color Balance, and Levels and Curves on CMYK channels)
|
||||
//! Brightness/Contrast, Hue/Saturation, Color Balance, a CMYK Channel Mixer, and Levels and
|
||||
//! Curves on CMYK channels)
|
||||
//! join such a stack too: on the
|
||||
//! stored inks their rules are exact, where the RGB compositor can only apply them to a separation
|
||||
//! of its RGB composite, whose black differs from the file's. Such stacks are also rendered for
|
||||
@@ -54,7 +55,7 @@ enum InkOp<'a> {
|
||||
/// Each ink's stored value (1 - ink) through its channel's table: C, M, Y, K
|
||||
/// (`adjust::ink_through`; Levels, Curves and Brightness/Contrast).
|
||||
Tables([Vec<f32>; INKS]),
|
||||
/// Invert, Posterize or Threshold (`adjust::stored_channels`).
|
||||
/// Invert, Posterize, Threshold or a CMYK Channel Mixer (`adjust::stored_channels`).
|
||||
Rules(&'a Adjustment),
|
||||
/// Hue/Saturation or Color Balance on C, M and Y as inverted RGB (`adjust::apply_cmy`).
|
||||
Cmy(&'a Adjustment),
|
||||
@@ -86,7 +87,9 @@ fn ink_op(layer: &Layer, depth: SampleType) -> Option<InkOp<'_>> {
|
||||
return None;
|
||||
}
|
||||
match adj {
|
||||
Adjustment::Invert | Adjustment::Posterize { .. } | Adjustment::Threshold { .. } => Some(InkOp::Rules(adj)),
|
||||
Adjustment::Invert | Adjustment::Posterize { .. } | Adjustment::Threshold { .. } | Adjustment::ChannelMixer { cmyk: Some(_), .. } => {
|
||||
Some(InkOp::Rules(adj))
|
||||
}
|
||||
_ if adjust::cmy_adjustment(adj) => Some(InkOp::Cmy(adj)),
|
||||
Adjustment::BrightnessContrast { brightness, contrast, legacy } => {
|
||||
let t = adjust::ink_brightness_contrast_lut(*brightness, *contrast, *legacy);
|
||||
|
||||
@@ -378,6 +378,7 @@ pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer {
|
||||
fx_clip: Default::default(),
|
||||
fx_over_budget: false,
|
||||
tone_luts: prepare_tones(std::slice::from_ref(layer), 0),
|
||||
curve_levels: true,
|
||||
doc: None,
|
||||
layer_keys: Default::default(),
|
||||
},
|
||||
|
||||
@@ -278,9 +278,20 @@ pub enum Adjustment {
|
||||
density: f32,
|
||||
preserve_luminosity: bool,
|
||||
},
|
||||
/// `matrix`: one row per RGB output (red, green, blue), each `[red, green, blue, constant]`
|
||||
/// as fractions (1 = 100 %); with `monochrome` the first row is the gray mix.
|
||||
ChannelMixer {
|
||||
matrix: [[f32; 4]; 3],
|
||||
monochrome: bool,
|
||||
/// A CMYK document's mixer (Photoshop's Cyan, Magenta, Yellow and Black outputs): one row
|
||||
/// per output, each `[cyan, magenta, yellow, black, constant]`, evaluated on the ink
|
||||
/// amounts (0 none, 1 full; a positive constant adds ink). When set, `matrix` is unused;
|
||||
/// with `monochrome` the first row is the mix the black ink gets, and cyan, magenta and
|
||||
/// yellow are cleared. `.pcraft` files from builds before #8047 have no such field and
|
||||
/// load as `None`; those builds ignore it, so they reopen a CMYK mixer as `matrix`
|
||||
/// (identity) and drop the ink rows on their next save.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
cmyk: Option<[[f32; 5]; 4]>,
|
||||
},
|
||||
/// A 3D LUT: `size`³ RGB triplets, red varying fastest (`((b·size + g)·size + r)·3`), in 0..=1.
|
||||
/// `lut` is None for a lookup Photoshop stores as an ICC profile (identity here).
|
||||
@@ -334,6 +345,9 @@ pub enum Adjustment {
|
||||
},
|
||||
}
|
||||
|
||||
/// The neutral CMYK Channel Mixer: each ink from itself at 100 %, no constant.
|
||||
pub const CMYK_MIXER_IDENTITY: [[f32; 5]; 4] = [[1.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0]];
|
||||
|
||||
impl Adjustment {
|
||||
pub fn label(&self) -> &str {
|
||||
match self {
|
||||
|
||||
@@ -189,26 +189,7 @@ pub fn from_params(kind: &str, p: &Value, base: Option<&Adjustment>, mode: Color
|
||||
preserve_luminosity: r.boolean("preserveLuminosity", p0)?,
|
||||
}
|
||||
}
|
||||
"channelMixer" => {
|
||||
let (mut matrix, mono0) = match base {
|
||||
Some(Adjustment::ChannelMixer { matrix, monochrome }) => (*matrix, *monochrome),
|
||||
_ => ([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], false),
|
||||
};
|
||||
let monochrome = r.boolean("monochrome", mono0)?;
|
||||
if monochrome && !mono0 && p.get("gray").is_none() {
|
||||
// Turning Monochrome on starts from Photoshop's grey mix.
|
||||
matrix[0] = [0.4, 0.4, 0.2, 0.0];
|
||||
}
|
||||
for (i, key) in ["red", "green", "blue"].iter().enumerate() {
|
||||
if let Some(v) = r.numbers(key, 4)? {
|
||||
matrix[i] = mixer_row(&v);
|
||||
}
|
||||
}
|
||||
if let Some(v) = r.numbers("gray", 4)? {
|
||||
matrix[0] = mixer_row(&v);
|
||||
}
|
||||
Adjustment::ChannelMixer { matrix, monochrome }
|
||||
}
|
||||
"channelMixer" => channel_mixer(&r, p, base, mode)?,
|
||||
"gradientMap" => {
|
||||
let (stops0, rev0, dither0, source0) = match base {
|
||||
Some(Adjustment::GradientMap { stops, reverse, dither, source }) => (stops.clone(), *reverse, *dither, source.clone()),
|
||||
@@ -327,7 +308,18 @@ pub fn to_params(adj: &Adjustment) -> Value {
|
||||
Adjustment::PhotoFilter { color, density, preserve_luminosity } => {
|
||||
json!({"color": hex(*color), "density": (density * 1000.0).round() / 10.0, "preserveLuminosity": preserve_luminosity})
|
||||
}
|
||||
Adjustment::ChannelMixer { matrix, monochrome } => {
|
||||
Adjustment::ChannelMixer { cmyk: Some(rows), monochrome, .. } => {
|
||||
let row = |r: &[f32; 5]| json!(r.map(|x| (x * 1000.0).round() / 10.0));
|
||||
let mut v = json!({"monochrome": monochrome});
|
||||
for (key, r) in MIXER_INKS.iter().zip(rows) {
|
||||
v[*key] = row(r);
|
||||
}
|
||||
if *monochrome {
|
||||
v["gray"] = row(&rows[0]);
|
||||
}
|
||||
v
|
||||
}
|
||||
Adjustment::ChannelMixer { matrix, monochrome, cmyk: None } => {
|
||||
let row = |r: &[f32; 4]| json!(r.map(|x| (x * 1000.0).round() / 10.0));
|
||||
let mut v = json!({"red": row(&matrix[0]), "green": row(&matrix[1]), "blue": row(&matrix[2]), "monochrome": monochrome});
|
||||
if *monochrome {
|
||||
@@ -449,14 +441,72 @@ fn merge(mut a: Value, b: Value) -> Value {
|
||||
a
|
||||
}
|
||||
|
||||
/// One Channel Mixer output row: every coefficient and the constant is a whole percentage.
|
||||
/// Scripted values round to the nearest whole percent before clamping, as the reference
|
||||
/// application measures (0.4 to 0, 0.5 to 1, 50.6 to 51, 300 to 200, #14414); halves round away
|
||||
/// from zero, which is what the dialog's own slider pass already does (`f32::round`).
|
||||
fn mixer_row(v: &[f32]) -> [f32; 4] {
|
||||
/// One Channel Mixer output row (RGB `[r, g, b, constant]` or ink `[c, m, y, k, constant]`):
|
||||
/// every coefficient and the constant is a whole percentage. Scripted values round to the nearest
|
||||
/// whole percent before clamping, as the reference application measures (0.4 to 0, 0.5 to 1,
|
||||
/// 50.6 to 51, 300 to 200, #14414); halves round away from zero, which is what the dialog's own
|
||||
/// slider pass already does (`f32::round`).
|
||||
fn mixer_row<const N: usize>(v: &[f32]) -> [f32; N] {
|
||||
std::array::from_fn(|i| v.get(i).copied().unwrap_or(0.0).round().clamp(-200.0, 200.0) / 100.0)
|
||||
}
|
||||
|
||||
/// Channel Mixer outputs of a CMYK mixer (each `[cyan, magenta, yellow, black, constant]` %).
|
||||
pub const MIXER_INKS: [&str; 4] = ["cyan", "magenta", "yellow", "black"];
|
||||
|
||||
/// Why a CMYK Channel Mixer refuses `monochrome: true` (#8047); the UI shows it on the disabled
|
||||
/// Monochrome checkbox.
|
||||
pub const MONOCHROME_CMYK_UNSUPPORTED: &str = "unsupported: Monochrome is not available for a CMYK Channel Mixer yet (no Photoshop sample to match)";
|
||||
|
||||
/// Channel Mixer: RGB outputs (`red`, `green`, `blue`, each `[red, green, blue, constant]` %) or,
|
||||
/// in CMYK documents or with CMYK keys, Photoshop's four ink outputs ([`MIXER_INKS`]); `gray` is
|
||||
/// the monochrome mix. Monochrome on a CMYK mixer is refused as unsupported
|
||||
/// ([`MONOCHROME_CMYK_UNSUPPORTED`]).
|
||||
fn channel_mixer(r: &Reader<'_>, p: &Value, base: Option<&Adjustment>, mode: ColorMode) -> Result<Adjustment> {
|
||||
let rgb_identity = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
|
||||
let (mut matrix, mono0, cmyk0) = match base {
|
||||
Some(Adjustment::ChannelMixer { matrix, monochrome, cmyk }) => (*matrix, *monochrome, *cmyk),
|
||||
_ => (rgb_identity, false, None),
|
||||
};
|
||||
// Only CMYK keys, a CMYK base or (with neither colour's keys) a CMYK document make CMYK outputs.
|
||||
let base_space = base.filter(|b| matches!(b, Adjustment::ChannelMixer { .. })).map(|_| if cmyk0.is_some() { ToneSpace::Cmyk } else { ToneSpace::Rgb });
|
||||
let cmyk = space_of(r, base_space, mode) == ToneSpace::Cmyk;
|
||||
let monochrome = r.boolean("monochrome", mono0)?;
|
||||
if cmyk {
|
||||
if monochrome {
|
||||
// No Photoshop sample of a monochrome CMYK mixer yet (#8047): its rendering and saved
|
||||
// layout would be guesses. An imported one still renders and saves back verbatim, but
|
||||
// can only be edited by turning Monochrome off.
|
||||
return Err(bad(r.cmd, MONOCHROME_CMYK_UNSUPPORTED));
|
||||
}
|
||||
let mut rows = cmyk0.unwrap_or(photocraft_doc::adjust::CMYK_MIXER_IDENTITY);
|
||||
for (i, key) in MIXER_INKS.iter().enumerate() {
|
||||
if let Some(v) = r.numbers(key, 5)? {
|
||||
rows[i] = mixer_row(&v);
|
||||
}
|
||||
}
|
||||
if let Some(v) = r.numbers("gray", 5)? {
|
||||
rows[0] = mixer_row(&v);
|
||||
}
|
||||
return Ok(Adjustment::ChannelMixer { matrix: if cmyk0.is_some() { matrix } else { rgb_identity }, monochrome, cmyk: Some(rows) });
|
||||
}
|
||||
if cmyk0.is_some() {
|
||||
matrix = rgb_identity;
|
||||
}
|
||||
if monochrome && !mono0 && p.get("gray").is_none() {
|
||||
// Turning Monochrome on starts from Photoshop's grey mix.
|
||||
matrix[0] = [0.4, 0.4, 0.2, 0.0];
|
||||
}
|
||||
for (i, key) in ["red", "green", "blue"].iter().enumerate() {
|
||||
if let Some(v) = r.numbers(key, 4)? {
|
||||
matrix[i] = mixer_row(&v);
|
||||
}
|
||||
}
|
||||
if let Some(v) = r.numbers("gray", 4)? {
|
||||
matrix[0] = mixer_row(&v);
|
||||
}
|
||||
Ok(Adjustment::ChannelMixer { matrix, monochrome, cmyk: None })
|
||||
}
|
||||
|
||||
fn hue_saturation(r: &Reader<'_>, base: Option<&Adjustment>) -> Result<Adjustment> {
|
||||
let (h, s, l, c, mut ranges) = match base {
|
||||
Some(Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges }) => (*hue, *saturation, *lightness, *colorize, ranges.clone()),
|
||||
|
||||
@@ -61,6 +61,75 @@ fn every_kind_round_trips_through_params() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Channel Mixer made in a CMYK document has Photoshop's four ink outputs, starting at
|
||||
/// identity (#8047); RGB and other documents keep red, green and blue.
|
||||
#[test]
|
||||
fn channel_mixer_outputs_follow_the_document_mode() {
|
||||
let ink = default_for("channelMixer", ColorMode::Cmyk).unwrap();
|
||||
assert!(matches!(ink, Adjustment::ChannelMixer { cmyk: Some(rows), monochrome: false, .. } if rows == photocraft_doc::adjust::CMYK_MIXER_IDENTITY));
|
||||
let p = to_params(&ink);
|
||||
assert!(MIXER_INKS.iter().all(|k| p.get(*k).is_some()) && p.get("red").is_none(), "{p}");
|
||||
assert_eq!(p["black"], json!([0.0, 0.0, 0.0, 100.0, 0.0]));
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab] {
|
||||
assert!(matches!(default_for("channelMixer", mode).unwrap(), Adjustment::ChannelMixer { cmyk: None, .. }), "{mode:?}");
|
||||
}
|
||||
// CMYK keys make ink outputs in any document; a partial update keeps the rest.
|
||||
let a = from_params("channelMixer", &json!({"magenta": [0, 100, 0, 0, -20]}), None, ColorMode::Rgb).unwrap();
|
||||
let Adjustment::ChannelMixer { cmyk: Some(rows), .. } = &a else { panic!("{a:?}") };
|
||||
assert_eq!(rows[1], [0.0, 1.0, 0.0, 0.0, -0.2]);
|
||||
assert_eq!(rows[3], [0.0, 0.0, 0.0, 1.0, 0.0]);
|
||||
let b = from_params("channelMixer", &json!({"black": [10, 10, 10, 90, 0]}), Some(&a), ColorMode::Cmyk).unwrap();
|
||||
assert!(matches!(&b, Adjustment::ChannelMixer { cmyk: Some(r), .. } if r[1] == rows[1] && r[3] == [0.1, 0.1, 0.1, 0.9, 0.0]));
|
||||
assert_eq!(from_params("channelMixer", &to_params(&b), None, ColorMode::Rgb).unwrap(), b);
|
||||
// RGB keys over a CMYK base switch back to RGB outputs.
|
||||
let rgb = from_params("channelMixer", &json!({"red": [50, 50, 0, 0]}), Some(&b), ColorMode::Cmyk).unwrap();
|
||||
assert!(matches!(rgb, Adjustment::ChannelMixer { cmyk: None, matrix, .. } if matrix[0] == [0.5, 0.5, 0.0, 0.0] && matrix[1] == [0.0, 1.0, 0.0, 0.0]));
|
||||
}
|
||||
|
||||
/// Monochrome on a CMYK Channel Mixer has no Photoshop sample yet (#8047), so turning it on is
|
||||
/// an unsupported error, never an inferred mixer: in a CMYK document, with CMYK keys, over a CMYK
|
||||
/// base, and over an imported monochrome CMYK mixer unless the edit turns Monochrome off. RGB
|
||||
/// mixers keep Monochrome.
|
||||
#[test]
|
||||
fn monochrome_cmyk_channel_mixer_is_refused_as_unsupported() {
|
||||
let ink = default_for("channelMixer", ColorMode::Cmyk).unwrap();
|
||||
let imported = Adjustment::ChannelMixer {
|
||||
matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
|
||||
monochrome: true,
|
||||
cmyk: Some([[0.3, 0.3, 0.3, 1.0, 0.0], [0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0]]),
|
||||
};
|
||||
let cases: [(Value, Option<&Adjustment>, ColorMode); 6] = [
|
||||
(json!({"monochrome": true}), None, ColorMode::Cmyk),
|
||||
(json!({"monochrome": true, "gray": [0, 0, 0, 100, 0]}), None, ColorMode::Cmyk),
|
||||
(json!({"monochrome": true, "cyan": [100, 0, 0, 0, 0]}), None, ColorMode::Rgb),
|
||||
(json!({"monochrome": true}), Some(&ink), ColorMode::Cmyk),
|
||||
(json!({"gray": [10, 10, 10, 90, 0]}), Some(&imported), ColorMode::Cmyk),
|
||||
(to_params(&imported), None, ColorMode::Cmyk),
|
||||
];
|
||||
for (p, base, mode) in cases {
|
||||
let err = from_params("channelMixer", &p, base, mode).expect_err(&format!("{p} over {base:?}"));
|
||||
assert!(matches!(&err, EngineError::BadParams { msg, .. } if msg == MONOCHROME_CMYK_UNSUPPORTED), "{err}");
|
||||
assert!(err.to_string().contains("unsupported"), "{err}");
|
||||
}
|
||||
// Turning an imported one's Monochrome off is a supported CMYK mixer again.
|
||||
let off = from_params("channelMixer", &json!({"monochrome": false}), Some(&imported), ColorMode::Cmyk).unwrap();
|
||||
assert!(matches!(off, Adjustment::ChannelMixer { cmyk: Some(_), monochrome: false, .. }), "{off:?}");
|
||||
// RGB keeps it, in any document.
|
||||
for mode in [ColorMode::Rgb, ColorMode::Cmyk] {
|
||||
let rgb = from_params("channelMixer", &json!({"monochrome": true, "red": [100, 0, 0, 0]}), None, mode).unwrap();
|
||||
assert!(matches!(rgb, Adjustment::ChannelMixer { cmyk: None, monochrome: true, .. }), "{mode:?}: {rgb:?}");
|
||||
}
|
||||
// The command refuses it and leaves the layer as it was.
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "cmyk", "background": "white"})).unwrap();
|
||||
s.execute("layer.newAdjustmentLayer.channelMixer", json!({})).unwrap();
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
let before = s.active().unwrap().doc.layer(id).unwrap().content.clone();
|
||||
let err = s.execute("layer.setAdjustment", json!({"layer": id.0, "monochrome": true})).unwrap_err();
|
||||
assert!(err.to_string().contains("unsupported"), "{err}");
|
||||
assert_eq!(s.active().unwrap().doc.layer(id).unwrap().content, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_reach_the_model() {
|
||||
basic_params_reach_the_model();
|
||||
@@ -71,7 +140,7 @@ fn basic_params_reach_the_model() {
|
||||
let a = from_params("colorBalance", &json!({"midtones": [50, 0, -200]}), None, ColorMode::Rgb).unwrap();
|
||||
assert_eq!(a, Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [50.0, 0.0, -100.0], highlights: [0.0; 3], preserve_luminosity: true });
|
||||
let a = from_params("channelMixer", &json!({"monochrome": true}), None, ColorMode::Rgb).unwrap();
|
||||
assert!(matches!(a, Adjustment::ChannelMixer { matrix, monochrome: true } if matrix[0] == [0.4, 0.4, 0.2, 0.0]));
|
||||
assert!(matches!(a, Adjustment::ChannelMixer { matrix, monochrome: true, .. } if matrix[0] == [0.4, 0.4, 0.2, 0.0]));
|
||||
let a = from_params("photoFilter", &json!({"filter": "cooling80", "density": 60}), None, ColorMode::Rgb).unwrap();
|
||||
assert!(matches!(a, Adjustment::PhotoFilter { color, density, .. } if color[2] == 1.0 && (density - 0.6).abs() < 1e-6));
|
||||
let a = from_params("blackWhite", &json!({"reds": 120, "tint": true}), None, ColorMode::Rgb).unwrap();
|
||||
@@ -118,6 +187,8 @@ fn bad_params_are_errors_not_panics() {
|
||||
("photoFilter", json!({"filter": "nope"})),
|
||||
("photoFilter", json!({"color": [1]})),
|
||||
("channelMixer", json!({"red": [1, 2, 3]})),
|
||||
("channelMixer", json!({"cyan": [1, 2, 3, 4]})),
|
||||
("channelMixer", json!({"black": [1, 2, 3, 4, "x"]})),
|
||||
("gradientMap", json!({"stops": [[0, "#000"]]})),
|
||||
("gradientMap", json!({"stops": 7})),
|
||||
("selectiveColor", json!({"method": 5})),
|
||||
|
||||
@@ -77,6 +77,8 @@ pub mod image_cmds;
|
||||
pub mod layer_copy_cmds;
|
||||
pub mod layer_css_cmds;
|
||||
#[cfg(test)]
|
||||
mod layer_duplicate_new_document_history_tests;
|
||||
#[cfg(test)]
|
||||
mod layer_from_background_name_tests;
|
||||
pub mod layer_label_cmds;
|
||||
pub mod layer_list_cmds;
|
||||
|
||||
@@ -149,7 +149,7 @@ fn starting_values_match_the_reference() {
|
||||
assert_eq!(adj("blackWhite"), Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None });
|
||||
let Adjustment::PhotoFilter { density, preserve_luminosity, .. } = adj("photoFilter") else { panic!() };
|
||||
assert!(close(density, 0.25) && preserve_luminosity);
|
||||
let Adjustment::ChannelMixer { matrix, monochrome } = adj("channelMixer") else { panic!() };
|
||||
let Adjustment::ChannelMixer { matrix, monochrome, .. } = adj("channelMixer") else { panic!() };
|
||||
assert!(!monochrome);
|
||||
let want = [[0.8, 0.1, 0.1, 0.05], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
|
||||
assert!(matrix.iter().flatten().zip(want.iter().flatten()).all(|(a, b)| close(*a, *b)), "{matrix:?}");
|
||||
|
||||
@@ -23,6 +23,8 @@ use serde_json::{Value, json};
|
||||
use crate::commands::CommandSpec;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
#[cfg(test)]
|
||||
mod convert_profile_fogra39_tests;
|
||||
#[cfg(test)]
|
||||
mod convert_profile_same_tests;
|
||||
mod profile_dither;
|
||||
@@ -139,6 +141,9 @@ pub struct ColorSettings {
|
||||
/// Monitor profile the canvas is displayed in: `auto` (the main display's profile when the
|
||||
/// platform supplies it, else sRGB), a built-in RGB profile id or an `.icc` path.
|
||||
pub monitor_profile: String,
|
||||
/// The Settings menu: the named setup these values come from (one of
|
||||
/// [`COLOR_SETTINGS_PRESETS`]), or [`CUSTOM_SETTINGS`] once anything differs (#14229).
|
||||
pub preset: String,
|
||||
}
|
||||
|
||||
impl Default for ColorSettings {
|
||||
@@ -160,10 +165,142 @@ impl Default for ColorSettings {
|
||||
blend_text_gamma: photocraft_compose::psblend::TEXT_GAMMA,
|
||||
spot_dot_gain: photocraft_compose::multichannel::SPOT_DOT_GAIN,
|
||||
monitor_profile: "auto".into(),
|
||||
// PhotoCraft's defaults match none of the named setups.
|
||||
preset: CUSTOM_SETTINGS.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Settings menu's entry for values that match no named setup.
|
||||
pub const CUSTOM_SETTINGS: &str = "Custom";
|
||||
|
||||
/// The named setups of Color Settings' Settings menu, in menu order (#14229).
|
||||
pub const COLOR_SETTINGS_PRESETS: [&str; 13] = [
|
||||
"Europe General Purpose 3",
|
||||
"Europe Prepress 3",
|
||||
"Europe Web/Internet 2",
|
||||
"Monitor Color",
|
||||
"Japan Color for Newspaper",
|
||||
"Japan General Purpose 2",
|
||||
"Japan Magazine Advertisement Color",
|
||||
"Japan Prepress 2",
|
||||
"Japan Web/Internet",
|
||||
"North America General Purpose 2",
|
||||
"North America Newspaper",
|
||||
"North America Prepress 2",
|
||||
"North America Web/Internet",
|
||||
];
|
||||
|
||||
/// The named setup whose working RGB follows the monitor profile.
|
||||
const MONITOR_COLOR: &str = "Monitor Color";
|
||||
|
||||
/// The RGB entry of "Monitor Color": the monitor profile (see [`ColorState::monitor_rgb_for`]).
|
||||
const MONITOR_RGB: &str = "monitor";
|
||||
|
||||
/// What one named setup sets. Spaces PhotoCraft doesn't ship stand in for the closest built-in:
|
||||
/// the wide-gamut RGB is `adobe-rgb-compat`; Coated FOGRA39 is `coated-fogra39`, every other
|
||||
/// press (SWOP, Japan Color, Japan Web Coated (Ad), US Newsprint) the generic `coated-cmyk`
|
||||
/// (#3499); Dot Gain 15 % and 25 % gray the Dot Gain 20 %-compatible gray. Spot dot gains are exact.
|
||||
struct SettingsPreset {
|
||||
name: &'static str,
|
||||
rgb: &'static str,
|
||||
cmyk: &'static str,
|
||||
gray: &'static str,
|
||||
spot: f32,
|
||||
/// RGB, CMYK, Gray.
|
||||
policies: [Policy; 3],
|
||||
/// Ask When Opening (mismatch), Ask When Pasting, Missing Profiles: Ask When Opening.
|
||||
ask: [bool; 3],
|
||||
intent: Intent,
|
||||
}
|
||||
|
||||
/// A row of [`SETTINGS_PRESETS`], in the table's column order.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
const fn preset(
|
||||
name: &'static str,
|
||||
rgb: &'static str,
|
||||
cmyk: &'static str,
|
||||
gray: &'static str,
|
||||
spot: f32,
|
||||
policies: [Policy; 3],
|
||||
ask: [bool; 3],
|
||||
intent: Intent,
|
||||
) -> SettingsPreset {
|
||||
SettingsPreset { name, rgb, cmyk, gray, spot, policies, ask, intent }
|
||||
}
|
||||
|
||||
const SETTINGS_PRESETS: [SettingsPreset; 13] = {
|
||||
use Intent::{Perceptual as PER, RelativeColorimetric as REL};
|
||||
use Policy::{Convert as C, Off, Preserve as P};
|
||||
const SRGB: &str = "srgb";
|
||||
const WIDE: &str = "adobe-rgb-compat";
|
||||
const FOGRA39: &str = "coated-fogra39";
|
||||
const COATED: &str = "coated-cmyk";
|
||||
const DOT_GAIN: &str = "dot-gain-20-compat";
|
||||
const GAMMA_22: &str = "gray-gamma-2.2";
|
||||
[
|
||||
preset("Europe General Purpose 3", SRGB, FOGRA39, DOT_GAIN, 15.0, [P, P, P], [false, false, false], REL),
|
||||
preset("Europe Prepress 3", WIDE, FOGRA39, DOT_GAIN, 15.0, [P, P, P], [true, true, true], REL),
|
||||
preset("Europe Web/Internet 2", SRGB, FOGRA39, GAMMA_22, 15.0, [C, P, P], [true, true, false], REL),
|
||||
preset("Monitor Color", MONITOR_RGB, COATED, GAMMA_22, 20.0, [Off, Off, Off], [true, false, false], REL),
|
||||
preset("Japan Color for Newspaper", WIDE, COATED, DOT_GAIN, 25.0, [P, P, P], [true, true, true], PER),
|
||||
preset("Japan General Purpose 2", SRGB, COATED, DOT_GAIN, 15.0, [P, P, P], [false, false, false], PER),
|
||||
preset("Japan Magazine Advertisement Color", WIDE, COATED, DOT_GAIN, 15.0, [P, P, P], [true, true, true], PER),
|
||||
preset("Japan Prepress 2", WIDE, COATED, DOT_GAIN, 15.0, [P, P, P], [true, true, true], PER),
|
||||
preset("Japan Web/Internet", SRGB, COATED, GAMMA_22, 15.0, [C, P, P], [true, true, false], PER),
|
||||
preset("North America General Purpose 2", SRGB, COATED, DOT_GAIN, 20.0, [P, P, P], [false, false, false], REL),
|
||||
preset("North America Newspaper", WIDE, COATED, DOT_GAIN, 25.0, [P, P, P], [true, true, true], PER),
|
||||
preset("North America Prepress 2", WIDE, COATED, DOT_GAIN, 20.0, [P, P, P], [true, true, true], REL),
|
||||
preset("North America Web/Internet", SRGB, COATED, GAMMA_22, 20.0, [C, P, P], [true, true, false], REL),
|
||||
]
|
||||
};
|
||||
|
||||
/// `from` with the named setup `name` applied (#14229): its working spaces, policies, Ask
|
||||
/// boxes, intent, and Black Point Compensation and Dither on; Blend Text Colors Using Gamma on
|
||||
/// at 1.45, as a scripted preset sets it. "Monitor Color" takes `monitor_rgb` as its working RGB.
|
||||
/// `None` for a name that isn't one of [`COLOR_SETTINGS_PRESETS`].
|
||||
pub fn preset_setup(from: &ColorSettings, name: &str, monitor_rgb: &str) -> Option<ColorSettings> {
|
||||
let p = SETTINGS_PRESETS.iter().find(|p| p.name == name)?;
|
||||
let rgb = if p.rgb == MONITOR_RGB { monitor_rgb } else { p.rgb };
|
||||
let [policy_rgb, policy_cmyk, policy_gray] = p.policies;
|
||||
let [ask_on_mismatch, ask_on_paste, ask_on_missing] = p.ask;
|
||||
Some(ColorSettings {
|
||||
working_rgb: rgb.into(),
|
||||
working_cmyk: p.cmyk.into(),
|
||||
working_gray: p.gray.into(),
|
||||
policy_rgb,
|
||||
policy_cmyk,
|
||||
policy_gray,
|
||||
ask_on_mismatch,
|
||||
ask_on_paste,
|
||||
ask_on_missing,
|
||||
intent: p.intent.id().into(),
|
||||
bpc: true,
|
||||
dither: true,
|
||||
blend_text_gamma: photocraft_compose::psblend::TEXT_GAMMA,
|
||||
spot_dot_gain: p.spot,
|
||||
preset: p.name.into(),
|
||||
// The rest (the monitor profile) is not part of a setup. A setting a setup does
|
||||
// set belongs above, and in `same_setup`.
|
||||
..from.clone()
|
||||
})
|
||||
}
|
||||
|
||||
/// Is `name` an entry of the Settings menu (a named setup or Custom)?
|
||||
pub fn is_settings_preset(name: &str) -> bool {
|
||||
name == CUSTOM_SETTINGS || COLOR_SETTINGS_PRESETS.contains(&name)
|
||||
}
|
||||
|
||||
/// Do `a` and `b` agree on everything a named setup sets? (Blend Text Colors Using Gamma and the
|
||||
/// monitor profile are not part of it.)
|
||||
fn same_setup(a: &ColorSettings, b: &ColorSettings) -> bool {
|
||||
(&a.working_rgb, &a.working_cmyk, &a.working_gray, a.spot_dot_gain.to_bits())
|
||||
== (&b.working_rgb, &b.working_cmyk, &b.working_gray, b.spot_dot_gain.to_bits())
|
||||
&& (a.policy_rgb, a.policy_cmyk, a.policy_gray) == (b.policy_rgb, b.policy_cmyk, b.policy_gray)
|
||||
&& (a.ask_on_mismatch, a.ask_on_paste, a.ask_on_missing) == (b.ask_on_mismatch, b.ask_on_paste, b.ask_on_missing)
|
||||
&& (&a.intent, a.bpc, a.dither) == (&b.intent, b.bpc, b.dither)
|
||||
}
|
||||
|
||||
impl ColorSettings {
|
||||
pub fn intent(&self) -> Intent {
|
||||
Intent::parse(&self.intent).unwrap_or(Intent::RelativeColorimetric)
|
||||
@@ -213,6 +350,9 @@ pub fn validate_settings(c: &ColorSettings) -> std::result::Result<(), String> {
|
||||
if !(c.spot_dot_gain.is_finite() && (0.0..=photocraft_compose::multichannel::MAX_SPOT_DOT_GAIN).contains(&c.spot_dot_gain)) {
|
||||
return Err(format!("spot dot gain must be 0..{} %", photocraft_compose::multichannel::MAX_SPOT_DOT_GAIN));
|
||||
}
|
||||
if !is_settings_preset(&c.preset) {
|
||||
return Err(format!("unknown preset `{}` ({CUSTOM_SETTINGS}, {})", c.preset, COLOR_SETTINGS_PRESETS.join(", ")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -251,6 +391,30 @@ impl ColorState {
|
||||
.unwrap_or_else(|| working_profile(mode))
|
||||
}
|
||||
|
||||
/// The working RGB "Monitor Color" sets, with Monitor Profile at `monitor_profile`: that
|
||||
/// profile when it names one; for `auto`, the built-in matching the main display's profile,
|
||||
/// sRGB when none does (a display profile is only bytes here, so it can't be a working
|
||||
/// space spec).
|
||||
pub fn monitor_rgb_for(&self, monitor_profile: &str) -> String {
|
||||
if !(monitor_profile.is_empty() || monitor_profile == "auto") {
|
||||
return monitor_profile.to_string();
|
||||
}
|
||||
let display = self.main_display.and_then(|id| self.displays.iter().find(|d| d.id == id)).or(self.displays.first());
|
||||
let description = display.and_then(|d| d.icc.as_deref()).and_then(|b| Profile::parse(b).ok()).map(|p| p.description);
|
||||
description
|
||||
.and_then(|n| Builtin::from_profile_name(&n))
|
||||
.filter(|b| b.profile().color_space == ColorSpace::Rgb)
|
||||
.unwrap_or(Builtin::Srgb)
|
||||
.id()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// `from` with the named setup `name` applied (see [`preset_setup`]), its Monitor RGB that
|
||||
/// of `from`'s Monitor Profile ([`ColorState::monitor_rgb_for`]).
|
||||
pub fn preset_settings(&self, from: &ColorSettings, name: &str) -> Option<ColorSettings> {
|
||||
preset_setup(from, name, &self.monitor_rgb_for(&from.monitor_profile))
|
||||
}
|
||||
|
||||
/// Resolve a profile spec, reading "working…" specs from Color Settings.
|
||||
pub fn resolve(&self, spec: &str, doc: Option<&Document>, mode: Option<ColorMode>) -> Result<Arc<Profile>> {
|
||||
match spec {
|
||||
@@ -1265,6 +1429,32 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("reset").and_then(Value::as_bool) == Some(true) {
|
||||
next = ColorSettings::default();
|
||||
}
|
||||
// Settings menu (#14229): a named setup loads its values; the params below then change
|
||||
// them, and the name stays only while they still match the setup.
|
||||
let preset = match p.get("preset") {
|
||||
None => None,
|
||||
Some(Value::String(name)) if is_settings_preset(name) => Some(name.as_str()),
|
||||
Some(v) => {
|
||||
return Err(EngineError::BadParams {
|
||||
cmd: cmd.into(),
|
||||
msg: format!("`preset` must be {CUSTOM_SETTINGS} or one of: {} (got {v})", COLOR_SETTINGS_PRESETS.join(", ")),
|
||||
});
|
||||
}
|
||||
};
|
||||
let setup = match preset {
|
||||
Some(name) if name != CUSTOM_SETTINGS => {
|
||||
// "Monitor Color" follows a Monitor Profile changed in the same call.
|
||||
let mut from = next.clone();
|
||||
if let Some(m) = p.get("monitorProfile").and_then(Value::as_str) {
|
||||
from.monitor_profile = m.to_string();
|
||||
}
|
||||
s.color().preset_settings(&from, name)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(setup) = &setup {
|
||||
next = setup.clone();
|
||||
}
|
||||
let str_of = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string);
|
||||
if let Some(v) = str_of("workingRgb") {
|
||||
next.working_rgb = v;
|
||||
@@ -1317,6 +1507,19 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`spotDotGain` must be a dot gain of 0..{max} %") })?;
|
||||
next.spot_dot_gain = g as f32;
|
||||
}
|
||||
next.preset = match (preset, &setup) {
|
||||
(_, Some(setup)) if same_setup(&next, setup) => setup.preset.clone(),
|
||||
(Some(_), _) => CUSTOM_SETTINGS.into(),
|
||||
// No preset given: any change but the monitor profile makes the values Custom.
|
||||
(None, _) => {
|
||||
let old = &s.color().settings;
|
||||
let unchanged = ColorSettings { monitor_profile: old.monitor_profile.clone(), preset: old.preset.clone(), ..next.clone() } == *old;
|
||||
// "Monitor Color" takes its working RGB from the monitor profile, so a new monitor
|
||||
// profile keeps the name only while the setup still is what it would set now.
|
||||
let still_monitor_color = old.preset != MONITOR_COLOR || s.color().preset_settings(&next, MONITOR_COLOR).is_some_and(|m| same_setup(&next, &m));
|
||||
if unchanged && still_monitor_color && is_settings_preset(&old.preset) { old.preset.clone() } else { CUSTOM_SETTINGS.into() }
|
||||
}
|
||||
};
|
||||
validate_settings(&next).map_err(|msg| EngineError::BadParams { cmd: cmd.into(), msg })?;
|
||||
if next != s.color().settings {
|
||||
photocraft_compose::psblend::set_text_gamma(next.blend_text_gamma);
|
||||
@@ -1329,6 +1532,7 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let desc = |m: ColorMode| s.color().working(m).description.clone();
|
||||
Ok(json!({
|
||||
"settings": c,
|
||||
"preset": c.preset,
|
||||
"working": {"rgb": desc(ColorMode::Rgb), "cmyk": desc(ColorMode::Cmyk), "gray": desc(ColorMode::Grayscale)},
|
||||
"monitor": s.color().monitor().description,
|
||||
"monitorDetected": !s.color().displays.is_empty(),
|
||||
@@ -1432,7 +1636,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"edit.colorSettings",
|
||||
"Color Settings…",
|
||||
["Edit"],
|
||||
r##"{"workingRgb":"srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020","workingCmyk":"coated-cmyk","workingGray":"dot-gain-20-compat|sgray|gray-gamma-2.2","policyRgb":"preserve|convert|off","policyCmyk":"preserve|convert|off","policyGray":"preserve|convert|off","askOnMismatch":bool=true,"askOnPaste":bool=true,"askOnMissing":bool=false,"intent":"relative|perceptual|saturation|absolute","blendTextGamma":1.0..2.2|bool=1.45,"spotDotGain":0..49=20,"bpc":bool=true,"dither":bool=true,"monitorProfile":"auto|srgb|display-p3|adobe-rgb-compat|prophoto-compat|rec2020","reset":bool=false} (spotDotGain = the Spot working space: the dot gain, in % at a 50 % dot, that spot channel previews add, as Photoshop's Spot menu (Dot Gain 10–30 %, or a custom value); working spaces and the monitor profile also accept .icc paths; monitor `auto` = the main display's profile when the platform provides it, else sRGB; the reply's `monitorStatus` says which profile is in use and why: source auto|manual|fallback, reason)"##,
|
||||
r##"{"preset":"Custom|Europe General Purpose 3|Europe Prepress 3|Europe Web/Internet 2|Monitor Color|Japan Color for Newspaper|Japan General Purpose 2|Japan Magazine Advertisement Color|Japan Prepress 2|Japan Web/Internet|North America General Purpose 2|North America Newspaper|North America Prepress 2|North America Web/Internet","workingRgb":"srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020","workingCmyk":"coated-cmyk|coated-fogra39","workingGray":"dot-gain-20-compat|sgray|gray-gamma-2.2","policyRgb":"preserve|convert|off","policyCmyk":"preserve|convert|off","policyGray":"preserve|convert|off","askOnMismatch":bool=true,"askOnPaste":bool=true,"askOnMissing":bool=false,"intent":"relative|perceptual|saturation|absolute","blendTextGamma":1.0..2.2|bool=1.45,"spotDotGain":0..49=20,"bpc":bool=true,"dither":bool=true,"monitorProfile":"auto|srgb|display-p3|adobe-rgb-compat|prophoto-compat|rec2020","reset":bool=false} (preset = the Settings menu: a named setup sets the working spaces, policies, Ask boxes and intent, Black Point Compensation and Dither on and Blend Text Colors Using Gamma 1.45, then the other params change those values; the reply's `preset` is that name while the values still match it, else Custom, as after any change made without `preset`; spotDotGain = the Spot working space: the dot gain, in % at a 50 % dot, that spot channel previews add, as Photoshop's Spot menu (Dot Gain 10–30 %, or a custom value); working spaces and the monitor profile also accept .icc paths; monitor `auto` = the main display's profile when the platform provides it, else sRGB; the reply's `monitorStatus` says which profile is in use and why: source auto|manual|fallback, reason)"##,
|
||||
always,
|
||||
color_settings,
|
||||
true,
|
||||
@@ -1736,6 +1940,10 @@ mod tests {
|
||||
#[path = "assign_profile_enabled_modes_tests.rs"]
|
||||
mod assign_profile_enabled_modes_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../color_settings_presets_tests.rs"]
|
||||
mod color_settings_presets_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod settings_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! #14267: Convert to Profile from sRGB to the built-in Coated FOGRA39 gives the reference
|
||||
//! application's inks for each intent, and Perceptual and Saturation separate differently.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Inks (CMYK %) the reference application gives for an sRGB patch, per intent: relative +
|
||||
/// BPC, relative, perceptual, saturation, absolute (Convert to Profile, dither on).
|
||||
const REFERENCE: [(&str, [[f32; 4]; 5]); 3] = [
|
||||
("#c81e1e", [[14.5, 97.7, 95.3, 4.3], [13.3, 100.0, 100.0, 5.5], [18.0, 96.9, 92.9, 8.6], [14.9, 100.0, 100.0, 5.9], [8.6, 100.0, 100.0, 2.4]]),
|
||||
("#1e3cc8", [[91.8, 75.3, 0.0, 0.0], [94.5, 76.5, 0.0, 0.0], [94.5, 77.7, 0.0, 0.0], [93.7, 76.9, 0.0, 0.0], [92.6, 74.9, 0.0, 0.0]]),
|
||||
("#808080", [[49.0, 38.4, 38.4, 20.0], [49.8, 39.2, 38.8, 21.2], [49.0, 38.4, 38.4, 20.0], [49.0, 38.4, 38.4, 20.0], [46.7, 36.9, 38.4, 18.4]]),
|
||||
];
|
||||
|
||||
const INTENTS: [(&str, bool); 5] = [("relative", true), ("relative", false), ("perceptual", true), ("saturation", true), ("absolute", false)];
|
||||
|
||||
/// The inks of an 8-bit sRGB document filled with `background`, converted to Coated FOGRA39.
|
||||
fn separate(background: &str, intent: &str, bpc: bool) -> [f32; 4] {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "background": background})).unwrap();
|
||||
s.execute("edit.assignProfile", json!({"profile": "srgb"})).unwrap();
|
||||
s.execute("edit.convertToProfile", json!({"profile": "coated-fogra39", "intent": intent, "bpc": bpc, "dither": false})).unwrap();
|
||||
let doc = &s.active().unwrap().doc;
|
||||
assert_eq!(doc.mode, ColorMode::Cmyk);
|
||||
let px = doc.layers[0].surface().unwrap().pixel(4, 4);
|
||||
[px[0], px[1], px[2], px[3]].map(|v| v * 100.0)
|
||||
}
|
||||
|
||||
/// Within 2 % per ink, except Saturation red: that patch lies between nodes of the profile's
|
||||
/// table that are clipped to the magenta–yellow edge and nodes that are not, which costs 2.2 %
|
||||
/// (a finer table closes it, at three times the profile size). It is held to 2.5 %.
|
||||
#[test]
|
||||
fn srgb_to_fogra39_matches_the_reference_inks() {
|
||||
let mut failures = Vec::new();
|
||||
for (background, want) in REFERENCE {
|
||||
for ((intent, bpc), want) in INTENTS.into_iter().zip(want) {
|
||||
let got = separate(background, intent, bpc);
|
||||
let limit = if (background, intent) == ("#c81e1e", "saturation") { 2.5 } else { 2.0 };
|
||||
// A NaN ink compares false with `>`, so it is failed explicitly.
|
||||
if (0..4).any(|i| (got[i] - want[i]).abs().is_nan() || (got[i] - want[i]).abs() > limit) {
|
||||
failures.push(format!("{background} {intent} bpc {bpc}: {got:.1?}, reference {want:?}, limit {limit}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{failures:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perceptual_and_saturation_separate_differently() {
|
||||
let (perceptual, saturation) = (separate("#c81e1e", "perceptual", true), separate("#c81e1e", "saturation", true));
|
||||
assert!(saturation[1] > perceptual[1] + 1.0 && saturation[2] > perceptual[2] + 1.0, "perceptual {perceptual:?}, saturation {saturation:?}");
|
||||
}
|
||||
@@ -311,7 +311,7 @@ use content_aware_scale::content_aware_scale;
|
||||
pub use fade::{FadePreview, fade_preview, fade_surface};
|
||||
use fade::{can_fade, fade};
|
||||
pub use find_replace::find_matches;
|
||||
use find_replace::{find_replace, has_type_layer};
|
||||
use find_replace::{can_find_replace, find_replace};
|
||||
pub(crate) use presets::current_path;
|
||||
pub use presets::{PRESET_FORMAT, PresetFile};
|
||||
use presets::{can_define_shape, define_brush_preset, define_custom_shape, preset_manager};
|
||||
@@ -378,7 +378,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Edit"],
|
||||
None,
|
||||
r##"{"find":text,"replace":text,"action":"changeAll|find|change|changeFind","caseSensitive":bool=false,"wholeWord":bool=false,"forward":bool=true,"allLayers":bool=true}"##,
|
||||
has_type_layer,
|
||||
can_find_replace,
|
||||
find_replace
|
||||
),
|
||||
spec!(
|
||||
|
||||
@@ -55,9 +55,15 @@ fn start_index(doc: &Document, layers: &[LayerId], active: Option<LayerId>) -> u
|
||||
walk.iter().skip(active_walk + 1).find_map(|(_, _, l)| layers.iter().position(|id| *id == l.id)).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub(super) fn has_type_layer(s: &Session) -> std::result::Result<(), String> {
|
||||
pub(super) fn can_find_replace(s: &Session) -> std::result::Result<(), String> {
|
||||
let d = s.active().ok_or("no document open")?;
|
||||
if type_layers(&d.doc).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) }
|
||||
// A document without type keeps the menu available. Documents with only locked type
|
||||
// retain their existing refusal.
|
||||
if type_layers(&d.doc).is_empty() && d.doc.walk().iter().any(|(_, _, layer)| matches!(layer.content, LayerContent::Text(_))) {
|
||||
Err("the document has no type layers".into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -198,3 +204,7 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
other => Err(bad(cmd, format!("unknown action `{other}` (find|change|changeFind|changeAll)"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "find_replace_enabled_tests.rs"]
|
||||
mod enabled_tests;
|
||||
@@ -0,0 +1,62 @@
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
const COMMAND: &str = "edit.findAndReplaceText";
|
||||
|
||||
#[test]
|
||||
fn find_replace_without_type_is_enabled_and_leaves_the_document_unchanged() {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let revision = s.active().unwrap().revision;
|
||||
let history = s.active().unwrap().history.entries();
|
||||
assert!(s.is_enabled(COMMAND), "{depth}-bit document without type");
|
||||
for action in ["changeAll", "find", "change", "changeFind"] {
|
||||
let reply = s.execute(COMMAND, json!({"find": "word", "replace": "other", "action": action})).unwrap();
|
||||
match action {
|
||||
"changeAll" => assert_eq!(reply, json!({"count": 0, "layers": 0})),
|
||||
"change" => assert_eq!(reply, json!({"changed": null})),
|
||||
_ => assert_eq!(reply, json!({"found": null, "changed": null})),
|
||||
}
|
||||
let st = s.active().unwrap();
|
||||
assert!(Arc::ptr_eq(&before, &st.doc));
|
||||
assert_eq!(st.revision, revision);
|
||||
assert_eq!(st.history.entries(), history);
|
||||
}
|
||||
assert!(s.execute(COMMAND, json!({})).is_err(), "the command still requires a search term");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_replace_needs_a_document_and_preserves_locked_type_refusal() {
|
||||
let mut s = crate::session();
|
||||
assert!(!s.is_enabled(COMMAND));
|
||||
assert!(s.execute(COMMAND, json!({"find": "word"})).is_err());
|
||||
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
let layer = s.execute("type.create", json!({"text": "word", "size": 8})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.setProps", json!({"layer": layer, "locked": true})).unwrap();
|
||||
assert!(!s.is_enabled(COMMAND));
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
assert!(s.execute(COMMAND, json!({"find": "word", "replace": "other"})).is_err());
|
||||
assert!(Arc::ptr_eq(&before, &s.active().unwrap().doc));
|
||||
|
||||
s.execute("layer.setProps", json!({"layer": layer, "locked": false})).unwrap();
|
||||
assert!(s.is_enabled(COMMAND));
|
||||
assert_eq!(s.execute(COMMAND, json!({"find": "word", "replace": "other"})).unwrap(), json!({"count": 1, "layers": 1}));
|
||||
assert!(s.undo());
|
||||
let content = &s.active().unwrap().doc.layer(LayerId(layer)).unwrap().content;
|
||||
assert!(matches!(content, LayerContent::Text(text) if text.text == "word"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_replace_empty_document_without_an_active_layer_is_a_noop() {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
let st = s.active_mut().unwrap();
|
||||
Arc::make_mut(st.doc_mut()).layers.clear();
|
||||
st.set_active_layer(None);
|
||||
st.selection_mut().clear();
|
||||
assert!(s.is_enabled(COMMAND));
|
||||
assert_eq!(s.execute(COMMAND, json!({"find": "word", "allLayers": false})).unwrap(), json!({"count": 0, "layers": 0}));
|
||||
}
|
||||
@@ -776,7 +776,7 @@ fn find_matches_cases() {
|
||||
#[test]
|
||||
fn find_and_replace_across_type_layers() {
|
||||
let mut s = session(8);
|
||||
assert!(!s.is_enabled("edit.findAndReplaceText"));
|
||||
assert!(s.is_enabled("edit.findAndReplaceText"));
|
||||
s.execute("type.create", json!({"text": "Hello world", "x": 4, "y": 20, "size": 12})).unwrap();
|
||||
s.execute("type.create", json!({"text": "world peace, World", "x": 4, "y": 40, "size": 12})).unwrap();
|
||||
let r = s.execute("edit.findAndReplaceText", json!({"find": "world", "replace": "planet"})).unwrap();
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::EngineError;
|
||||
|
||||
const COMMAND: &str = "file.scripts.imageProcessor";
|
||||
const NO_SOURCE: &str = "There were no source files that could be opened by PhotoCraft.";
|
||||
|
||||
fn settings(input: &Path, output: &Path, per_format: bool) -> Value {
|
||||
let mut params = json!({"input": input, "output": output});
|
||||
if per_format {
|
||||
params["jpeg"] = json!({});
|
||||
params["tiff"] = json!({});
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
fn write_image(path: &Path) -> std::io::Result<()> {
|
||||
fs::write(path, b"P6\n2 1\n255\n\xff\0\0\0\xff\0")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_empty_non_image_and_corrupt_sources_report_no_openable_files() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let input = root.path().join("input");
|
||||
let output = root.path().join("output");
|
||||
fs::create_dir(&input).unwrap();
|
||||
let mut session = crate::session();
|
||||
|
||||
for per_format in [false, true] {
|
||||
assert_eq!(session.execute(COMMAND, settings(Path::new(""), &output, per_format)), Err(EngineError::Other(NO_SOURCE.into())));
|
||||
}
|
||||
|
||||
for file in [None, Some("notes.txt"), Some("broken.jpg")] {
|
||||
if let Some(file) = file {
|
||||
fs::write(input.join(file), b"not an image").unwrap();
|
||||
}
|
||||
for per_format in [false, true] {
|
||||
assert_eq!(session.execute(COMMAND, settings(&input, &output, per_format)), Err(EngineError::Other(NO_SOURCE.into())));
|
||||
}
|
||||
assert!(!output.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_processor_skips_non_images_and_can_find_images_in_subfolders() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let input = root.path().join("input");
|
||||
let nested = input.join("nested");
|
||||
fs::create_dir_all(&nested).unwrap();
|
||||
fs::write(input.join("notes.txt"), b"not an image").unwrap();
|
||||
fs::write(nested.join("manifest.txt"), b"not an image").unwrap();
|
||||
write_image(&nested.join("test.ppm")).unwrap();
|
||||
let mut session = crate::session();
|
||||
|
||||
for per_format in [false, true] {
|
||||
let output = root.path().join(if per_format { "multi" } else { "single" });
|
||||
let mut params = settings(&input, &output, per_format);
|
||||
assert_eq!(session.execute(COMMAND, params.clone()), Err(EngineError::Other(NO_SOURCE.into())));
|
||||
params["includeSubfolders"] = json!(true);
|
||||
let result = session.execute(COMMAND, params).unwrap();
|
||||
let mut expected = vec![output.join("nested/test.jpg")];
|
||||
if per_format {
|
||||
expected.push(output.join("nested/test.tif"));
|
||||
}
|
||||
let files: Vec<PathBuf> = serde_json::from_value(result["files"].clone()).unwrap();
|
||||
assert_eq!(files, expected);
|
||||
assert_eq!(result["errors"], json!([]));
|
||||
for path in expected {
|
||||
let image = photocraft_io::import(&path.to_string_lossy(), &fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!((image.document.size.width, image.document.size.height), (2, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opened_image_can_still_report_a_processing_or_write_failure() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let input = root.path().join("input");
|
||||
let output = root.path().join("output");
|
||||
fs::create_dir(&input).unwrap();
|
||||
write_image(&input.join("test.ppm")).unwrap();
|
||||
fs::write(&output, b"not a directory").unwrap();
|
||||
let mut session = crate::session();
|
||||
for per_format in [false, true] {
|
||||
let result = session.execute(COMMAND, settings(&input, &output, per_format)).unwrap();
|
||||
assert_eq!(result["files"], json!([]));
|
||||
let errors = result["errors"].as_array().unwrap();
|
||||
assert_eq!(errors.len(), if per_format { 2 } else { 1 });
|
||||
assert!(errors.iter().all(|error| error["file"] == json!(input.join("test.ppm"))));
|
||||
}
|
||||
assert_eq!(fs::read(&output).unwrap(), b"not a directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_paths_and_missing_open_documents_keep_their_own_errors() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let missing = root.path().join("missing");
|
||||
let output = root.path().join("output");
|
||||
let mut session = crate::session();
|
||||
for per_format in [false, true] {
|
||||
let params = settings(&missing, &output, per_format);
|
||||
let error = session.execute(COMMAND, params.clone()).unwrap_err().to_string();
|
||||
assert!(error.contains(&missing.to_string_lossy().to_string()), "{error}");
|
||||
assert_ne!(error, NO_SOURCE);
|
||||
for source in ["current", "open"] {
|
||||
let mut params = params.clone();
|
||||
params["source"] = json!(source);
|
||||
assert_eq!(session.execute(COMMAND, params), Err(EngineError::NoDocument));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_valid_and_corrupt_images_keep_the_corrupt_file_report() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let input = root.path().join("input");
|
||||
fs::create_dir(&input).unwrap();
|
||||
let corrupt = input.join("broken.jpg");
|
||||
fs::write(&corrupt, b"not an image").unwrap();
|
||||
write_image(&input.join("test.ppm")).unwrap();
|
||||
let mut session = crate::session();
|
||||
for per_format in [false, true] {
|
||||
let output = root.path().join(if per_format { "multi" } else { "single" });
|
||||
let result = session.execute(COMMAND, settings(&input, &output, per_format)).unwrap();
|
||||
let mut expected = vec![output.join("test.jpg")];
|
||||
if per_format {
|
||||
expected.push(output.join("test.tif"));
|
||||
}
|
||||
let files: Vec<PathBuf> = serde_json::from_value(result["files"].clone()).unwrap();
|
||||
assert_eq!(files, expected);
|
||||
let errors = result["errors"].as_array().unwrap();
|
||||
assert_eq!(errors.len(), if per_format { 2 } else { 1 });
|
||||
assert!(errors.iter().all(|error| error["file"] == json!(corrupt)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_explicit_inputs_error_and_invalid_recursion_keeps_its_diagnostic() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let output = root.path().join("output");
|
||||
let mut session = crate::session();
|
||||
for per_format in [false, true] {
|
||||
let mut params = settings(Path::new(""), &output, per_format);
|
||||
params["includeSubfolders"] = json!("true");
|
||||
let error = session.execute(COMMAND, params.clone()).unwrap_err();
|
||||
assert!(matches!(error, EngineError::BadParams { msg, .. } if msg.contains("includeSubfolders")));
|
||||
params["includeSubfolders"] = json!(false);
|
||||
params["input"] = json!([]);
|
||||
assert_eq!(session.execute(COMMAND, params), Err(EngineError::Other(NO_SOURCE.into())));
|
||||
}
|
||||
assert!(!output.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_removed_between_formats_keeps_the_written_file_and_read_error() {
|
||||
use super::{ProcessorInputs, image_processor_folder_inputs, processor_format, run_processor_formats};
|
||||
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let output = root.path().join("output");
|
||||
let input = root.path().join("test.ppm");
|
||||
let jpeg = output.join("test.jpg");
|
||||
fs::create_dir(&output).unwrap();
|
||||
write_image(&input).unwrap();
|
||||
let session = crate::session();
|
||||
let output = output.to_str().unwrap();
|
||||
let sources = image_processor_folder_inputs(&json!({"files": [input]}), output).unwrap();
|
||||
let inputs = ProcessorInputs::Folder(sources);
|
||||
let formats =
|
||||
[processor_format(&session, "jpeg", "jpg", &json!({})).unwrap().unwrap(), processor_format(&session, "tiff", "tif", &json!({})).unwrap().unwrap()];
|
||||
let result = run_processor_formats(
|
||||
&session,
|
||||
&inputs,
|
||||
output,
|
||||
formats.into_iter().inspect(|format| {
|
||||
if format.extension == "tif" {
|
||||
assert!(jpeg.is_file());
|
||||
fs::remove_file(&input).unwrap();
|
||||
}
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
let files = result["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(Path::new(files[0].as_str().unwrap()), jpeg);
|
||||
let errors = result["errors"].as_array().unwrap();
|
||||
assert_eq!(errors.len(), 1);
|
||||
assert_eq!(errors[0]["file"], json!(input));
|
||||
assert_eq!(errors[0]["format"], "tif");
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::cell::Cell;
|
||||
|
||||
use super::batch_run::{BatchInput, TreeNaming, batch_inputs_tree, process_document_copies, process_tree};
|
||||
use super::open::import_opened;
|
||||
use super::paths::{file_name, list_images, read_file, stem, untitled_name};
|
||||
@@ -7,6 +9,9 @@ use super::{
|
||||
str_param,
|
||||
};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
#[path = "image_processor_empty_source_tests.rs"]
|
||||
mod image_processor_empty_source_tests;
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
#[path = "image_processor_formats_tests.rs"]
|
||||
mod image_processor_formats_tests;
|
||||
@@ -101,7 +106,8 @@ pub(super) fn parse_steps(v: &Value) -> Result<Vec<(String, Value)>> {
|
||||
/// Resize and export folder inputs or copies of the current/all open documents.
|
||||
/// An omitted `source` keeps the folder-input contract; document sources include unsaved
|
||||
/// edits without modifying the original documents. Invalid parameters and missing documents
|
||||
/// return an error; processing failures and output-name collisions appear in per-file errors.
|
||||
/// return an error, as does a folder source with no openable images. Processing failures and
|
||||
/// output-name collisions appear in per-file errors.
|
||||
pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = IMAGE_PROCESSOR;
|
||||
let source = match p.get("source") {
|
||||
@@ -134,8 +140,11 @@ pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(false)
|
||||
};
|
||||
let r = if source == "folder" {
|
||||
let inputs = batch_inputs_tree(p, cmd, &output)?;
|
||||
process_tree(s, &inputs, &output, format, save, TreeNaming::Unique, &process)
|
||||
let inputs = image_processor_folder_inputs(p, &output)?;
|
||||
let opened = Cell::new(false);
|
||||
let result = process_image_processor_folder(s, &inputs, &output, format, save, &opened, &process);
|
||||
require_opened_source(&opened)?;
|
||||
result
|
||||
} else {
|
||||
let documents = if source == "current" { vec![s.active().ok_or(EngineError::NoDocument)?] } else { s.documents().iter().map(|st| &**st).collect() };
|
||||
if documents.is_empty() {
|
||||
@@ -148,6 +157,38 @@ pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
const IMAGE_PROCESSOR: &str = "file.scripts.imageProcessor";
|
||||
const IMAGE_PROCESSOR_NO_FORMAT: &str = "You must save to at least one file type.";
|
||||
const IMAGE_PROCESSOR_NO_SOURCE: &str = "There were no source files that could be opened by PhotoCraft.";
|
||||
|
||||
fn image_processor_folder_inputs(p: &Value, output: &str) -> Result<Vec<BatchInput>> {
|
||||
if p.get("input").or_else(|| p.get("files")).and_then(Value::as_str) == Some("") {
|
||||
// Treat the empty dialog field as an empty file list while retaining normal validation.
|
||||
let mut params = p.clone();
|
||||
params["input"] = json!([]);
|
||||
return batch_inputs_tree(¶ms, IMAGE_PROCESSOR, output);
|
||||
}
|
||||
batch_inputs_tree(p, IMAGE_PROCESSOR, output)
|
||||
}
|
||||
|
||||
/// The runner calls `process` only after it opens an input. Export and processing failures
|
||||
/// still belong in the per-file report, even when none of the opened inputs could be saved.
|
||||
fn process_image_processor_folder(
|
||||
s: &Session,
|
||||
inputs: &[BatchInput],
|
||||
output: &str,
|
||||
format: &str,
|
||||
save: SaveOpts,
|
||||
opened: &Cell<bool>,
|
||||
process: &dyn Fn(&mut Session, &str) -> Result<bool>,
|
||||
) -> Value {
|
||||
process_tree(s, inputs, output, format, save, TreeNaming::Unique, &|scratch, out| {
|
||||
opened.set(true);
|
||||
process(scratch, out)
|
||||
})
|
||||
}
|
||||
|
||||
fn require_opened_source(opened: &Cell<bool>) -> Result<()> {
|
||||
if opened.get() { Ok(()) } else { Err(EngineError::Other(IMAGE_PROCESSOR_NO_SOURCE.into())) }
|
||||
}
|
||||
|
||||
fn image_processor_param(message: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: IMAGE_PROCESSOR.into(), msg: message.into() }
|
||||
@@ -224,17 +265,22 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) -
|
||||
return Err(image_processor_param(IMAGE_PROCESSOR_NO_FORMAT));
|
||||
}
|
||||
let inputs = match source {
|
||||
"folder" => ProcessorInputs::Folder(batch_inputs_tree(p, IMAGE_PROCESSOR, output)?),
|
||||
"folder" => ProcessorInputs::Folder(image_processor_folder_inputs(p, output)?),
|
||||
"current" => ProcessorInputs::Documents(vec![s.active().ok_or(EngineError::NoDocument)?]),
|
||||
_ if s.documents().is_empty() => return Err(EngineError::NoDocument),
|
||||
_ => ProcessorInputs::Documents(s.documents().iter().map(|st| &**st).collect()),
|
||||
};
|
||||
run_processor_formats(s, &inputs, output, formats)
|
||||
}
|
||||
|
||||
fn run_processor_formats(s: &Session, inputs: &ProcessorInputs<'_>, output: &str, formats: impl IntoIterator<Item = ProcessorFormat>) -> Result<Value> {
|
||||
let mut files = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let opened = Cell::new(false);
|
||||
for format in formats {
|
||||
// The existing runners prepare fresh scratch documents for each output.
|
||||
let process = |scratch: &mut Session, out: &str| {
|
||||
if let ProcessorInputs::Folder(inputs) = &inputs
|
||||
if let ProcessorInputs::Folder(inputs) = inputs
|
||||
&& super::paths::is_file(out)
|
||||
&& inputs.iter().any(|input| super::paths::same_file(&input.path, out))
|
||||
{
|
||||
@@ -248,8 +294,8 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) -
|
||||
}
|
||||
Ok(false)
|
||||
};
|
||||
let mut result = match &inputs {
|
||||
ProcessorInputs::Folder(inputs) => process_tree(s, inputs, output, format.extension, format.save, TreeNaming::Unique, &process),
|
||||
let mut result = match inputs {
|
||||
ProcessorInputs::Folder(inputs) => process_image_processor_folder(s, inputs, output, format.extension, format.save, &opened, &process),
|
||||
ProcessorInputs::Documents(documents) => process_document_copies(s, documents, output, format.extension, format.save, &process),
|
||||
};
|
||||
if let Some(Value::Array(written)) = result.get_mut("files").map(Value::take) {
|
||||
@@ -265,6 +311,9 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) -
|
||||
}));
|
||||
}
|
||||
}
|
||||
if matches!(inputs, ProcessorInputs::Folder(_)) {
|
||||
require_opened_source(&opened)?;
|
||||
}
|
||||
Ok(json!({"files": files, "errors": errors}))
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
use crate::color_cmds::ColorExt;
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_color::ColorMode;
|
||||
use photocraft_doc::text_styles::{CharacterStyleDef, ParagraphStyleDef};
|
||||
@@ -406,11 +407,21 @@ pub(crate) fn duplicate_to_new_document(s: &mut Session, p: &Value) -> Result<Va
|
||||
// Its own Basic Paragraph is the source's: type that inherits from it must not gain overrides.
|
||||
nd.text_styles.basic.clone_from(&sdoc.text_styles.basic);
|
||||
let new_ids: Vec<LayerId> = nd.layers.iter().map(|l| l.id).collect();
|
||||
// Keep the copies in the opening snapshot and use a layer-free document for undo.
|
||||
let layers = std::mem::take(&mut nd.layers);
|
||||
let mut before = nd.clone();
|
||||
nd.layers = layers;
|
||||
let index = s.add_document(nd, None);
|
||||
if let (Some(name), [id]) = (typed, new_ids.as_slice()) {
|
||||
crate::type_cmds::note_typed_name(s, *id, &name);
|
||||
}
|
||||
crate::layer_multi_cmds::reselect(s, new_ids.clone(), new_ids.last().copied());
|
||||
if let Some(st) = s.active_mut() {
|
||||
// add_document can replace the ID to avoid collisions with open documents or clone sources.
|
||||
before.id = st.doc.id;
|
||||
st.history.set_current_layers(Default::default());
|
||||
st.history.record("Duplicate Layer", Arc::new(before), st.layer_target());
|
||||
}
|
||||
let mut out = json!({"document": index, "layers": new_ids.iter().map(|l| l.0).collect::<Vec<_>>()});
|
||||
if let [one] = new_ids.as_slice()
|
||||
&& let Some(map) = out.as_object_mut()
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_doc::LayerId;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{DocState, Session};
|
||||
|
||||
fn check_duplicate_history(s: &mut Session, source: &DocState) {
|
||||
let dst = s.active().unwrap();
|
||||
assert!(dst.history.can_undo(), "the duplicate is undoable in the destination");
|
||||
assert_eq!(dst.history.entries(), ["Open", "Duplicate Layer"]);
|
||||
let with_copies = dst.doc.clone();
|
||||
let selected = dst.selected_layers().to_vec();
|
||||
let active = dst.active_layer;
|
||||
let mut empty = (*with_copies).clone();
|
||||
empty.layers.clear();
|
||||
|
||||
assert_eq!(s.execute("edit.undo", json!({})).unwrap(), true);
|
||||
assert_eq!(s.active_index(), Some(1));
|
||||
let dst = s.active().unwrap();
|
||||
assert_eq!(*dst.doc, empty, "undo removes the copies and retains document properties");
|
||||
assert_eq!(dst.active_layer, None);
|
||||
assert!(dst.selected_layers().is_empty());
|
||||
assert!(!dst.history.can_undo());
|
||||
assert_eq!(*s.documents()[0].doc, *source.doc);
|
||||
assert_eq!(s.documents()[0].history.entries(), source.history.entries());
|
||||
|
||||
assert_eq!(s.execute("edit.redo", json!({})).unwrap(), true);
|
||||
let dst = s.active().unwrap();
|
||||
assert_eq!(s.active_index(), Some(1));
|
||||
assert_eq!(*dst.doc, *with_copies);
|
||||
assert_eq!(dst.selected_layers(), selected);
|
||||
assert_eq!(dst.active_layer, active);
|
||||
assert_eq!(dst.history.entries(), ["Open", "Duplicate Layer"]);
|
||||
assert_eq!(*s.documents()[0].doc, *source.doc);
|
||||
assert_eq!(s.documents()[0].history.entries(), source.history.entries());
|
||||
assert_eq!(s.documents()[0].selected_layers(), source.selected_layers());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_to_a_new_document_undoes_one_layer_at_each_depth() {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth})).unwrap();
|
||||
let layer = s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap()["layer"].clone();
|
||||
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
|
||||
let source = s.active().unwrap().clone();
|
||||
|
||||
let r = s.execute("layer.duplicate", json!({"document": "new", "layer": layer, "name": "Ink"})).unwrap();
|
||||
assert_eq!(r["document"], 1);
|
||||
assert_eq!(s.active_index(), Some(1));
|
||||
let dst = s.active().unwrap();
|
||||
assert_eq!(dst.doc.layers.len(), 1);
|
||||
assert_eq!(dst.doc.layers[0].name, "Ink");
|
||||
assert_eq!(dst.snapshots().len(), 1);
|
||||
assert_eq!(dst.snapshots()[0].name, dst.doc.name);
|
||||
assert_eq!(*dst.snapshots()[0].doc, *dst.doc);
|
||||
check_duplicate_history(&mut s, &source);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_to_a_new_document_undoes_all_selected_layers_in_one_step() {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 40, "height": 30})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap();
|
||||
let background = s.active().unwrap().doc.layers[0].id.0;
|
||||
s.execute("layer.select", json!({"layer": background, "mode": "add"})).unwrap();
|
||||
let source = s.active().unwrap().clone();
|
||||
assert_eq!(source.selected_layers().len(), 2);
|
||||
|
||||
s.execute("layer.duplicate", json!({"document": "new"})).unwrap();
|
||||
let dst = s.active().unwrap();
|
||||
let names: Vec<_> = dst.doc.layers.iter().map(|layer| layer.name.as_str()).collect();
|
||||
assert_eq!(names, ["Background", "Paint"]);
|
||||
assert_eq!(dst.selected_layers().len(), 2);
|
||||
assert_eq!(dst.snapshots().len(), 1);
|
||||
check_duplicate_history(&mut s, &source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_to_a_new_document_undoes_a_group_without_a_first_snapshot() {
|
||||
let mut s = crate::session();
|
||||
s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": false})).unwrap();
|
||||
s.execute("file.new", json!({"width": 40, "height": 30, "mode": "gray", "depth": 16, "resolution": 300, "profile": "gray-gamma-2.2"})).unwrap();
|
||||
let child = s.execute("layer.new.layer", json!({"name": "Child"})).unwrap()["layer"].clone();
|
||||
let group = s.execute("layer.groupLayers", json!({"name": "Folder", "layer": child})).unwrap();
|
||||
let source = s.active().unwrap().clone();
|
||||
let r = s.execute("layer.duplicate", json!({"document": "new", "layer": group["layer"], "documentName": "Grayscale copy"})).unwrap();
|
||||
let dst = s.active().unwrap();
|
||||
assert!(dst.snapshots().is_empty());
|
||||
assert_eq!(dst.doc.mode, ColorMode::Grayscale);
|
||||
assert_eq!(dst.doc.depth, SampleType::U16);
|
||||
assert_eq!(dst.doc.resolution_dpi, 300.0);
|
||||
assert!(dst.doc.icc_profile.is_some());
|
||||
assert_eq!(dst.doc.icc_profile, source.doc.icc_profile);
|
||||
assert_eq!(dst.doc.layers.len(), 1);
|
||||
let copied = dst.doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap();
|
||||
assert_eq!(copied.name, "Folder");
|
||||
let children = copied.children().unwrap();
|
||||
assert_eq!(children.len(), 1);
|
||||
assert_eq!(children[0].name, "Child");
|
||||
check_duplicate_history(&mut s, &source);
|
||||
assert!(s.active().unwrap().snapshots().is_empty());
|
||||
}
|
||||
@@ -89,7 +89,7 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// [`rotate_arbitrary`]; `image_rotation` is true on the Image Rotation path and decides two
|
||||
/// things there: count points stay where they were (#11762) and the selection is dropped, in the
|
||||
/// things there: the angle rounds to hundredths of a degree, count points stay where they were (#11762) and the selection is dropped, in the
|
||||
/// same history step, so one undo brings it back (#14507). The Crop tool's straighten turn and the
|
||||
/// Ruler's Straighten pass false: they move count points with the image and warp the selection.
|
||||
/// `keep_guides` turns the guides with the canvas (#14508, measured for Image Rotation > Arbitrary)
|
||||
@@ -106,6 +106,7 @@ pub(crate) fn rotate_arbitrary_with(s: &mut Session, p: &Value, image_rotation:
|
||||
"ccw" => -angle,
|
||||
d => return Err(bad(CMD, format!("direction `{d}` (cw|ccw)"))),
|
||||
};
|
||||
let deg = if image_rotation { (deg * 100.0).round() % 36_000.0 / 100.0 } else { deg };
|
||||
if deg.rem_euclid(360.0).abs() < 1e-9 {
|
||||
return Ok(json!({"width": s.active().map(|d| d.doc.size.width), "height": s.active().map(|d| d.doc.size.height)}));
|
||||
}
|
||||
@@ -953,3 +954,6 @@ mod color_table_index_tests;
|
||||
#[cfg(test)]
|
||||
#[path = "rotate_canvas_interpolation_pref_tests.rs"]
|
||||
mod rotate_canvas_interpolation_pref_tests;
|
||||
#[cfg(test)]
|
||||
#[path = "rotate_canvas_tiny_angle_tests.rs"]
|
||||
mod rotate_canvas_tiny_angle_tests;
|
||||
@@ -92,13 +92,13 @@ fn rotate_arbitrary_keeps_the_background_opaque_with_a_translucent_background_co
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_arbitrary_keeps_the_full_precision_angle() {
|
||||
fn straighten_keeps_the_full_precision_angle() {
|
||||
// Rounded to f32 this angle crosses a whole pixel: 1003 px instead of 1002, so a rotated crop
|
||||
// that sized its canvas with `rotated_size` at f64 would land 1 px off.
|
||||
let angle = 0.114_706_514_493_370_71;
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 1000, "height": 1000})).unwrap();
|
||||
let r = s.execute("image.rotation.arbitrary", json!({"angle": angle})).unwrap();
|
||||
let r = rotate_arbitrary_with(&mut s, &json!({"angle": angle}), false, false).unwrap();
|
||||
assert_eq!(rotated_size(Size::new(1000, 1000), angle), Size::new(1002, 1002));
|
||||
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(1002), Some(1002)));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn canvas_rotation_rounds_to_hundredths_before_editing() {
|
||||
for direction in ["cw", "ccw"] {
|
||||
for (angle, width, height, edits) in [
|
||||
(0.001, 400, 300, 0),
|
||||
(0.004, 400, 300, 0),
|
||||
(-0.004, 400, 300, 0),
|
||||
(0.0, 400, 300, 0),
|
||||
(360.0, 400, 300, 0),
|
||||
(-360.0, 400, 300, 0),
|
||||
(720.0, 400, 300, 0),
|
||||
(359.996, 400, 300, 0),
|
||||
(0.005, 401, 301, 1),
|
||||
(-0.005, 401, 301, 1),
|
||||
(359.99, 401, 301, 1),
|
||||
(361.0, 406, 307, 1),
|
||||
] {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let before = s.active().unwrap().history.past_len();
|
||||
let result = s.execute("image.rotation.arbitrary", json!({"angle": angle, "direction": direction})).unwrap();
|
||||
assert_eq!(result, json!({"width": width, "height": height}), "{direction} {angle}");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), before + edits, "{direction} {angle}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn straightening_still_applies_a_sub_hundredth_turn() {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 40, "height": 30})).unwrap();
|
||||
let before = s.active().unwrap().history.past_len();
|
||||
let result = rotate_arbitrary_with(&mut s, &json!({"angle": 0.004}), false, false).unwrap();
|
||||
assert_eq!(result, json!({"width": 41, "height": 31}));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), before + 1);
|
||||
}
|
||||
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
(
|
||||
"channelMixer",
|
||||
"Channel Mixer…",
|
||||
r##"{"red":json,"green":json,"blue":json,"gray":json,"monochrome":bool=false} (per output channel [red %, green %, blue %, constant %] in -200..200; gray = the monochrome mix)"##,
|
||||
r##"{"red":json,"green":json,"blue":json,"cyan":json,"magenta":json,"yellow":json,"black":json,"gray":json,"monochrome":bool=false} (per output channel [red %, green %, blue %, constant %] in -200..200; CMYK documents (or cyan/magenta/yellow/black keys): per ink output [cyan %, magenta %, yellow %, black %, constant %]; gray = the monochrome mix; monochrome is unsupported for CMYK outputs)"##,
|
||||
),
|
||||
("invert", "Invert", "{}"),
|
||||
("posterize", "Posterize…", r##"{"levels":2..255=4}"##),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! #13244: a Line tool drag is one History step named "Line Tool" in Shape and Path mode; the
|
||||
//! commands without the tool keep "New Shape Layer" and "Work Path".
|
||||
//! #13244 and #13328: a Line tool drag records one "Line Tool" step when creating a shape
|
||||
//! layer, adding to that layer, or drawing a path. Scripts retain the default History names.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -65,3 +65,52 @@ fn an_unknown_history_name_is_refused_without_a_step() {
|
||||
assert!(s.execute("path.set", json!({"name": "work", "path": outline(100.0), "historyName": 7})).is_err());
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_a_line_to_a_shape_uses_the_tool_history_name() {
|
||||
let mut s = session();
|
||||
let id = s.execute("shape.create", line(Some("Line Tool"))).unwrap()["layer"].as_u64().unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
// Shift, Alt and Shift+Alt send these three operations to shape.create.
|
||||
for op in ["combine", "subtract", "intersect"] {
|
||||
let mut params = line(Some("Line Tool"));
|
||||
params["addTo"] = json!(id);
|
||||
params["op"] = json!(op);
|
||||
params["from"] = json!([450, 320]);
|
||||
let result = s.execute("shape.create", params).unwrap();
|
||||
assert_eq!(result["layer"], id, "{op}");
|
||||
assert_eq!(result["path"]["subpaths"][1]["op"], op, "{op}");
|
||||
assert_eq!(steps(&s), n + 1, "{op}");
|
||||
assert_eq!(last_step(&s), Some("Line Tool"), "{op}");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(*s.active().unwrap().doc, *before, "{op}");
|
||||
assert_eq!(steps(&s), n, "{op}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scripted_shape_add_keeps_its_default_history_name() {
|
||||
let mut s = session();
|
||||
let id = s.execute("shape.create", line(None)).unwrap()["layer"].as_u64().unwrap();
|
||||
let n = steps(&s);
|
||||
let mut params = line(None);
|
||||
params["addTo"] = json!(id);
|
||||
params.as_object_mut().unwrap().remove("historyName");
|
||||
s.execute("shape.create", params).unwrap();
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
assert_eq!(last_step(&s), Some("Add Shape"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_label_for_a_shape_add_preserves_the_document_and_history() {
|
||||
let mut s = session();
|
||||
let id = s.execute("shape.create", line(None)).unwrap()["layer"].as_u64().unwrap();
|
||||
let n = steps(&s);
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let mut params = line(Some("Unknown Tool"));
|
||||
params["addTo"] = json!(id);
|
||||
assert!(s.execute("shape.create", params).is_err());
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before));
|
||||
}
|
||||
@@ -436,10 +436,12 @@ fn default_name(kind: &str) -> &'static str {
|
||||
}
|
||||
|
||||
/// Creates a shape layer, or adds path components to the shape identified by `addTo`.
|
||||
/// A tool history override labels new layers. Additions use the Add Shape label.
|
||||
/// Line Tool additions keep the tool's History name. Other shape additions use Add Shape.
|
||||
pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "shape.create";
|
||||
let label = super::paths::pen_history_name(p, CMD, "New Shape Layer")?;
|
||||
let add_to = p.get("addTo").and_then(Value::as_u64);
|
||||
let default_label = if add_to.is_some() { "Add Shape" } else { "New Shape Layer" };
|
||||
let label = super::paths::pen_history_name(p, CMD, default_label)?;
|
||||
let kind = p.get("kind").and_then(Value::as_str).unwrap_or("rect");
|
||||
let (path, live) = if kind == "path" {
|
||||
let v = p.get("path").ok_or_else(|| bad(CMD, "kind \"path\" needs `path`"))?;
|
||||
@@ -451,10 +453,11 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (fill, stroke) = new_fill_stroke(s, CMD, p)?;
|
||||
vector::flatten::validate_shape(&path, stroke.as_ref()).map_err(|e| bad(CMD, e))?;
|
||||
// Add to an existing shape layer with a path operation (Shape tool in combine/subtract… mode).
|
||||
if let Some(target) = p.get("addTo").and_then(Value::as_u64) {
|
||||
if let Some(target) = add_to {
|
||||
let op = p.get("op").and_then(Value::as_str).map_or(Some(PathOp::Combine), op_from).ok_or_else(|| bad(CMD, "unknown `op`"))?;
|
||||
let id = LayerId(target);
|
||||
with_shape(s, id, "Add Shape", |sh, _| {
|
||||
let label = if kind == "line" && label == "Line Tool" { label } else { "Add Shape" };
|
||||
with_shape(s, id, label, |sh, _| {
|
||||
for mut sp in path.subpaths {
|
||||
// A joined subpath (a hole) belongs to the component before it, which takes `op`.
|
||||
if sp.op != PathOp::Join {
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Edit > Color Settings' Settings menu (#14229): the 13 named setups, the stored preset name,
|
||||
//! and "Custom" once anything changes.
|
||||
//!
|
||||
//! Running a setup sets the process-wide Spot dot gain, which races every test that renders a
|
||||
//! Multichannel document. So the command runs here only with setups whose Spot is the default
|
||||
//! Dot Gain 20 %; `crates/engine/tests/global_state/color_settings_presets.rs` runs all of them
|
||||
//! in the `global_state` binary.
|
||||
|
||||
use super::*;
|
||||
|
||||
const CMD: &str = "edit.colorSettings";
|
||||
|
||||
fn setup(name: &str) -> ColorSettings {
|
||||
let s = crate::session();
|
||||
s.color().preset_settings(&s.color().settings, name).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_menu_lists_the_thirteen_setups_in_order() {
|
||||
assert_eq!(COLOR_SETTINGS_PRESETS.len(), 13);
|
||||
assert_eq!(COLOR_SETTINGS_PRESETS.map(|n| n.to_string()), SETTINGS_PRESETS.map(|p| p.name.to_string()));
|
||||
assert_eq!(COLOR_SETTINGS_PRESETS[0], "Europe General Purpose 3");
|
||||
assert_eq!(COLOR_SETTINGS_PRESETS[3], "Monitor Color");
|
||||
assert_eq!(COLOR_SETTINGS_PRESETS[12], "North America Web/Internet");
|
||||
// The params doc offers Custom, then the same names.
|
||||
crate::install().unwrap();
|
||||
let spec = crate::commands::find(CMD).unwrap().params;
|
||||
let names = format!("\"preset\":\"{CUSTOM_SETTINGS}|{}\"", COLOR_SETTINGS_PRESETS.join("|"));
|
||||
assert!(spec.contains(&names), "{spec}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_setup_sets_the_measured_values() {
|
||||
use Policy::{Convert as C, Off, Preserve as P};
|
||||
// Name, RGB, CMYK, Gray, Spot, policies, Ask open/paste/missing, intent.
|
||||
type Row = (&'static str, &'static str, &'static str, &'static str, f32, [Policy; 3], [bool; 3], &'static str);
|
||||
let rows: [Row; 13] = [
|
||||
("Europe General Purpose 3", "srgb", "coated-fogra39", "dot-gain-20-compat", 15.0, [P, P, P], [false, false, false], "relative"),
|
||||
("Europe Prepress 3", "adobe-rgb-compat", "coated-fogra39", "dot-gain-20-compat", 15.0, [P, P, P], [true, true, true], "relative"),
|
||||
("Europe Web/Internet 2", "srgb", "coated-fogra39", "gray-gamma-2.2", 15.0, [C, P, P], [true, true, false], "relative"),
|
||||
// Without a display profile, Monitor RGB is sRGB.
|
||||
("Monitor Color", "srgb", "coated-cmyk", "gray-gamma-2.2", 20.0, [Off, Off, Off], [true, false, false], "relative"),
|
||||
("Japan Color for Newspaper", "adobe-rgb-compat", "coated-cmyk", "dot-gain-20-compat", 25.0, [P, P, P], [true, true, true], "perceptual"),
|
||||
("Japan General Purpose 2", "srgb", "coated-cmyk", "dot-gain-20-compat", 15.0, [P, P, P], [false, false, false], "perceptual"),
|
||||
("Japan Magazine Advertisement Color", "adobe-rgb-compat", "coated-cmyk", "dot-gain-20-compat", 15.0, [P, P, P], [true, true, true], "perceptual"),
|
||||
("Japan Prepress 2", "adobe-rgb-compat", "coated-cmyk", "dot-gain-20-compat", 15.0, [P, P, P], [true, true, true], "perceptual"),
|
||||
("Japan Web/Internet", "srgb", "coated-cmyk", "gray-gamma-2.2", 15.0, [C, P, P], [true, true, false], "perceptual"),
|
||||
("North America General Purpose 2", "srgb", "coated-cmyk", "dot-gain-20-compat", 20.0, [P, P, P], [false, false, false], "relative"),
|
||||
("North America Newspaper", "adobe-rgb-compat", "coated-cmyk", "dot-gain-20-compat", 25.0, [P, P, P], [true, true, true], "perceptual"),
|
||||
("North America Prepress 2", "adobe-rgb-compat", "coated-cmyk", "dot-gain-20-compat", 20.0, [P, P, P], [true, true, true], "relative"),
|
||||
("North America Web/Internet", "srgb", "coated-cmyk", "gray-gamma-2.2", 20.0, [C, P, P], [true, true, false], "relative"),
|
||||
];
|
||||
for (name, rgb, cmyk, gray, spot, policies, ask, intent) in rows {
|
||||
let c = setup(name);
|
||||
assert_eq!((c.working_rgb.as_str(), c.working_cmyk.as_str(), c.working_gray.as_str()), (rgb, cmyk, gray), "{name}");
|
||||
assert_eq!(c.spot_dot_gain, spot, "{name}");
|
||||
assert_eq!([c.policy_rgb, c.policy_cmyk, c.policy_gray], policies, "{name}");
|
||||
assert_eq!([c.ask_on_mismatch, c.ask_on_paste, c.ask_on_missing], ask, "{name}");
|
||||
assert_eq!(c.intent, intent, "{name}");
|
||||
// Every setup: Black Point Compensation and Dither on, Blend Text Colors Using Gamma 1.45.
|
||||
assert!(c.bpc && c.dither, "{name}");
|
||||
assert_eq!(c.blend_text_gamma, photocraft_compose::psblend::TEXT_GAMMA, "{name}");
|
||||
assert_eq!(c.preset, name);
|
||||
// Each resolves to working spaces PhotoCraft can use.
|
||||
validate_settings(&c).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_color_takes_a_named_monitor_profile() {
|
||||
let mut s = crate::session();
|
||||
s.color_mut().settings.monitor_profile = "display-p3".into();
|
||||
let c = s.color().preset_settings(&s.color().settings, "Monitor Color").unwrap();
|
||||
assert_eq!(c.working_rgb, "display-p3");
|
||||
// The monitor profile itself is not part of the setup.
|
||||
assert_eq!(c.monitor_profile, "display-p3");
|
||||
// Scripted with a Monitor Profile changed in the same call, it follows that profile.
|
||||
let r = s.execute(CMD, json!({"preset": "Monitor Color", "monitorProfile": "prophoto-compat"})).unwrap();
|
||||
assert_eq!(r["preset"], "Monitor Color");
|
||||
assert_eq!(r["settings"]["workingRgb"], "prophoto-compat");
|
||||
// With `auto` and no display profile read, it is sRGB.
|
||||
let r = s.execute(CMD, json!({"preset": "Monitor Color", "monitorProfile": "auto"})).unwrap();
|
||||
assert_eq!((&r["preset"], &r["settings"]["workingRgb"]), (&json!("Monitor Color"), &json!("srgb")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_monitor_profile_change_makes_monitor_color_custom() {
|
||||
let mut s = crate::session();
|
||||
let r = s.execute(CMD, json!({"preset": "Monitor Color", "monitorProfile": "srgb"})).unwrap();
|
||||
assert_eq!((&r["preset"], &r["settings"]["workingRgb"]), (&json!("Monitor Color"), &json!("srgb")));
|
||||
// Monitor Color would now set Display P3, so the sRGB values left behind are Custom.
|
||||
let r = s.execute(CMD, json!({"monitorProfile": "display-p3"})).unwrap();
|
||||
assert_eq!((&r["preset"], &r["settings"]["workingRgb"]), (&json!(CUSTOM_SETTINGS), &json!("srgb")));
|
||||
// A monitor change that leaves the setup as Monitor Color would set it keeps the name.
|
||||
let r = s.execute(CMD, json!({"preset": "Monitor Color", "monitorProfile": "srgb"})).unwrap();
|
||||
assert_eq!(r["preset"], "Monitor Color");
|
||||
let r = s.execute(CMD, json!({"monitorProfile": "auto"})).unwrap();
|
||||
assert_eq!(r["preset"], "Monitor Color");
|
||||
// Other setups don't follow the monitor profile.
|
||||
s.execute(CMD, json!({"preset": "North America Prepress 2"})).unwrap();
|
||||
let r = s.execute(CMD, json!({"monitorProfile": "display-p3"})).unwrap();
|
||||
assert_eq!(r["preset"], "North America Prepress 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_settings_are_custom() {
|
||||
let mut s = crate::session();
|
||||
assert_eq!(ColorSettings::default().preset, CUSTOM_SETTINGS);
|
||||
let r = s.execute(CMD, json!({})).unwrap();
|
||||
assert_eq!(r["preset"], CUSTOM_SETTINGS);
|
||||
assert_eq!(r["settings"]["preset"], CUSTOM_SETTINGS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scripted_setup_is_stored_and_reported() {
|
||||
let mut s = crate::session();
|
||||
// Blend Text Colors Using Gamma off: a scripted setup turns it back on at 1.45.
|
||||
s.color_mut().settings.blend_text_gamma = 1.0;
|
||||
let r = s.execute(CMD, json!({"preset": "North America Prepress 2"})).unwrap();
|
||||
assert_eq!(r["preset"], "North America Prepress 2");
|
||||
let c = &s.color().settings;
|
||||
assert_eq!(c.preset, "North America Prepress 2");
|
||||
assert_eq!((c.working_rgb.as_str(), c.policy_rgb, c.ask_on_missing), ("adobe-rgb-compat", Policy::Preserve, true));
|
||||
assert_eq!(c.blend_text_gamma, photocraft_compose::psblend::TEXT_GAMMA);
|
||||
// Reading the settings again keeps the name.
|
||||
assert_eq!(s.execute(CMD, json!({})).unwrap()["preset"], "North America Prepress 2");
|
||||
// So does setting a value to what it already is, and changing the monitor profile.
|
||||
assert_eq!(s.execute(CMD, json!({"bpc": true, "monitorProfile": "srgb"})).unwrap()["preset"], "North America Prepress 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_change_makes_it_custom() {
|
||||
let changes = [
|
||||
json!({"workingRgb": "srgb"}),
|
||||
json!({"policyCmyk": "off"}),
|
||||
json!({"askOnPaste": false}),
|
||||
json!({"intent": "perceptual"}),
|
||||
json!({"bpc": false}),
|
||||
json!({"dither": false}),
|
||||
// Blend Text Colors Using Gamma too: in `tests/global_state/color_settings_presets.rs`, as it is process-wide.
|
||||
json!({"reset": true}),
|
||||
];
|
||||
for change in changes {
|
||||
let mut s = crate::session();
|
||||
s.execute(CMD, json!({"preset": "North America Prepress 2"})).unwrap();
|
||||
let r = s.execute(CMD, change.clone()).unwrap();
|
||||
assert_eq!(r["preset"], CUSTOM_SETTINGS, "{change}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dialogs_ok_keeps_the_name_with_its_own_text_gamma() {
|
||||
// OK in the dialog sends the picked setup with every value, and Blend Text Colors Using Gamma
|
||||
// as the dialog kept it: the name stays, and so does that gamma.
|
||||
let mut s = crate::session();
|
||||
let mut params = serde_json::to_value(setup("North America Web/Internet")).unwrap();
|
||||
params["blendTextGamma"] = json!(1.45);
|
||||
params["preset"] = json!("North America Web/Internet");
|
||||
let r = s.execute(CMD, params.clone()).unwrap();
|
||||
assert_eq!(r["preset"], "North America Web/Internet");
|
||||
// Changed after picking it, the dialog shows and sends Custom.
|
||||
params["preset"] = json!(CUSTOM_SETTINGS);
|
||||
params["bpc"] = json!(false);
|
||||
let r = s.execute(CMD, params).unwrap();
|
||||
assert_eq!(r["preset"], CUSTOM_SETTINGS);
|
||||
assert!(!s.color().settings.bpc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setup_with_a_differing_value_is_custom() {
|
||||
let mut s = crate::session();
|
||||
let r = s.execute(CMD, json!({"preset": "Monitor Color", "policyRgb": "preserve"})).unwrap();
|
||||
assert_eq!(r["preset"], CUSTOM_SETTINGS);
|
||||
// The setup's other values still apply.
|
||||
let c = &s.color().settings;
|
||||
assert_eq!((c.policy_rgb, c.policy_cmyk, c.working_gray.as_str()), (Policy::Preserve, Policy::Off, "gray-gamma-2.2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_keeps_the_values() {
|
||||
let mut s = crate::session();
|
||||
s.execute(CMD, json!({"preset": "North America General Purpose 2"})).unwrap();
|
||||
let r = s.execute(CMD, json!({"preset": CUSTOM_SETTINGS})).unwrap();
|
||||
assert_eq!(r["preset"], CUSTOM_SETTINGS);
|
||||
assert!(!s.color().settings.ask_on_mismatch, "the setup's values stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_preset_is_an_error_and_changes_nothing() {
|
||||
let mut s = crate::session();
|
||||
s.execute(CMD, json!({"preset": "North America General Purpose 2"})).unwrap();
|
||||
let before = s.color().settings.clone();
|
||||
for bad in [json!(null), json!("Europe"), json!(""), json!("custom"), json!(3), json!(true), json!(["Monitor Color"]), json!({"name": "Monitor Color"})] {
|
||||
let e = s.execute(CMD, json!({"preset": bad.clone(), "bpc": false})).unwrap_err();
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{bad}: {e}");
|
||||
assert_eq!(s.color().settings, before, "{bad}");
|
||||
}
|
||||
// A stored name the menu doesn't have (a hand-edited preferences file) is refused too.
|
||||
let mut c = before.clone();
|
||||
c.preset = "Nowhere".into();
|
||||
assert!(validate_settings(&c).is_err());
|
||||
}
|
||||
@@ -171,7 +171,7 @@ pub fn effect_defaults(kind: &str) -> Value {
|
||||
json!({"style": "inner", "technique": "smooth", "depth": 100, "direction": "up", "size": 5, "soften": 0, "angle": 120, "useGlobalLight": true, "altitude": 30, "glossContour": "Linear", "glossAntiAlias": false, "highlightBlend": "Screen", "highlightColor": "#ffffff", "highlightOpacity": 75, "shadowBlend": "Multiply", "shadowColor": "#000000", "shadowOpacity": 75, "contour": false, "contourName": "Linear", "contourRange": 50, "contourAntiAlias": false})
|
||||
}
|
||||
"satin" => {
|
||||
json!({"blend": "Multiply", "color": "#000000", "opacity": 50, "angle": 19, "distance": 11, "size": 14, "contour": "Linear", "antiAlias": true, "invert": true})
|
||||
json!({"blend": "Multiply", "color": "#000000", "opacity": 50, "angle": 90, "distance": 50, "size": 80, "contour": "Linear", "antiAlias": true, "invert": true})
|
||||
}
|
||||
_ => json!({}),
|
||||
}
|
||||
@@ -612,9 +612,9 @@ fn fresh_effect(kind: &str) -> Option<Effect> {
|
||||
"satin" => Effect::Satin(Satin {
|
||||
common: FxCommon::new(BlendMode::Multiply, 0.5),
|
||||
color: Color::BLACK,
|
||||
angle: 19.0,
|
||||
distance: 11.0,
|
||||
size: 14.0,
|
||||
angle: 90.0,
|
||||
distance: 50.0,
|
||||
size: 80.0,
|
||||
contour: Contour::Linear,
|
||||
anti_alias: true,
|
||||
invert: true,
|
||||
@@ -1286,6 +1286,9 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod satin_defaults_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod outer_glow_defaults_tests;
|
||||
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
//! #14977: the Satin page's factory values (Multiply, black, 50 %, Angle 90, Distance 50 px,
|
||||
//! Size 80 px, Linear, Anti-aliased on, Invert on) and the rule that a Satin a document already
|
||||
//! carries keeps its stored values. Reset to Default reads the same factory set; the saved Make
|
||||
//! Default path is not measured and keeps today's behaviour. The measured pixels of the factory
|
||||
//! Satin sit within 1 level of the reference application's on the white test document.
|
||||
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
use serde_json::json;
|
||||
|
||||
/// The issue's test document: 400 x 300 px at 72 ppi, RGB 8 bit, a white Background and a pixel
|
||||
/// layer with an orange (255,128,0) rectangle at x 100..299, y 75..224.
|
||||
fn test_document() -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "background": "#ffffff"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 100, "y": 75, "width": 200, "height": 150})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "color", "color": "#ff8000"})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The one Satin the active layer carries.
|
||||
fn satin_of(s: &Session) -> Satin {
|
||||
let d = s.active().unwrap();
|
||||
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
|
||||
match l.effects.items.as_slice() {
|
||||
[Effect::Satin(s)] => s.clone(),
|
||||
other => panic!("no satin: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The flattened test document, as one row-major pixel buffer.
|
||||
fn flattened(s: &Session) -> Vec<[f32; 4]> {
|
||||
let d = s.active().unwrap();
|
||||
photocraft_compose::render(&d.doc, d.doc.bounds()).into_px()
|
||||
}
|
||||
|
||||
/// One 8-bit level of the flattened test document: `channel` 0 is R, 1 G and 2 B.
|
||||
fn level(px: &[[f32; 4]], channel: usize, x: usize, y: usize) -> i32 {
|
||||
(px[y * 400 + x][channel] * 255.0).round() as i32
|
||||
}
|
||||
|
||||
/// Compare an RGB triple with the reference application's, within 1 level.
|
||||
fn assert_rgb(px: &[[f32; 4]], x: usize, y: usize, want: [i32; 3]) {
|
||||
let got = [level(px, 0, x, y), level(px, 1, x, y), level(px, 2, x, y)];
|
||||
assert!(
|
||||
got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1),
|
||||
"({x}, {y}) = {}.{}.{}. the reference gives {}.{}.{}",
|
||||
got[0],
|
||||
got[1],
|
||||
got[2],
|
||||
want[0],
|
||||
want[1],
|
||||
want[2]
|
||||
);
|
||||
}
|
||||
|
||||
/// #14977: Layer > Layer Style > Satin... on a layer without one starts from the reference
|
||||
/// application's factory values. The dialog seeds a new instance from `effect_defaults`.
|
||||
#[test]
|
||||
fn a_new_satin_starts_at_the_factory_values() {
|
||||
let d = effect_defaults("satin");
|
||||
assert_eq!(d["blend"], json!("Multiply"), "blend mode");
|
||||
assert_eq!(d["color"], json!("#000000"), "colour");
|
||||
assert_eq!(d["opacity"], json!(50), "opacity");
|
||||
assert_eq!(d["angle"], json!(90), "angle");
|
||||
assert_eq!(d["distance"], json!(50), "distance");
|
||||
assert_eq!(d["size"], json!(80), "size");
|
||||
assert_eq!(d["contour"], json!("Linear"), "contour");
|
||||
assert_eq!(d["antiAlias"], json!(true), "anti-aliased");
|
||||
assert_eq!(d["invert"], json!(true), "invert");
|
||||
}
|
||||
|
||||
/// #14977: `layer.layerStyle.satin` without params on a layer without one makes the same effect
|
||||
/// the page starts at.
|
||||
#[test]
|
||||
fn a_satin_command_without_params_makes_the_factory_effect() {
|
||||
let mut s = session();
|
||||
s.execute("layer.layerStyle.satin", json!({})).unwrap();
|
||||
let fx = satin_of(&s);
|
||||
assert_eq!(fx.common.blend, BlendMode::Multiply, "blend mode");
|
||||
assert!((fx.common.opacity * 100.0 - 50.0).abs() < 1e-4, "opacity {} %", fx.common.opacity * 100.0);
|
||||
let rgb = fx.color.to_rgb();
|
||||
assert!(rgb.iter().all(|v| v.abs() < 1e-4), "colour {rgb:?} is not black");
|
||||
assert_eq!((fx.angle, fx.distance, fx.size), (90.0, 50.0, 80.0), "angle, distance, size");
|
||||
assert!(matches!(fx.contour, Contour::Linear), "contour {:?}", fx.contour);
|
||||
assert!(fx.anti_alias, "anti-aliased");
|
||||
assert!(fx.invert, "invert");
|
||||
}
|
||||
|
||||
/// #14977: Reset to Default reads these factory values through `layer.layerStyle.defaultFor`.
|
||||
/// A saved Make Default still wins: that path is not measured, so it keeps today's behaviour.
|
||||
#[test]
|
||||
fn reset_to_default_restores_the_satin_factory_values() {
|
||||
let mut s = session();
|
||||
let d = s.execute("layer.layerStyle.defaultFor", json!({"kind": "satin"})).unwrap();
|
||||
assert_eq!(d["user"], json!(false));
|
||||
let p = &d["params"];
|
||||
assert_eq!((p["blend"].as_str(), p["color"].as_str(), p["opacity"].as_f64()), (Some("Multiply"), Some("#000000"), Some(50.0)));
|
||||
assert_eq!((p["angle"].as_f64(), p["distance"].as_f64(), p["size"].as_f64()), (Some(90.0), Some(50.0), Some(80.0)));
|
||||
assert_eq!((p["contour"].as_str(), p["antiAlias"].as_bool(), p["invert"].as_bool()), (Some("Linear"), Some(true), Some(true)));
|
||||
s.execute("layer.layerStyle.makeDefault", json!({"kind": "satin", "params": {"angle": 19, "distance": 11, "size": 14}})).unwrap();
|
||||
let saved = s.execute("layer.layerStyle.defaultFor", json!({"kind": "satin"})).unwrap();
|
||||
assert_eq!(saved["user"], json!(true));
|
||||
assert_eq!(
|
||||
(saved["params"]["angle"].as_f64(), saved["params"]["distance"].as_f64(), saved["params"]["size"].as_f64()),
|
||||
(Some(19.0), Some(11.0), Some(14.0)),
|
||||
"a saved default still wins"
|
||||
);
|
||||
}
|
||||
|
||||
/// #14977 measured: OK on the factory values over the white test document. The G channel down
|
||||
/// the centre column x 200 (every 5 px from y 75), the darkest point at y 149 and 150, the top
|
||||
/// edge and the corners, within 1 level of the reference application's.
|
||||
#[test]
|
||||
fn the_factory_satin_gives_the_measured_profile() {
|
||||
let mut s = test_document();
|
||||
s.execute("layer.layerStyle.satin", json!({})).unwrap();
|
||||
let px = flattened(&s);
|
||||
let column: [i32; 30] =
|
||||
[119, 118, 118, 116, 115, 112, 109, 105, 101, 96, 91, 85, 80, 74, 69, 65, 70, 76, 81, 86, 92, 97, 102, 106, 110, 113, 115, 117, 118, 119];
|
||||
for (i, want) in column.iter().copied().enumerate() {
|
||||
let y = 75 + 5 * i;
|
||||
let got = level(&px, 1, 200, y);
|
||||
assert!((got - want).abs() <= 1, "centre column at (200, {y}): G {got}, the reference gives {want}");
|
||||
}
|
||||
for y in [149, 150] {
|
||||
assert_eq!(level(&px, 1, 200, y), 65, "the darkest point at y {y}");
|
||||
}
|
||||
let top_edge: [i32; 20] = [92, 98, 104, 108, 112, 115, 117, 118, 119, 119, 119, 119, 119, 118, 117, 115, 112, 108, 103, 98];
|
||||
for (i, want) in top_edge.iter().copied().enumerate() {
|
||||
let x = 100 + 10 * i;
|
||||
let got = level(&px, 1, x, 75);
|
||||
assert!((got - want).abs() <= 1, "top edge at ({x}, 75): G {got}, the reference gives {want}");
|
||||
}
|
||||
for y in [75, 76, 77, 78, 79] {
|
||||
assert_rgb(&px, 200, y, [237, 119, 0]);
|
||||
}
|
||||
assert_rgb(&px, 100, 75, [183, 92, 0]);
|
||||
assert_rgb(&px, 100, 150, [128, 64, 0]);
|
||||
assert_rgb(&px, 200, 150, [129, 65, 0]);
|
||||
}
|
||||
|
||||
/// #14977: the values themselves, passed as params, give the same picture the factory defaults
|
||||
/// now must. Guard test, passes before and after: it pins the profile to the effect's own params.
|
||||
#[test]
|
||||
fn the_measured_values_as_params_give_the_same_profile() {
|
||||
let mut s = test_document();
|
||||
s.execute("layer.layerStyle.satin", json!({"angle": 90, "distance": 50, "size": 80})).unwrap();
|
||||
let px = flattened(&s);
|
||||
let column: [i32; 30] =
|
||||
[119, 118, 118, 116, 115, 112, 109, 105, 101, 96, 91, 85, 80, 74, 69, 65, 70, 76, 81, 86, 92, 97, 102, 106, 110, 113, 115, 117, 118, 119];
|
||||
for (i, want) in column.iter().copied().enumerate() {
|
||||
let y = 75 + 5 * i;
|
||||
let got = level(&px, 1, 200, y);
|
||||
assert!((got - want).abs() <= 1, "centre column at (200, {y}): G {got}, the reference gives {want}");
|
||||
}
|
||||
assert_rgb(&px, 100, 75, [183, 92, 0]);
|
||||
assert_rgb(&px, 200, 150, [129, 65, 0]);
|
||||
}
|
||||
|
||||
/// #14977: a Satin the document already carries keeps the values it was read with. The Layer
|
||||
/// Style dialog's OK (and so a PSD or `.pcraft` effect edited in it) goes through
|
||||
/// `layer.layerStyle.replace` with the effect's own snapshot: absent params leave it alone.
|
||||
#[test]
|
||||
fn a_stored_satin_keeps_its_own_values_through_replace() {
|
||||
let mut s = session();
|
||||
s.execute("layer.layerStyle.satin", json!({"angle": 19, "distance": 11, "size": 14})).unwrap();
|
||||
let stored = satin_of(&s);
|
||||
let snapshot = serde_json::to_value(Effect::Satin(stored.clone())).unwrap();
|
||||
s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "satin", "params": {}, "fx": snapshot}]})).unwrap();
|
||||
let kept = satin_of(&s);
|
||||
assert_eq!(kept, stored, "an edited effect list left the satin's values alone");
|
||||
assert_eq!((kept.angle, kept.distance, kept.size), (19.0, 11.0, 14.0), "kept {kept:?}");
|
||||
}
|
||||
|
||||
/// #14977: the same for a saved `.pcraft` round trip -- stored Satin values are read back as they
|
||||
/// were, whatever the factory defaults are.
|
||||
#[test]
|
||||
fn a_pcraft_satin_keeps_its_stored_values() {
|
||||
let mut s = session();
|
||||
s.execute("layer.layerStyle.satin", json!({"angle": 45, "distance": 7, "size": 3, "opacity": 20})).unwrap();
|
||||
let stored = satin_of(&s);
|
||||
let pc = photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap();
|
||||
let again = photocraft_format::load_from_bytes(&pc).unwrap();
|
||||
let read = again
|
||||
.layers
|
||||
.iter()
|
||||
.find_map(|l| l.effects.items.iter().find_map(|e| if let Effect::Satin(x) = e { Some(x.clone()) } else { None }))
|
||||
.expect("the saved document still carries the satin");
|
||||
assert_eq!(read, stored, "the round trip kept the stored values");
|
||||
assert_eq!((read.angle, read.distance, read.size), (45.0, 7.0, 3.0));
|
||||
}
|
||||
@@ -227,7 +227,8 @@ fn adjusted_with_transfer(
|
||||
transfer: adjust::Transfer,
|
||||
) -> Vec<f32> {
|
||||
let fmt = s.format();
|
||||
if fmt.mode == mode && matches!(mode, photocraft_color::ColorMode::Lab | photocraft_color::ColorMode::Cmyk) && adjust::stored_channel_adjustment(adj) {
|
||||
let own_channels = adjust::stored_channel_adjustment(adj) || (mode == photocraft_color::ColorMode::Cmyk && adjust::cmyk_mixer(adj));
|
||||
if fmt.mode == mode && matches!(mode, photocraft_color::ColorMode::Lab | photocraft_color::ColorMode::Cmyk) && own_channels {
|
||||
return adjusted_channels(s, r, selection, |ch| adjust::stored_channels(adj, fmt.mode, Some(fmt.sample), ch));
|
||||
}
|
||||
if fmt.mode == mode && mode == photocraft_color::ColorMode::Cmyk && adjust::cmy_adjustment(adj) {
|
||||
@@ -282,8 +283,10 @@ fn adjusted_channels(s: &Surface, r: Rect, selection: Option<&Surface>, op: impl
|
||||
let Some(out) = out.get_mut(..colors) else { continue };
|
||||
out.copy_from_slice(ch);
|
||||
op(out);
|
||||
// `v·(1−k) + o·k`, as in [`mix_through_selection`]: exact at full coverage, even over
|
||||
// huge 32-bit values whose difference from the result would round it away (#9483).
|
||||
for (v, o) in ch.iter_mut().zip(out.iter()) {
|
||||
*v += (o - *v) * k;
|
||||
*v = *v * (1.0 - k) + o * k;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -405,6 +405,55 @@ fn hue_saturation_and_color_balance_keep_a_cmyk_layers_black() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Layer › New Adjustment Layer › Channel Mixer in a CMYK document makes a mixer with cyan,
|
||||
/// magenta, yellow and black outputs (#8047); its identity leaves the inks alone, the destructive
|
||||
/// command mixes the ink amounts as Photoshop does, and a mix changes only the ink it targets.
|
||||
#[test]
|
||||
fn channel_mixer_in_a_cmyk_document_mixes_the_inks() {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "cmyk", "background": "white"})).unwrap();
|
||||
s.execute("layer.newAdjustmentLayer.channelMixer", json!({})).unwrap();
|
||||
let doc = &s.active().unwrap().doc;
|
||||
let adj = doc
|
||||
.layers
|
||||
.iter()
|
||||
.find_map(|l| match &l.content {
|
||||
photocraft_doc::LayerContent::Adjustment(a) => Some(a.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(adj, Adjustment::ChannelMixer { cmyk: Some(rows), monochrome: false, .. } if rows == photocraft_doc::adjust::CMYK_MIXER_IDENTITY),
|
||||
"{adj:?}"
|
||||
);
|
||||
let params = crate::adjust_params::to_params(&adj);
|
||||
assert!(params.get("cyan").is_some() && params.get("red").is_none(), "{params}");
|
||||
|
||||
let cmyk = PixelFormat::new(ColorMode::Cmyk, SampleType::U16, true);
|
||||
let ink = [0.2, 0.4, 0.6, 0.1, 1.0];
|
||||
let same = adjusted_pixel(cmyk, &ink, &adj, None);
|
||||
assert!(same.iter().zip(&ink).all(|(g, w)| (g - w).abs() < 1e-4), "identity: {same:?}");
|
||||
// Magenta from itself plus a 20 % constant: 20 % more magenta ink, the rest untouched.
|
||||
let more_magenta = crate::adjust_params::from_params("channelMixer", &json!({"magenta": [0, 100, 0, 0, 20]}), None, ColorMode::Cmyk).unwrap();
|
||||
let got = adjusted_pixel(cmyk, &ink, &more_magenta, None);
|
||||
let want = [0.2, 0.6, 0.6, 0.1, 1.0];
|
||||
assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-4), "magenta: {got:?}");
|
||||
// Black from cyan: the black ink becomes cyan's 20 %.
|
||||
let black_from_cyan = crate::adjust_params::from_params("channelMixer", &json!({"black": [100, 0, 0, 0, 0]}), None, ColorMode::Cmyk).unwrap();
|
||||
let got = adjusted_pixel(cmyk, &ink, &black_from_cyan, None);
|
||||
let want = [0.2, 0.4, 0.6, 0.2, 1.0];
|
||||
assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-4), "black: {got:?}");
|
||||
// An imported monochrome mixer (the command refuses to make one): the mix goes to the black
|
||||
// ink alone.
|
||||
let mut rows = photocraft_doc::adjust::CMYK_MIXER_IDENTITY;
|
||||
rows[0] = [0.0, 0.0, 0.0, 1.0, 0.0];
|
||||
let Adjustment::ChannelMixer { matrix, .. } = &adj else { panic!("{adj:?}") };
|
||||
let mono = Adjustment::ChannelMixer { matrix: *matrix, monochrome: true, cmyk: Some(rows) };
|
||||
let got = adjusted_pixel(cmyk, &ink, &mono, None);
|
||||
let want = [0.0, 0.0, 0.0, 0.1, 1.0];
|
||||
assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-4), "monochrome: {got:?}");
|
||||
}
|
||||
|
||||
/// Two small blocks two billion pixels apart: the content bounds are a grid of 6·10¹³ tiles
|
||||
/// that holds nothing, which no adjustment may materialize.
|
||||
fn distant_blocks(fmt: PixelFormat, default: f32) -> Surface {
|
||||
@@ -469,6 +518,18 @@ fn full_coverage_keeps_the_edit_over_huge_hdr_values() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The same for an edit of a CMYK layer's own channels: a result of 0.5 over a stored cyan of
|
||||
/// 2^26 came out as 0, the difference rounding the stored value away.
|
||||
#[test]
|
||||
fn full_coverage_keeps_a_stored_channel_edit_over_huge_hdr_values() {
|
||||
let fmt = PixelFormat::new(ColorMode::Cmyk, SampleType::F32, true);
|
||||
let mut s = Surface::new(fmt);
|
||||
let big = 67_108_864.0_f32;
|
||||
s.write_pixel(0, 0, &[big, 0.25, 0.25, 0.25, 1.0]);
|
||||
let out = adjusted_channels(&s, Rect::new(0, 0, 1, 1), None, |ch| ch.iter_mut().for_each(|v| *v = 0.5));
|
||||
assert_eq!(out[..4], [0.5, 0.5, 0.5, 0.5]);
|
||||
}
|
||||
|
||||
/// Remapping walks the stored tiles, not the dense rectangle around them: two pixels a million
|
||||
/// pixels apart (a ~4 TB rectangle) flip to their mirrored places.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Edit › Color Settings' named setups (#14229) through the command, every one of them.
|
||||
//!
|
||||
//! In the `global_state` binary, beside `spot_dot_gain.rs` and `text_gamma.rs`, for the same
|
||||
//! reason: a setup sets the process-wide Spot dot gain and Blend Text Colors Using Gamma, which
|
||||
//! other tests' Multichannel and type renders read. The setups themselves are checked value by
|
||||
//! value in `crates/engine/src/color_settings_presets_tests.rs`.
|
||||
|
||||
use photocraft_compose::multichannel::{SPOT_DOT_GAIN, spot_dot_gain};
|
||||
use photocraft_compose::psblend::TEXT_GAMMA;
|
||||
use photocraft_engine::Session;
|
||||
use photocraft_engine::color_cmds::{COLOR_SETTINGS_PRESETS, CUSTOM_SETTINGS};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn every_setup_runs_and_sets_the_compositor() {
|
||||
let _process = crate::lock(&crate::PROCESS);
|
||||
let mut s = Session::new();
|
||||
for name in COLOR_SETTINGS_PRESETS {
|
||||
// Blend Text Colors Using Gamma off before: a scripted setup turns it on at 1.45.
|
||||
s.execute("edit.colorSettings", json!({"blendTextGamma": false})).unwrap();
|
||||
let r = s.execute("edit.colorSettings", json!({"preset": name})).unwrap();
|
||||
assert_eq!(r["preset"], name);
|
||||
assert_eq!(r["settings"]["blendTextGamma"], json!(TEXT_GAMMA), "{name}");
|
||||
// The compositor follows the setup's Spot dot gain.
|
||||
let spot = r["settings"]["spotDotGain"].as_f64().unwrap() as f32;
|
||||
assert_eq!(spot_dot_gain(), spot, "{name}");
|
||||
assert!(matches!(spot, 15.0 | 20.0 | 25.0), "{name}: {spot}");
|
||||
}
|
||||
// Changing Blend Text Colors Using Gamma alone also makes the values Custom.
|
||||
s.execute("edit.colorSettings", json!({"preset": "Europe Prepress 3"})).unwrap();
|
||||
let r = s.execute("edit.colorSettings", json!({"blendTextGamma": 1.8})).unwrap();
|
||||
assert_eq!(r["preset"], CUSTOM_SETTINGS);
|
||||
assert_eq!(spot_dot_gain(), 15.0, "the setup's other values stay");
|
||||
s.execute("edit.colorSettings", json!({"reset": true})).unwrap();
|
||||
assert_eq!(spot_dot_gain(), SPOT_DOT_GAIN);
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
//! `it` so plain `cargo test` runs them without the rest of the suite.
|
||||
|
||||
mod artboard_export_scratch;
|
||||
mod color_settings_presets;
|
||||
mod lut_row_cache_purge;
|
||||
mod mask_cache_purge;
|
||||
mod memory_gate;
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! A CMYK Channel Mixer's ink rows (`Adjustment::ChannelMixer::cmyk`, #8047) survive a `.pcraft`
|
||||
//! round trip; manifests written before the field existed load as a mixer without them
|
||||
//! (`cmyk: None`), as `#[serde(default)]` promises.
|
||||
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_doc::{Adjustment, Document, Layer, LayerContent, Size};
|
||||
use photocraft_format::*;
|
||||
|
||||
/// The first layer's adjustment, if the first layer is an adjustment layer.
|
||||
fn adjustment_of(d: &Document) -> Option<&Adjustment> {
|
||||
match &d.layers.first()?.content {
|
||||
LayerContent::Adjustment(a) => Some(a),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves and reloads a CMYK mixer, then drops the `cmyk` key from its manifest entry (what
|
||||
/// builds before #8047 wrote) and checks the older entry still loads, with `cmyk: None` and the
|
||||
/// rest of the mixer kept.
|
||||
#[test]
|
||||
fn cmyk_mixer_rows_round_trip_and_older_manifests_load_without_them() {
|
||||
let mut doc = Document::new("mixer", Size::new(8, 8), ColorMode::Cmyk, SampleType::U8);
|
||||
let matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
|
||||
let rows = [[0.8, 0.3, -0.1, 0.0, 0.0], [0.1, 0.9, 0.0, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0, 0.0], [0.0; 5]];
|
||||
let mixer = Adjustment::ChannelMixer { matrix, monochrome: false, cmyk: Some(rows) };
|
||||
doc.layers.push(Layer::new("Channel Mixer 1", LayerContent::Adjustment(mixer.clone())));
|
||||
let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
|
||||
assert_eq!(adjustment_of(&load_from_bytes(&bytes).unwrap()), Some(&mixer));
|
||||
|
||||
let m = read_manifest(&bytes).unwrap();
|
||||
let mut v = serde_json::to_value(&m.document).unwrap();
|
||||
let fields = &mut v["layers"][0]["content"]["adjustment"]["ChannelMixer"];
|
||||
assert!(fields.as_object_mut().unwrap().remove("cmyk").is_some(), "{fields}");
|
||||
let old: manifest::DocM = serde_json::from_value(v).unwrap();
|
||||
let manifest::ContentM::Adjustment { adjustment } = &old.layers[0].content else { panic!("not an adjustment layer") };
|
||||
assert_eq!(*adjustment, Adjustment::ChannelMixer { matrix, monochrome: false, cmyk: None });
|
||||
|
||||
// An RGB mixer writes no `cmyk` key, so builds before #8047 read it exactly as before.
|
||||
let rgb = Adjustment::ChannelMixer { matrix: [[0.5, 0.5, 0.0, 0.0], matrix[1], matrix[2]], monochrome: false, cmyk: None };
|
||||
let json = serde_json::to_value(&rgb).unwrap();
|
||||
assert!(json["ChannelMixer"].get("cmyk").is_none(), "{json}");
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
mod analysis;
|
||||
mod autosave;
|
||||
mod camera_raw_roundtrip;
|
||||
mod channel_mixer_cmyk;
|
||||
mod common;
|
||||
mod corruption;
|
||||
mod directory_symlinks;
|
||||
|
||||
@@ -18,17 +18,26 @@ impl B {
|
||||
// shadow_map
|
||||
let angle = if s.use_global_light { light.angle } else { s.angle };
|
||||
let (dx, dy) = offset(angle, s.distance);
|
||||
// #14933: a Size 1 inner shadow with Choke 0. `blur_kernel(1.0)` is the identity, and the
|
||||
// `× shape` step below would then remove the whole shadow, exactly as on the CPU. Both
|
||||
// compositors expand the inverted shape by the ¼–½–¼ taps instead
|
||||
// (`photocraft_compose::effects::size_one_kernel`, the kernel `shadow_map` applies).
|
||||
// #14934: an Anti-aliased Inner Shadow takes the CPU's sub-pixel source offset, on the
|
||||
// CPU's gate only (`fx::aa_shift`: the inner branch, the Gaussian contour, and a Size and
|
||||
// Choke that leave the map a shift plus a blur that is not the identity). A Drop Shadow
|
||||
// keeps today's map (#14881). At a Choke that dilates the CPU recomputes its dilation
|
||||
// distance on the offset map while this builder shifts the whole-pixel field of the
|
||||
// unshifted shape, and at a blur of width 1 the offset would be the whole map: both
|
||||
// neighbours take no offset here, which is what keeps them equal on both compositors
|
||||
// neighbours take no offset here — which covers the Size 1 case above —, which is what
|
||||
// keeps them equal on both compositors
|
||||
// (`anti_aliased_inner_shadow_gated_neighbours_match_the_cpu`).
|
||||
let aa = fx::aa_shift(inner && s.anti_alias, &s.contour, s.size, s.spread);
|
||||
let src = self.shift(In::Shape, dx + aa, dy + aa, if inner { 1.0 } else { 0.0 }, inner);
|
||||
let m = self.spread_blur(src, (s.size, s.spread), inner, dx, dy);
|
||||
let m = if inner && s.size == 1.0 && s.spread == 0.0 {
|
||||
self.conv(src, fx::size_one_kernel())
|
||||
} else {
|
||||
self.spread_blur(src, (s.size, s.spread), inner, dx, dy)
|
||||
};
|
||||
self.finish(m, None, false, &s.contour, inner, 0);
|
||||
1
|
||||
}
|
||||
|
||||
@@ -318,6 +318,41 @@ fn bands_end_at_the_coordinate_ceiling() {
|
||||
assert_eq!(super::bands(Rect::new(0, 0, 8, 10), 0).len(), 10, "a zero step still makes progress");
|
||||
}
|
||||
|
||||
/// #14933: the Size 1 Inner Shadow program convolves the ¼–½–¼ taps the CPU's `shadow_map`
|
||||
/// applies, instead of dropping the identity width-1 blur, so both compositors build the same map.
|
||||
/// A Size 6 inner shadow still takes the tent of its own size, untouched.
|
||||
#[test]
|
||||
fn size_one_inner_shadow_convolves_the_cpus_kernel() {
|
||||
use crate::plan::Kernel;
|
||||
let light = GlobalLight::default();
|
||||
let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() };
|
||||
s.distance = 0.0;
|
||||
s.spread = 0.0;
|
||||
let mut blurs = |size: f32| {
|
||||
s.size = size;
|
||||
program(&Effect::InnerShadow(s.clone()), &light, false)
|
||||
.stages
|
||||
.into_iter()
|
||||
.filter(|st| st.kernel == Kernel::MBlur)
|
||||
.map(|st| (st.radius, st.lut.map(|l| (*l).clone()).unwrap_or_default()))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let one = blurs(1.0);
|
||||
assert_eq!(one.len(), 2, "two separable passes over the Size 1 inner shadow map");
|
||||
let (r1, w1) = photocraft_compose::effects::size_one_kernel();
|
||||
for (radius, lut) in &one {
|
||||
assert_eq!(*radius, r1, "the Size 1 kernel radius");
|
||||
assert_eq!(lut.as_slice(), w1.as_slice(), "the taps the CPU map applies");
|
||||
}
|
||||
let (r6, w6) = photocraft_compose::effects::tent_kernel(6.0);
|
||||
let six = blurs(6.0);
|
||||
assert_eq!(six.len(), 2, "a Size 6 inner shadow still blurs twice");
|
||||
for (radius, lut) in &six {
|
||||
assert_eq!(*radius, r6);
|
||||
assert_eq!(lut.as_slice(), w6.as_slice(), "Size 6 stays on the tent");
|
||||
}
|
||||
}
|
||||
|
||||
/// #14934: the GPU's Inner Shadow program takes the same sub-pixel source offset as the CPU's
|
||||
/// `shadow_map` - without a device, by asking what stages the effect builds. The measured gate
|
||||
/// (Anti-aliased on, Gaussian contour, the inner branch) is what adds the stage; a Linear contour
|
||||
|
||||
@@ -159,8 +159,10 @@ fn to_row(t: &[f32]) -> [f32; 4096] {
|
||||
/// and a CMYK document on its inks (`cmyk_channel_adjustment`), which only the CPU does.
|
||||
pub fn adjustment_on_gpu(adj: &Adjustment, mode: photocraft_color::ColorMode) -> bool {
|
||||
use photocraft_compose::adjust::{cmyk_channel_adjustment, lab_channel_adjustment};
|
||||
// A CMYK Channel Mixer mixes inks, in any document.
|
||||
let tone_in_space =
|
||||
matches!(adj, Adjustment::Levels { space: ToneSpace::Cmyk | ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Cmyk | ToneSpace::Lab, .. });
|
||||
matches!(adj, Adjustment::Levels { space: ToneSpace::Cmyk | ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Cmyk | ToneSpace::Lab, .. })
|
||||
|| photocraft_compose::adjust::cmyk_mixer(adj);
|
||||
let own_channels = match mode {
|
||||
photocraft_color::ColorMode::Lab => lab_channel_adjustment(adj),
|
||||
photocraft_color::ColorMode::Cmyk => cmyk_channel_adjustment(adj),
|
||||
@@ -257,7 +259,7 @@ pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraf
|
||||
p[2] = [b[4], b[5], b[6], 0.0];
|
||||
(9, p, None)
|
||||
}
|
||||
Adjustment::ChannelMixer { matrix, monochrome } => {
|
||||
Adjustment::ChannelMixer { matrix, monochrome, .. } => {
|
||||
// compose::adjust: 32-bit documents cut each percentage to 1/1024, count 255/512 of
|
||||
// the constant and don't clip (the shader checks F_HDR).
|
||||
let hdr = depth == photocraft_color::SampleType::F32;
|
||||
|
||||
@@ -68,8 +68,8 @@ fn hdr_adjustments_preserve_range_and_cpu_parity() {
|
||||
// 32-bit Photoshop rules: unclipped, legacy pivot 127, the mixer's 1/1024 steps and halved constant.
|
||||
Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy: true },
|
||||
Adjustment::BrightnessContrast { brightness: -20.0, contrast: -30.0, legacy: true },
|
||||
Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false },
|
||||
Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0; 4], [0.0; 4]], monochrome: true },
|
||||
Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false, cmyk: None },
|
||||
Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0; 4], [0.0; 4]], monochrome: true, cmyk: None },
|
||||
Adjustment::PhotoFilter { color: [0.97, 0.76, 0.0], density: 0.4, preserve_luminosity: true },
|
||||
Adjustment::PhotoFilter { color: [0.2, 0.6, 0.9], density: 0.3, preserve_luminosity: false },
|
||||
Adjustment::BlackWhite { weights: [70.0, 20.0, 50.0, 10.0, 90.0, 30.0], tint: Some([0.9, 0.7, 0.5]) },
|
||||
@@ -767,8 +767,8 @@ fn adjustments() -> Vec<Adjustment> {
|
||||
Adjustment::Vibrance { vibrance: 50.0, saturation: -20.0 },
|
||||
Adjustment::Vibrance { vibrance: -60.0, saturation: 0.0 },
|
||||
Adjustment::Vibrance { vibrance: 0.0, saturation: -100.0 },
|
||||
Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false },
|
||||
Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.0], [0.0; 4], [0.0; 4]], monochrome: true },
|
||||
Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false, cmyk: None },
|
||||
Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.0], [0.0; 4], [0.0; 4]], monochrome: true, cmyk: None },
|
||||
Adjustment::PhotoFilter { color: [0.9, 0.6, 0.2], density: 0.4, preserve_luminosity: true },
|
||||
Adjustment::PhotoFilter { color: [0.2, 0.6, 0.9], density: 0.3, preserve_luminosity: false },
|
||||
Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None },
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! Every [`Adjustment`] kind is written (`vibA`, `blnc`, `blwh`, `phfl` and `mixr` included);
|
||||
//! a Color Lookup without a table is written as an identity cube and a Gradient Map with fewer
|
||||
//! than two stops as the equivalent two-stop gradient, so nothing is dropped on save. Blocks
|
||||
//! that cannot be read (noise gradients, profile lookups, CMYK channel mixers, unknown versions)
|
||||
//! that cannot be read (noise gradients, profile lookups, ink channel mixers outside CMYK documents, unknown versions)
|
||||
//! stay [`Adjustment::Unsupported`] and are written back verbatim.
|
||||
|
||||
use craft_psd::descriptor::{Descriptor, Value, VersionedDescriptor};
|
||||
@@ -167,9 +167,13 @@ pub fn unreadable_reason(key: &[u8; 4], data: &[u8]) -> Option<String> {
|
||||
/// (modern brightness/contrast parameters). Levels/Curves store the
|
||||
/// composite record first, then one per document channel (see [`Channels`]).
|
||||
pub fn parse(key: &[u8; 4], data: &[u8], cged: Option<&[u8]>, channels: Channels) -> Adjustment {
|
||||
// A CMYK Channel Mixer (any record using the fourth, black, source) has no RGB meaning:
|
||||
// keep it raw. Mixers written by `write` leave that source at 0 and map in every mode.
|
||||
if key == b"mixr" && matches!(channels, Channels::Cmyk | Channels::Other) && (0..).map_while(|r| bei16(data, 4 + r * 10 + 6)).any(|k| k != 0) {
|
||||
// A CMYK document's mixer has Photoshop's four ink outputs.
|
||||
if key == b"mixr" && channels == Channels::Cmyk && !legacy_rgb_mixer(data) {
|
||||
return parse_cmyk_mixer(data).unwrap_or_else(|| unsupported(key, data));
|
||||
}
|
||||
// In other modes a mixer using the fourth (black) source has no RGB meaning: keep it raw.
|
||||
// Mixers written by `write` from RGB outputs leave that source at 0.
|
||||
if key == b"mixr" && channels != Channels::Cmyk && (0..).map_while(|r| bei16(data, 4 + r * 10 + 6)).any(|k| k != 0) {
|
||||
return unsupported(key, data);
|
||||
}
|
||||
let mut a = parse_any(key, data, cged);
|
||||
@@ -668,7 +672,48 @@ fn parse_channel_mixer(d: &[u8]) -> Option<Adjustment> {
|
||||
let first = rec(0)?;
|
||||
// A monochrome block may carry only the gray record.
|
||||
let (g, b) = if monochrome { (rec(1).unwrap_or([0.0; 4]), rec(2).unwrap_or([0.0; 4])) } else { (rec(1)?, rec(2)?) };
|
||||
Some(Adjustment::ChannelMixer { matrix: [first, g, b], monochrome })
|
||||
Some(Adjustment::ChannelMixer { matrix: [first, g, b], monochrome, cmyk: None })
|
||||
}
|
||||
|
||||
/// `mixr` in a CMYK document: the same layout with four output records (cyan, magenta,
|
||||
/// yellow, black), each using all four sources (cyan, magenta, yellow, black) and the constant,
|
||||
/// on ink amounts. Photoshop writes exactly these four records (photoshop corpus cmyk8 and
|
||||
/// cmyk16 channel-mixer.psd: a 44-byte block whose black record is all zeros, and whose merged
|
||||
/// image has no black ink). A monochrome block may carry only its first record (the mix the
|
||||
/// black ink gets); no Photoshop sample of one exists yet, and an unedited one is saved back as
|
||||
/// it was read.
|
||||
/// A Channel Mixer block PhotoCraft wrote in its RGB layout before CMYK mixers were read
|
||||
/// ([`encode::channel_mixer`]): its fourth record repeats the first and no record uses the black
|
||||
/// source. Read as CMYK rows, that fourth record would set the black ink to the cyan mix
|
||||
/// (`K' = C`), so such a block in a CMYK document keeps the RGB reading it had. A CMYK block
|
||||
/// whose black output is exactly the cyan mix with no black source would read the same way.
|
||||
fn legacy_rgb_mixer(d: &[u8]) -> bool {
|
||||
let record = |r: usize| d.get(4 + r * 10..4 + (r + 1) * 10);
|
||||
let no_black = (0..4).all(|r| record(r).and_then(|rec| rec.get(6..8)) == Some(&[0, 0][..]));
|
||||
d.len() == 44 && no_black && record(0).is_some() && record(0) == record(3)
|
||||
}
|
||||
|
||||
fn parse_cmyk_mixer(d: &[u8]) -> Option<Adjustment> {
|
||||
if be16(d, 0)? != 1 {
|
||||
return None;
|
||||
}
|
||||
let monochrome = be16(d, 2)? != 0;
|
||||
let rec = |r: usize| -> Option<[f32; 5]> {
|
||||
let at = 4 + r * 10;
|
||||
let v = |k: usize| bei16(d, at + k * 2).map(|x| f32::from(x).clamp(-200.0, 200.0) / 100.0);
|
||||
Some([v(0)?, v(1)?, v(2)?, v(3)?, v(4)?])
|
||||
};
|
||||
let identity = photocraft_doc::adjust::CMYK_MIXER_IDENTITY;
|
||||
let mut rows = identity;
|
||||
for (r, row) in rows.iter_mut().enumerate() {
|
||||
*row = match rec(r) {
|
||||
Some(v) => v,
|
||||
None if monochrome && r > 0 => identity[r],
|
||||
None => return None,
|
||||
};
|
||||
}
|
||||
let matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
|
||||
Some(Adjustment::ChannelMixer { matrix, monochrome, cmyk: Some(rows) })
|
||||
}
|
||||
|
||||
fn put16(v: &mut Vec<u8>, x: u16) {
|
||||
@@ -689,6 +734,44 @@ fn levels_write(v: &mut Vec<u8>, c: &LevelsChannel) {
|
||||
put16(v, (c.gamma * 100.0).round().clamp(1.0, 999.0) as u16);
|
||||
}
|
||||
|
||||
/// The Channel Mixer `adj` reshaped for a document whose `mixr` records are `channels`, or None
|
||||
/// when it already has that shape (or is not a mixer). A PSD stores no output shape: a CMYK
|
||||
/// document reads four ink records and every other mode three RGB records, so a mixer of the
|
||||
/// other shape could not be read back as it is. An RGB mixer in a CMYK document becomes ink
|
||||
/// outputs (cyan from the red row, magenta from green, yellow from blue, sources red, green,
|
||||
/// blue as cyan, magenta, yellow) with black passed through; a CMYK mixer elsewhere keeps its
|
||||
/// cyan, magenta and yellow rows as red, green and blue without the black source. A CMYK mixer
|
||||
/// mixes ink amounts and an RGB one light (ink = 1 - light, ignoring black), so each row keeps
|
||||
/// its sources and its constant becomes `complement_constant`. Either is an approximation, so
|
||||
/// the caller warns.
|
||||
pub fn mixer_for(adj: &Adjustment, channels: Channels) -> Option<Adjustment> {
|
||||
let Adjustment::ChannelMixer { matrix, monochrome, cmyk } = adj else { return None };
|
||||
match (cmyk, channels == Channels::Cmyk) {
|
||||
(None, true) => {
|
||||
let mut rows = photocraft_doc::adjust::CMYK_MIXER_IDENTITY;
|
||||
for (row, m) in rows.iter_mut().zip(matrix) {
|
||||
*row = [m[0], m[1], m[2], 0.0, complement_constant(m[0], m[1], m[2], m[3])];
|
||||
}
|
||||
let matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
|
||||
Some(Adjustment::ChannelMixer { matrix, monochrome: *monochrome, cmyk: Some(rows) })
|
||||
}
|
||||
(Some(rows), false) => {
|
||||
let matrix = std::array::from_fn(|i| rows.get(i).map_or([0.0; 4], |r| [r[0], r[1], r[2], complement_constant(r[0], r[1], r[2], r[4])]));
|
||||
Some(Adjustment::ChannelMixer { matrix, monochrome: *monochrome, cmyk: None })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The constant of a mixer row with sources `a`, `b`, `c` and constant `k` once it mixes the
|
||||
/// complements of its inputs and output (ink for light, or light for ink): 1 - a - b - c - k,
|
||||
/// since 1 - (a(1 - x) + b(1 - y) + c(1 - z) + k) = ax + by + cz + (1 - a - b - c - k). It is
|
||||
/// rounded to the whole percent a `mixr` record stores and kept to its -200..200 %, so the saved
|
||||
/// block reads back the same.
|
||||
fn complement_constant(a: f32, b: f32, c: f32, k: f32) -> f32 {
|
||||
((1.0 - a - b - c - k) * 100.0).round().clamp(-200.0, 200.0) / 100.0
|
||||
}
|
||||
|
||||
/// Serializes an adjustment into its PSD blocks: `(key, data)` pairs
|
||||
/// (Brightness/Contrast also writes a `CgEd` descriptor). Every evaluated kind has an
|
||||
/// encoding; the result is empty only for an [`Adjustment::Unsupported`] with a malformed key.
|
||||
@@ -729,7 +812,8 @@ pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec<u8>)> {
|
||||
Adjustment::PhotoFilter { color, density, preserve_luminosity } => {
|
||||
return block(b"phfl", encode::photo_filter(*color, *density, *preserve_luminosity));
|
||||
}
|
||||
Adjustment::ChannelMixer { matrix, monochrome } => {
|
||||
Adjustment::ChannelMixer { cmyk: Some(rows), monochrome, .. } => return block(b"mixr", encode::channel_mixer_cmyk(rows, *monochrome)),
|
||||
Adjustment::ChannelMixer { matrix, monochrome, cmyk: None } => {
|
||||
return block(b"mixr", encode::channel_mixer(matrix, *monochrome));
|
||||
}
|
||||
Adjustment::Unsupported { psd_key, raw } => {
|
||||
|
||||
@@ -237,3 +237,16 @@ pub(super) fn channel_mixer(matrix: &[[f32; 4]; 3], monochrome: bool) -> Vec<u8>
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// CMYK Channel Mixer payload: the cyan, magenta, yellow and black records (each C, M, Y, K and
|
||||
/// constant), 44 bytes as Photoshop writes them (photoshop corpus cmyk8 and cmyk16
|
||||
/// channel-mixer.psd). With `monochrome` the first record is the black ink's mix.
|
||||
pub(super) fn channel_mixer_cmyk(rows: &[[f32; 5]; 4], monochrome: bool) -> Vec<u8> {
|
||||
let mut v = words(&[1, u16::from(monochrome)]);
|
||||
for row in rows {
|
||||
for x in row {
|
||||
v.extend_from_slice(&clamp_i16((x * 100.0).clamp(-200.0, 200.0)).to_be_bytes());
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
@@ -221,8 +221,8 @@ fn roundtrips() {
|
||||
let q = |v: u16| f32::from(v) / 65535.0;
|
||||
rt(Adjustment::PhotoFilter { color: [q(60000), q(30000), q(0)], density: 0.25, preserve_luminosity: true });
|
||||
rt(Adjustment::PhotoFilter { color: [q(0), q(40000), q(65535)], density: 1.0, preserve_luminosity: false });
|
||||
rt(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false });
|
||||
rt(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0, 1.0, 0.0, 0.0], [-2.0, 0.0, 2.0, 0.0]], monochrome: true });
|
||||
rt(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false, cmyk: None });
|
||||
rt(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0, 1.0, 0.0, 0.0], [-2.0, 0.0, 2.0, 0.0]], monochrome: true, cmyk: None });
|
||||
let id = craft_cms::lutfile::LutFile::identity(5).unwrap();
|
||||
let cube = craft_cms::lutfile::write_cube(&id).into_bytes();
|
||||
let source = Some(LutSource { format: LutFormat::Cube, bytes: std::sync::Arc::new(cube) });
|
||||
@@ -452,17 +452,35 @@ fn malformed_adjustments_are_unsupported() {
|
||||
}
|
||||
|
||||
fn malformed_channel_mixers_are_unsupported() {
|
||||
// A CMYK mixer (black source used) maps to ink outputs in CMYK documents and stays raw
|
||||
// in modes without inks; our own RGB layout maps there.
|
||||
let mut cmyk = i16s(&[1, 0]);
|
||||
for r in 0..4 {
|
||||
cmyk.extend(i16s(&std::array::from_fn::<i16, 5, _>(|k| if k == r { 100 } else { 0 })));
|
||||
}
|
||||
for channels in [Channels::Cmyk, Channels::Other] {
|
||||
assert!(matches!(parse(b"mixr", &cmyk, None, channels), Adjustment::Unsupported { .. }));
|
||||
}
|
||||
let ours = write(&Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false });
|
||||
for channels in [Channels::Cmyk, Channels::Other] {
|
||||
assert!(matches!(parse(b"mixr", &ours[0].1, None, channels), Adjustment::ChannelMixer { .. }));
|
||||
}
|
||||
assert!(
|
||||
matches!(parse(b"mixr", &cmyk, None, Channels::Cmyk), Adjustment::ChannelMixer { cmyk: Some(rows), .. } if rows == photocraft_doc::adjust::CMYK_MIXER_IDENTITY)
|
||||
);
|
||||
assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Other), Adjustment::Unsupported { .. }));
|
||||
// Truncated CMYK blocks stay raw (a monochrome one may carry its first record alone).
|
||||
assert!(matches!(parse(b"mixr", &cmyk[..4 + 3 * 10], None, Channels::Cmyk), Adjustment::Unsupported { .. }));
|
||||
assert!(matches!(parse(b"mixr", &[0, 1, 0, 1, 0, 100], None, Channels::Cmyk), Adjustment::Unsupported { .. }));
|
||||
let mut mono = i16s(&[1, 1]);
|
||||
mono.extend(i16s(&[30, 30, 30, 100, 0]));
|
||||
assert!(
|
||||
matches!(parse(b"mixr", &mono, None, Channels::Cmyk), Adjustment::ChannelMixer { cmyk: Some(rows), monochrome: true, .. } if rows[0] == [0.3, 0.3, 0.3, 1.0, 0.0])
|
||||
);
|
||||
let ours = write(&Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false, cmyk: None });
|
||||
assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Other), Adjustment::ChannelMixer { .. }));
|
||||
// Our RGB layout in a CMYK document (written before CMYK mixers were read: its fourth record
|
||||
// repeats the red row) keeps its RGB reading: read as ink rows, the black ink became the cyan mix.
|
||||
let legacy = [[0.8, 0.2, 0.0, 0.05], [0.1, 0.9, 0.0, 0.0], [0.0, 0.3, 0.7, 0.0]];
|
||||
let block = write(&Adjustment::ChannelMixer { matrix: legacy, monochrome: false, cmyk: None });
|
||||
assert!(
|
||||
matches!(parse(b"mixr", &block[0].1, None, Channels::Cmyk), Adjustment::ChannelMixer { cmyk: None, matrix, .. } if matrix == legacy),
|
||||
"{:?}",
|
||||
parse(b"mixr", &block[0].1, None, Channels::Cmyk)
|
||||
);
|
||||
assert!(matches!(parse(b"mixr", &[0, 1, 0, 0, 0, 100], None, Channels::Rgb), Adjustment::Unsupported { .. }));
|
||||
}
|
||||
|
||||
@@ -608,7 +626,7 @@ fn channel_mixer_golden_blocks() {
|
||||
let mut d = i16s(&[1, 0]);
|
||||
d.extend(i16s(&[100, 0, 0, 0, 20, 50, 50, 0, 0, 0, 0, -50, 150, 0, -10]));
|
||||
let a = parse(b"mixr", &d, None, Channels::Rgb);
|
||||
assert_eq!(a, Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.2], [0.5, 0.5, 0.0, 0.0], [0.0, -0.5, 1.5, -0.1]], monochrome: false });
|
||||
assert_eq!(a, Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.2], [0.5, 0.5, 0.0, 0.0], [0.0, -0.5, 1.5, -0.1]], monochrome: false, cmyk: None });
|
||||
// Written with the trailing gray record (a copy of the first row).
|
||||
let w = write(&a);
|
||||
assert_eq!(w[0].1[..d.len()], d[..]);
|
||||
@@ -616,10 +634,76 @@ fn channel_mixer_golden_blocks() {
|
||||
// Monochrome with only the gray record: 30/59/11.
|
||||
let mut m = i16s(&[1, 1]);
|
||||
m.extend(i16s(&[30, 59, 11, 0, 0]));
|
||||
let Adjustment::ChannelMixer { matrix, monochrome: true } = parse(b"mixr", &m, None, Channels::Rgb) else { panic!() };
|
||||
let Adjustment::ChannelMixer { matrix, monochrome: true, .. } = parse(b"mixr", &m, None, Channels::Rgb) else { panic!() };
|
||||
assert_eq!(matrix[0], [0.3, 0.59, 0.11, 0.0]);
|
||||
}
|
||||
|
||||
/// CMYK `mixr` blocks hold four ink records (cyan, magenta, yellow, black), each C, M, Y, K and
|
||||
/// constant, and are written back in Photoshop's own 44-byte layout (photoshop corpus cmyk8 and
|
||||
/// cmyk16 channel-mixer.psd), monochrome or not.
|
||||
#[test]
|
||||
fn cmyk_channel_mixer_blocks_round_trip_with_four_ink_outputs() {
|
||||
// Cyan = 100 % C + 20 % K - 10 % const; magenta = 50 % M + 50 % Y; yellow = 100 % Y;
|
||||
// black = 30 % C + 30 % M + 30 % Y + 100 % K.
|
||||
let rows = [[1.0, 0.0, 0.0, 0.2, -0.1], [0.0, 0.5, 0.5, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.3, 0.3, 0.3, 1.0, 0.0]];
|
||||
let mut d = i16s(&[1, 0]);
|
||||
d.extend(i16s(&[100, 0, 0, 20, -10, 0, 50, 50, 0, 0, 0, 0, 100, 0, 0, 30, 30, 30, 100, 0]));
|
||||
let a = parse(b"mixr", &d, None, Channels::Cmyk);
|
||||
let Adjustment::ChannelMixer { cmyk: Some(got), monochrome: false, .. } = &a else { panic!("{a:?}") };
|
||||
assert_eq!(*got, rows);
|
||||
// Written as the same four ink records, and read back.
|
||||
let w = write(&a);
|
||||
assert_eq!(w[0].0, *b"mixr");
|
||||
assert_eq!(w[0].1, d);
|
||||
assert_eq!(parse(b"mixr", &w[0].1, None, Channels::Cmyk), a);
|
||||
// Photoshop's block (photoshop corpus cmyk8 channel-mixer.psd, set to cyan 80/30/-10,
|
||||
// magenta 10/90/0 +5, yellow 0/20/70 and no black record): read as four ink rows, the black
|
||||
// one empty (the file's merged image has no black ink), and written back byte for byte.
|
||||
let mut ps = i16s(&[1, 0]);
|
||||
ps.extend(i16s(&[80, 30, -10, 0, 0, 10, 90, 0, 0, 5, 0, 20, 70, 0, 0, 0, 0, 0, 0, 0]));
|
||||
assert_eq!(ps.len(), 44);
|
||||
let a = parse(b"mixr", &ps, None, Channels::Cmyk);
|
||||
let Adjustment::ChannelMixer { cmyk: Some(got), monochrome: false, .. } = &a else { panic!("{a:?}") };
|
||||
assert_eq!(*got, [[0.8, 0.3, -0.1, 0.0, 0.0], [0.1, 0.9, 0.0, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0, 0.0], [0.0; 5]]);
|
||||
assert_eq!(write(&a)[0].1, ps);
|
||||
for mono in [false, true] {
|
||||
let m = Adjustment::ChannelMixer {
|
||||
matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
|
||||
monochrome: mono,
|
||||
cmyk: Some([[0.3, 0.3, 0.3, 1.0, 0.05], [0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [-2.0, 0.0, 0.0, 2.0, 0.0]]),
|
||||
};
|
||||
let b = write(&m);
|
||||
assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), m, "monochrome {mono}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A mixer whose outputs don't match the document's mode is reshaped to the mode's own before it
|
||||
/// is written, so the reopened `mixr` block reads back as what was saved (no black output
|
||||
/// borrowed from the gray record, no CMYK block kept raw in an RGB file).
|
||||
#[test]
|
||||
fn channel_mixers_are_reshaped_to_the_document_mode() {
|
||||
let rgb = Adjustment::ChannelMixer { matrix: [[0.0, 1.0, 0.0, 0.1], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, -0.2]], monochrome: false, cmyk: None };
|
||||
let Some(ink) = mixer_for(&rgb, Channels::Cmyk) else { panic!("an RGB mixer in CMYK is reshaped") };
|
||||
let Adjustment::ChannelMixer { cmyk: Some(rows), .. } = &ink else { panic!("{ink:?}") };
|
||||
// Ink = 1 - light, so each constant becomes 1 - sources - constant.
|
||||
assert_eq!(*rows, [[0.0, 1.0, 0.0, 0.0, -0.1], [1.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.2], [0.0, 0.0, 0.0, 1.0, 0.0]]);
|
||||
let b = write(&ink);
|
||||
assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), ink);
|
||||
let cmyk = Adjustment::ChannelMixer {
|
||||
matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
|
||||
monochrome: true,
|
||||
cmyk: Some([[0.3, 0.3, 0.2, 1.0, 0.05], [0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0]]),
|
||||
};
|
||||
let Some(screen) = mixer_for(&cmyk, Channels::Rgb) else { panic!("a CMYK mixer in RGB is reshaped") };
|
||||
assert_eq!(screen, Adjustment::ChannelMixer { matrix: [[0.3, 0.3, 0.2, 0.15], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: true, cmyk: None });
|
||||
let b = write(&screen);
|
||||
assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Rgb), screen);
|
||||
// Matching shapes and other adjustments are left alone.
|
||||
assert_eq!(mixer_for(&rgb, Channels::Rgb), None);
|
||||
assert_eq!(mixer_for(&cmyk, Channels::Cmyk), None);
|
||||
assert_eq!(mixer_for(&Adjustment::Invert, Channels::Cmyk), None);
|
||||
}
|
||||
|
||||
fn vdesc(d: Descriptor) -> Vec<u8> {
|
||||
VersionedDescriptor::new(d).to_bytes()
|
||||
}
|
||||
|
||||
+73
-52
@@ -420,6 +420,78 @@ impl Ex<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The adjustment part of [`Self::content_blocks`] for layer `l` holding `a`: keeps a preserved
|
||||
/// block of `raw` that still decodes to `a` (or a Gradient Map retargeted in place, or the
|
||||
/// verbatim block of an unknown type); otherwise drops the stale blocks from `raw` and pushes
|
||||
/// the regenerated ones onto `regenerated`, warning about anything PSD cannot hold as it is.
|
||||
fn adjustment_blocks(&mut self, l: &Layer, a: &photocraft_doc::Adjustment, raw: &mut Vec<([u8; 4], Vec<u8>)>, regenerated: &mut Vec<([u8; 4], Vec<u8>)>) {
|
||||
let channels = match self.fmt.mode {
|
||||
ColorMode::Rgb => adjust_map::Channels::Rgb,
|
||||
ColorMode::Grayscale => adjust_map::Channels::Gray,
|
||||
ColorMode::Cmyk => adjust_map::Channels::Cmyk,
|
||||
ColorMode::Lab => adjust_map::Channels::Lab,
|
||||
_ => adjust_map::Channels::Other,
|
||||
};
|
||||
let cged = raw.iter().find(|(k, _)| k == b"CgEd").map(|(_, d)| d.clone());
|
||||
let keep = raw.iter().any(|(k, d)| {
|
||||
// A previously saved PhotoCraft v2 Photo Filter block may be 18 bytes.
|
||||
// It parses here, but Photoshop requires four-byte alignment, so repair
|
||||
// that legacy record on re-save rather than preserving the broken bytes.
|
||||
let legacy_phfl = k == b"phfl" && d.starts_with(&[0, 2]) && d.len() % 4 != 0;
|
||||
// Older PhotoCraft builds wrote `grdm` 2 bytes short of four-byte alignment,
|
||||
// which makes Photoshop refuse the file (#8070): regenerate it too.
|
||||
let legacy_grdm = k == b"grdm" && adjust_map::is_unpadded_photocraft_gradient_map(d);
|
||||
!legacy_phfl && !legacy_grdm && adjust_map::ADJUSTMENT_KEYS.contains(&k) && adjust_map::parse(k, d, cged.as_deref(), channels) == *a
|
||||
});
|
||||
// A Gradient Map whose stops are unchanged keeps the file's own block (stops in
|
||||
// the document's CMYK/Lab/Gray space, smoothness, method) with Reverse and Dither
|
||||
// updated in place.
|
||||
let keep = keep
|
||||
|| (matches!(a, photocraft_doc::Adjustment::GradientMap { .. })
|
||||
&& raw
|
||||
.iter_mut()
|
||||
.any(|(k, d)| k == b"grdm" && !adjust_map::is_unpadded_photocraft_gradient_map(d) && adjust_map::retarget_gradient_map(d, a, channels)));
|
||||
// An adjustment type no mapper knows (#6575) is its block: kept verbatim, and
|
||||
// never written a second time beside a stale copy.
|
||||
let own = match a {
|
||||
photocraft_doc::Adjustment::Unsupported { psd_key, .. } => Some(psd_key.as_bytes()),
|
||||
_ => None,
|
||||
};
|
||||
let keep =
|
||||
keep || matches!(a, photocraft_doc::Adjustment::Unsupported { raw: r, .. } if raw.iter().any(|(k, d)| own == Some(&k[..]) && d[..] == r[..]));
|
||||
if !keep {
|
||||
raw.retain(|(k, _)| !adjust_map::ADJUSTMENT_KEYS.contains(&k) && k != b"CgEd" && own != Some(&k[..]));
|
||||
// A Channel Mixer whose outputs don't match the document's mode has no
|
||||
// PSD encoding that reads back as it is: save its nearest equivalent.
|
||||
let reshaped = adjust_map::mixer_for(a, channels);
|
||||
let target = reshaped.as_ref().unwrap_or(a);
|
||||
// No Photoshop sample shows a monochrome CMYK `mixr` yet (#8047), so its layout would
|
||||
// be a guess: such a mixer is saved only as the imported block it came from (kept
|
||||
// above), never regenerated, whether it was a CMYK mixer or an RGB one reshaped here.
|
||||
let unconfirmed = matches!(target, photocraft_doc::Adjustment::ChannelMixer { cmyk: Some(_), monochrome: true, .. });
|
||||
if unconfirmed {
|
||||
self.warnings
|
||||
.push(format!("layer \"{}\": monochrome CMYK Channel Mixer is not written to PSD (its Photoshop layout is not confirmed yet)", l.name));
|
||||
return;
|
||||
}
|
||||
if reshaped.is_some() {
|
||||
let shape = if channels == adjust_map::Channels::Cmyk { "cyan, magenta, yellow and black" } else { "red, green and blue" };
|
||||
self.warnings.push(format!("layer \"{}\": Channel Mixer saved with {shape} outputs, the document mode's own", l.name));
|
||||
}
|
||||
let w = adjust_map::write(target);
|
||||
if w.is_empty() {
|
||||
self.warnings.push(format!("layer \"{}\": {} adjustment is not yet written to PSD", l.name, a.label()));
|
||||
}
|
||||
// Photoshop's `clrL` descriptor has no interpolation setting, so the
|
||||
// reopened layer renders trilinear.
|
||||
if matches!(a, photocraft_doc::Adjustment::ColorLookup { tetrahedral: true, .. }) {
|
||||
self.warnings
|
||||
.push(format!("layer \"{}\": Color Lookup tetrahedral interpolation is saved as trilinear (PSD has no interpolation setting)", l.name));
|
||||
}
|
||||
regenerated.extend(w);
|
||||
}
|
||||
}
|
||||
|
||||
/// Content blocks for `l`: preserved raw blocks (with `psd_raw`
|
||||
/// overrides) plus regenerated adjustment/fill blocks. A preserved
|
||||
/// adjustment or fill block is reused verbatim while it still decodes to
|
||||
@@ -496,58 +568,7 @@ impl Ex<'_> {
|
||||
}
|
||||
};
|
||||
match &l.content {
|
||||
LayerContent::Adjustment(a) => {
|
||||
let channels = match self.fmt.mode {
|
||||
ColorMode::Rgb => adjust_map::Channels::Rgb,
|
||||
ColorMode::Grayscale => adjust_map::Channels::Gray,
|
||||
ColorMode::Cmyk => adjust_map::Channels::Cmyk,
|
||||
ColorMode::Lab => adjust_map::Channels::Lab,
|
||||
_ => adjust_map::Channels::Other,
|
||||
};
|
||||
let cged = raw.iter().find(|(k, _)| k == b"CgEd").map(|(_, d)| d.clone());
|
||||
let keep = raw.iter().any(|(k, d)| {
|
||||
// A previously saved PhotoCraft v2 Photo Filter block may be 18 bytes.
|
||||
// It parses here, but Photoshop requires four-byte alignment, so repair
|
||||
// that legacy record on re-save rather than preserving the broken bytes.
|
||||
let legacy_phfl = k == b"phfl" && d.starts_with(&[0, 2]) && d.len() % 4 != 0;
|
||||
// Older PhotoCraft builds wrote `grdm` 2 bytes short of four-byte alignment,
|
||||
// which makes Photoshop refuse the file (#8070): regenerate it too.
|
||||
let legacy_grdm = k == b"grdm" && adjust_map::is_unpadded_photocraft_gradient_map(d);
|
||||
!legacy_phfl && !legacy_grdm && adjust_map::ADJUSTMENT_KEYS.contains(&k) && adjust_map::parse(k, d, cged.as_deref(), channels) == *a
|
||||
});
|
||||
// A Gradient Map whose stops are unchanged keeps the file's own block (stops in
|
||||
// the document's CMYK/Lab/Gray space, smoothness, method) with Reverse and Dither
|
||||
// updated in place.
|
||||
let keep = keep
|
||||
|| (matches!(a, photocraft_doc::Adjustment::GradientMap { .. })
|
||||
&& raw.iter_mut().any(|(k, d)| {
|
||||
k == b"grdm" && !adjust_map::is_unpadded_photocraft_gradient_map(d) && adjust_map::retarget_gradient_map(d, a, channels)
|
||||
}));
|
||||
// An adjustment type no mapper knows (#6575) is its block: kept verbatim, and
|
||||
// never written a second time beside a stale copy.
|
||||
let own = match a {
|
||||
photocraft_doc::Adjustment::Unsupported { psd_key, .. } => Some(psd_key.as_bytes()),
|
||||
_ => None,
|
||||
};
|
||||
let keep = keep
|
||||
|| matches!(a, photocraft_doc::Adjustment::Unsupported { raw: r, .. } if raw.iter().any(|(k, d)| own == Some(&k[..]) && d[..] == r[..]));
|
||||
if !keep {
|
||||
raw.retain(|(k, _)| !adjust_map::ADJUSTMENT_KEYS.contains(&k) && k != b"CgEd" && own != Some(&k[..]));
|
||||
let w = adjust_map::write(a);
|
||||
if w.is_empty() {
|
||||
self.warnings.push(format!("layer \"{}\": {} adjustment is not yet written to PSD", l.name, a.label()));
|
||||
}
|
||||
// Photoshop's `clrL` descriptor has no interpolation setting, so the
|
||||
// reopened layer renders trilinear.
|
||||
if matches!(a, photocraft_doc::Adjustment::ColorLookup { tetrahedral: true, .. }) {
|
||||
self.warnings.push(format!(
|
||||
"layer \"{}\": Color Lookup tetrahedral interpolation is saved as trilinear (PSD has no interpolation setting)",
|
||||
l.name
|
||||
));
|
||||
}
|
||||
regenerated.extend(w);
|
||||
}
|
||||
}
|
||||
LayerContent::Adjustment(a) => self.adjustment_blocks(l, a, &mut raw, &mut regenerated),
|
||||
LayerContent::Fill(f) => fill_rule(&mut raw, &mut regenerated, f),
|
||||
LayerContent::Shape(sh) => {
|
||||
if let Some(f) = &sh.fill {
|
||||
|
||||
@@ -546,6 +546,13 @@ impl Ctx<'_> {
|
||||
if light { "Light" } else { adjust_map::label(k) }
|
||||
));
|
||||
}
|
||||
// Photoshop's CMYK Channel Mixer is checked against its own files, but not yet with
|
||||
// Monochrome on (#8047): say so. Unedited, its block is saved back as it was read.
|
||||
if matches!(adj, photocraft_doc::Adjustment::ChannelMixer { cmyk: Some(_), monochrome: true, .. }) {
|
||||
self.warn(format!(
|
||||
"layer \"{name}\": a monochrome CMYK Channel Mixer may not render as in Photoshop yet; unless edited, it is saved back unchanged"
|
||||
));
|
||||
}
|
||||
LayerContent::Adjustment(adj)
|
||||
} else if let Some(block) = rec.block(b"TySh") {
|
||||
// Only canonical type data with a safe transform can become a text layer. A retained
|
||||
|
||||
@@ -78,8 +78,8 @@ fn adjustments() -> Vec<(Adjustment, bool)> {
|
||||
(Adjustment::BlackWhite { weights: [70.0, 20.0, 50.0, -10.0, 90.0, 130.0], tint: Some([0.9, 0.7, 0.5]) }, true),
|
||||
(Adjustment::PhotoFilter { color: [q16(60620), q16(35455), q16(0)], density: 0.4, preserve_luminosity: true }, true),
|
||||
(Adjustment::PhotoFilter { color: [q16(0), q16(39321), q16(65535)], density: 0.3, preserve_luminosity: false }, true),
|
||||
(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false }, true),
|
||||
(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: true }, true),
|
||||
(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false, cmyk: None }, true),
|
||||
(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: true, cmyk: None }, true),
|
||||
// The LUT file is embedded as loaded (here a .cube), so it reads back with its source.
|
||||
(
|
||||
Adjustment::ColorLookup {
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
//! A CMYK document's Channel Mixer (`mixr` with four ink records, #8047) through PSD: an imported
|
||||
//! block nobody edited is saved back exactly as it was read, whatever its layout; an edited one
|
||||
//! is written in Photoshop's own 44-byte layout, except a monochrome one, whose layout no
|
||||
//! Photoshop sample confirms yet: that is not written. With the `corpus` feature, Photoshop's own CMYK
|
||||
//! mixers (photoshop corpus cmyk8 and cmyk16 channel-mixer.psd) are read, rendered on their inks
|
||||
//! against the files' merged images, and saved back byte for byte.
|
||||
|
||||
use craft_psd::PsdFile;
|
||||
use photocraft_color::{Color, ColorMode, SampleType};
|
||||
use photocraft_doc::{Adjustment, Document, Layer, LayerContent, Size};
|
||||
use photocraft_io::*;
|
||||
|
||||
/// The identity RGB matrix a CMYK mixer carries unused.
|
||||
const RGB_IDENTITY: [[f32; 4]; 3] = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
|
||||
|
||||
/// Big-endian i16 words, as a `mixr` block stores them.
|
||||
fn i16s(v: &[i16]) -> Vec<u8> {
|
||||
v.iter().flat_map(|x| x.to_be_bytes()).collect()
|
||||
}
|
||||
|
||||
/// The `mixr` block data of the first layer record that has one.
|
||||
fn mixr(file: &PsdFile) -> Option<Vec<u8>> {
|
||||
file.layers().iter().find_map(|l| l.block(b"mixr")).map(|b| b.data.clone())
|
||||
}
|
||||
|
||||
/// The document's first adjustment.
|
||||
fn first_adjustment(d: &Document) -> Option<Adjustment> {
|
||||
d.layers.iter().find_map(|l| match &l.content {
|
||||
LayerContent::Adjustment(a) => Some(a.clone()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Exports `d` and parses the PSD it became.
|
||||
fn exported(d: &Document) -> PsdFile {
|
||||
PsdFile::from_bytes(&export(d, "x.psd", &ExportOptions::default()).unwrap().bytes).unwrap()
|
||||
}
|
||||
|
||||
/// A CMYK PSD with a Channel Mixer layer over a white background whose `mixr` block is `block`,
|
||||
/// as another writer could have stored it.
|
||||
fn psd_with_mixr(block: &[u8]) -> Vec<u8> {
|
||||
let mut d = Document::with_background("mixer", Size::new(4, 4), ColorMode::Cmyk, SampleType::U8, Color::WHITE);
|
||||
let adj = Adjustment::ChannelMixer { matrix: RGB_IDENTITY, monochrome: false, cmyk: Some(photocraft_doc::adjust::CMYK_MIXER_IDENTITY) };
|
||||
d.layers.push(Layer::new("Channel Mixer 1", LayerContent::Adjustment(adj)));
|
||||
let mut file = exported(&d);
|
||||
let b = file.layers_mut().iter_mut().flat_map(|l| l.blocks.iter_mut()).find(|b| b.key == *b"mixr").unwrap();
|
||||
b.data = block.to_vec();
|
||||
file.to_bytes().unwrap()
|
||||
}
|
||||
|
||||
/// A monochrome block carrying its first record alone (padded), and a four-record block followed
|
||||
/// by bytes our writer never emits: both import as CMYK mixers (the monochrome one with a
|
||||
/// warning, as no Photoshop sample confirms how it renders), are saved back unchanged while
|
||||
/// unedited; once edited, the four-record one is rewritten as Photoshop's 44 bytes and the
|
||||
/// monochrome one is not written (its layout is unconfirmed).
|
||||
#[test]
|
||||
fn unedited_cmyk_mixer_blocks_are_saved_back_as_read() {
|
||||
let mut mono = i16s(&[1, 1, 30, 30, 30, 100, 0]);
|
||||
mono.extend([0, 0]);
|
||||
let mut long = i16s(&[1, 0, 80, 30, -10, 0, 0, 10, 90, 0, 0, 5, 0, 20, 70, 0, 0, 0, 0, 0, 0, 0]);
|
||||
long.extend([0, 0, 0, 0]);
|
||||
for (block, monochrome) in [(mono, true), (long, false)] {
|
||||
let imp = import("x.psd", &psd_with_mixr(&block)).unwrap();
|
||||
let warned = imp.warnings.iter().any(|w| w.contains("monochrome CMYK Channel Mixer"));
|
||||
assert_eq!(warned, monochrome, "{:?}", imp.warnings);
|
||||
let adj = first_adjustment(&imp.document).unwrap();
|
||||
assert!(matches!(adj, Adjustment::ChannelMixer { cmyk: Some(_), monochrome: m, .. } if m == monochrome), "{adj:?}");
|
||||
assert_eq!(mixr(&exported(&imp.document)), Some(block.clone()), "monochrome {monochrome}: saved back as read");
|
||||
|
||||
let mut doc = imp.document;
|
||||
for l in &mut doc.layers {
|
||||
if let LayerContent::Adjustment(Adjustment::ChannelMixer { cmyk: Some(rows), .. }) = &mut l.content {
|
||||
rows[1][4] = 0.1;
|
||||
}
|
||||
}
|
||||
let r = export(&doc, "x.psd", &ExportOptions::default()).unwrap();
|
||||
let edited = mixr(&PsdFile::from_bytes(&r.bytes).unwrap());
|
||||
let skipped = r.warnings.iter().any(|w| w.contains("monochrome CMYK Channel Mixer is not written"));
|
||||
assert_eq!(skipped, monochrome, "{:?}", r.warnings);
|
||||
if monochrome {
|
||||
// No Photoshop sample confirms the layout: an edited one is not regenerated.
|
||||
assert_eq!(edited, None, "monochrome: edited");
|
||||
} else {
|
||||
let edited = edited.unwrap();
|
||||
assert_eq!(edited.len(), 44, "edited");
|
||||
assert_ne!(edited, block);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An RGB monochrome mixer in a CMYK document (from a `.pcraft` or a mode change) would be
|
||||
/// reshaped into a monochrome CMYK mixer, whose `mixr` layout no Photoshop sample confirms yet
|
||||
/// (#8047): it is not written, with a warning naming the layer; without Monochrome it is
|
||||
/// reshaped and written as before.
|
||||
#[test]
|
||||
fn rgb_monochrome_mixer_in_a_cmyk_document_is_not_written_as_cmyk() {
|
||||
for monochrome in [true, false] {
|
||||
let mut d = Document::with_background("mixer", Size::new(4, 4), ColorMode::Cmyk, SampleType::U8, Color::WHITE);
|
||||
let matrix = [[0.4, 0.4, 0.2, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
|
||||
d.layers.push(Layer::new("Gray Mix", LayerContent::Adjustment(Adjustment::ChannelMixer { matrix, monochrome, cmyk: None })));
|
||||
let r = export(&d, "x.psd", &ExportOptions::default()).unwrap();
|
||||
let block = mixr(&PsdFile::from_bytes(&r.bytes).unwrap());
|
||||
let skipped = r.warnings.iter().any(|w| w.contains("\"Gray Mix\"") && w.contains("monochrome CMYK Channel Mixer is not written"));
|
||||
assert_eq!(skipped, monochrome, "{:?}", r.warnings);
|
||||
if monochrome {
|
||||
assert_eq!(block, None, "no inferred monochrome CMYK block");
|
||||
} else {
|
||||
assert_eq!(block.map(|b| b.len()), Some(44), "reshaped to Photoshop's CMYK layout");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "corpus")]
|
||||
mod corpus {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
/// Photoshop's CMYK Channel Mixer (photoshop corpus cmyk8 and cmyk16 channel-mixer.psd, made
|
||||
/// with cyan 80/30/-10, magenta 10/90/0 +5 and yellow 0/20/70 and no black record): read as
|
||||
/// four ink rows with an empty black one, composited on the inks within 2 levels of 255 of
|
||||
/// Photoshop's merged image (black ink cleared everywhere), and saved back byte for byte.
|
||||
#[test]
|
||||
fn photoshop_cmyk_channel_mixers_read_render_and_save_back() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/photoshop/adjustments");
|
||||
let rows = [[0.8, 0.3, -0.1, 0.0, 0.0], [0.1, 0.9, 0.0, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0, 0.0], [0.0; 5]];
|
||||
for dir in ["cmyk8", "cmyk16"] {
|
||||
let path = root.join(dir).join("channel-mixer.psd");
|
||||
let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e} (run `cargo xtask corpus --all`)", path.display()));
|
||||
let file = PsdFile::from_bytes(&bytes).unwrap();
|
||||
assert_eq!(mixr(&file).map(|d| d.len()), Some(44), "{dir}: Photoshop's block");
|
||||
let imp = import("channel-mixer.psd", &bytes).unwrap();
|
||||
let doc = &imp.document;
|
||||
assert_eq!(first_adjustment(doc), Some(Adjustment::ChannelMixer { matrix: RGB_IDENTITY, monochrome: false, cmyk: Some(rows) }), "{dir}");
|
||||
|
||||
// Photoshop's merged image: planar big-endian samples, each stored as 1 - ink.
|
||||
let h = &file.header;
|
||||
let (w, ht) = (h.width as usize, h.height as usize);
|
||||
let wide = h.depth == 16;
|
||||
let merged = file.decode_merged().unwrap();
|
||||
let plane = w * ht * if wide { 2 } else { 1 };
|
||||
let ink = |c: usize, i: usize| -> f32 {
|
||||
let stored = if wide {
|
||||
let at = c * plane + i * 2;
|
||||
f32::from(u16::from_be_bytes([merged[at], merged[at + 1]])) / 65535.0
|
||||
} else {
|
||||
f32::from(merged[c * plane + i]) / 255.0
|
||||
};
|
||||
1.0 - stored
|
||||
};
|
||||
let flat = photocraft_compose::flatten_to_surface(doc, doc.pixel_format(), None);
|
||||
let mut worst = 0.0f32;
|
||||
for y in 0..ht {
|
||||
for x in 0..w {
|
||||
for (c, ours) in flat.pixel(x as i32, y as i32).into_iter().take(4).enumerate() {
|
||||
worst = worst.max((ours - ink(c, y * w + x)).abs());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(worst <= 2.0 / 255.0, "{dir}: inks differ from Photoshop's by up to {:.2} of 255", worst * 255.0);
|
||||
|
||||
assert_eq!(mixr(&exported(doc)), mixr(&file), "{dir}: saved back as read");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -181,9 +181,18 @@ pub fn gen_doc(mode: ColorMode, depth: SampleType, f: Features) -> Document {
|
||||
Adjustment::ColorBalance { shadows: [10.0, 0.0, -5.0], midtones: [0.0, 20.0, 0.0], highlights: [-30.0, 0.0, 15.0], preserve_luminosity: true },
|
||||
Adjustment::BlackWhite { weights: [50.0, 60.0, 40.0, 60.0, 20.0, 70.0], tint: Some([1.0, 0.8, 0.6]) },
|
||||
Adjustment::PhotoFilter { color: [1.0, f32::from(32768u16) / 65535.0, 0.0], density: 0.25, preserve_luminosity: false },
|
||||
Adjustment::ChannelMixer { matrix: [[0.8, 0.2, 0.0, 0.0], [0.0, 1.0, 0.0, 0.1], [0.1, 0.0, 0.9, 0.0]], monochrome: false },
|
||||
Adjustment::ChannelMixer { matrix: [[0.8, 0.2, 0.0, 0.0], [0.0, 1.0, 0.0, 0.1], [0.1, 0.0, 0.9, 0.0]], monochrome: false, cmyk: None },
|
||||
];
|
||||
let adjs = adjs.into_iter().chain(colour.into_iter().filter(|_| mode != ColorMode::Grayscale));
|
||||
// A CMYK document's Channel Mixer has ink outputs (#8047).
|
||||
let colour = colour.into_iter().map(|a| match a {
|
||||
Adjustment::ChannelMixer { monochrome, .. } if mode == ColorMode::Cmyk => Adjustment::ChannelMixer {
|
||||
matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
|
||||
monochrome,
|
||||
cmyk: Some([[0.8, 0.2, 0.0, 0.1, 0.0], [0.0, 1.0, 0.0, 0.0, 0.1], [0.1, 0.0, 0.9, 0.0, 0.0], [0.2, 0.2, 0.2, 0.8, -0.05]]),
|
||||
},
|
||||
other => other,
|
||||
});
|
||||
let adjs = adjs.into_iter().chain(colour.filter(|_| mode != ColorMode::Grayscale));
|
||||
for (i, a) in adjs.enumerate() {
|
||||
let mut l = Layer::new(format!("adj {i}"), LayerContent::Adjustment(a));
|
||||
l.opacity = g(if i % 2 == 0 { 255 } else { 128 });
|
||||
|
||||
@@ -11,6 +11,7 @@ mod banded;
|
||||
mod blend_modes_corpus;
|
||||
mod cancel;
|
||||
mod channels;
|
||||
mod cmyk_channel_mixer;
|
||||
mod cmyk_composite_export;
|
||||
mod cmyk_export;
|
||||
mod color;
|
||||
|
||||
@@ -16,6 +16,7 @@ suite = ["craft/suite"]
|
||||
[dependencies]
|
||||
chrono = { workspace = true }
|
||||
craft-print = { workspace = true }
|
||||
craft-xml = { workspace = true }
|
||||
craft = { workspace = true, features = ["ui", "layers", "color-ui", "draw", "imaging", "window", "keymap", "automation", "theme-store", "print", "menu", "timeline", "text", "text-font-picker", "font-manager", "quit", "cms", "tracked-serde"] }
|
||||
# Interface translations over the embedded craft-i18n catalogs (`build.rs`, `src/i18n.rs`).
|
||||
craft-i18n = { workspace = true }
|
||||
|
||||
@@ -221,6 +221,9 @@ impl PhotocraftApp {
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if id == "file.scripts.imageProcessor" && e == "There were no source files that could be opened by PhotoCraft." {
|
||||
crate::dialogs::alerts::alert(self, e.clone());
|
||||
}
|
||||
self.ui.status = e.clone();
|
||||
self.ui.status_error = true;
|
||||
// The reference application refuses a locked type layer (#14499) and a missing
|
||||
@@ -434,3 +437,26 @@ const ADDS_LAYER_MASK: [&str; 5] = [
|
||||
"layer.layerMask.hideSelection",
|
||||
"layer.layerMask.fromTransparency",
|
||||
];
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod image_processor_empty_source_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn confirming_image_processor_with_no_source_replaces_the_form_with_an_alert() {
|
||||
let input = tempfile::tempdir().unwrap();
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let ctx = app.ctx().clone();
|
||||
crate::menus::invoke(&mut app, &ctx, "file.scripts.imageProcessor", json!({})).unwrap();
|
||||
let id = app.framework.dialogs.stack().top().unwrap();
|
||||
let output = input.path().join("processed");
|
||||
app.framework.dialogs.set_json_field(&ctx, id, "input", json!(input.path())).unwrap();
|
||||
app.framework.dialogs.set_json_field(&ctx, id, "output", json!(output)).unwrap();
|
||||
|
||||
crate::dialogs::confirm(&mut app, &ctx, id).unwrap();
|
||||
assert!(app.framework.dialogs.get_dyn(id).is_none());
|
||||
assert_eq!(crate::dialogs::alerts::alerts(&app).len(), 1);
|
||||
assert_eq!(app.ui.status, "There were no source files that could be opened by PhotoCraft.");
|
||||
assert!(!output.exists());
|
||||
}
|
||||
}
|
||||
@@ -104,10 +104,11 @@ pub struct CanvasToolMenu {
|
||||
/// Opened with the Content-Aware Move tool inside the active selection (#12194).
|
||||
#[serde(default)]
|
||||
pub inside_selection: bool,
|
||||
/// Opened with the Delete Anchor Point or Convert Point tool over an anchor or a segment of the
|
||||
/// targeted path (#12771, #12744): the engine command that entry runs and its params. It heads
|
||||
/// the path menu, above a separator. The third part is the document id and revision it was read
|
||||
/// from: the knot index means something only there, so the entry expires once either moves on.
|
||||
/// Opened with the Delete Anchor Point or Convert Point tool, or the Pen (#12771, #12744,
|
||||
/// #12915), over an anchor or a segment of the targeted path: the engine command that entry
|
||||
/// runs and its params. It heads the path menu, above a separator. The third part is the
|
||||
/// document id and revision it was read from: the knot index means something only there, so
|
||||
/// the entry expires once either moves on.
|
||||
#[serde(default)]
|
||||
pub point: Option<(String, Value, (u64, u64))>,
|
||||
}
|
||||
@@ -1039,6 +1040,26 @@ fn point_at(app: &PhotocraftApp, target: PathRef, hit: BezierHit) -> Option<(Str
|
||||
Some((command.to_string(), params, stamp))
|
||||
}
|
||||
|
||||
/// The Pen's menu takes the `target`/`hit` the right-click reported as its point entry only in
|
||||
/// the measured configuration (#12915): the Pen in Path mode with no path being drawn, and the
|
||||
/// part on a CLOSED subpath. Its overlay reports the hit exactly as the anchor tools' does (the
|
||||
/// Auto Add/Delete mode the Pen runs by default). The Shape-mode and Pixels-mode right-click and
|
||||
/// an open path's parts are not measured and keep today's plain list, and so does every other case.
|
||||
/// The gate reads no modifiers: `capture` never receives the click's, and with ⌥ held the overlay
|
||||
/// is Convert, which senses the closed path's anchors and straight segments as well, so the row
|
||||
/// appears there too - observed and pinned, not measured.
|
||||
fn pen_point_allowed(app: &PhotocraftApp, target: PathRef, hit: &BezierHit) -> bool {
|
||||
if app.ui.pen.is_some() || app.ui.tool_options.vector_mode != craft::draw::ui::VectorMode::Path {
|
||||
return false;
|
||||
}
|
||||
let subpath = match *hit {
|
||||
BezierHit::Anchor { knot, .. } => knot.subpath,
|
||||
BezierHit::Segment { segment, .. } => segment.subpath,
|
||||
_ => return false,
|
||||
};
|
||||
crate::direct_select::path_of(app, &target).is_some_and(|path| path.subpaths.get(subpath).is_some_and(|sub| sub.closed))
|
||||
}
|
||||
|
||||
const POINT_DELETE: &str = "path.deleteAnchor";
|
||||
const POINT_ADD: &str = "path.addAnchor";
|
||||
|
||||
@@ -1547,6 +1568,10 @@ fn capture(app: &mut PhotocraftApp, menu: &mut CanvasToolMenu, doc: [f64; 2], po
|
||||
{
|
||||
select_right_clicked_anchor(app, target, [knot.subpath, knot.knot]);
|
||||
}
|
||||
} else if menu.tool == Tool::Pen && menu.has_path {
|
||||
// The Pen's overlay reports the right-click's hit as the anchor tools' does; only the
|
||||
// measured configuration heads the menu with the entry (#12915).
|
||||
menu.point = point.filter(|(target, hit)| pen_point_allowed(app, *target, hit)).and_then(|(target, hit)| point_at(app, target, hit));
|
||||
}
|
||||
menu.inside_selection = menu.tool == Tool::ContentAwareMove && selected_at(app, doc);
|
||||
if menu.tool == Tool::ColorSampler {
|
||||
@@ -1863,6 +1888,9 @@ pub(crate) mod tests;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod count_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod pen_anchor_row_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod pen_free_transform_label_tests;
|
||||
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! #12915: with the Pen (Path mode) a right-click on a part of the active CLOSED path heads the
|
||||
//! path menu with one entry above the separator and the usual Pen list: Add Anchor Point on a
|
||||
//! segment, Delete Anchor Point on an anchor; choosing it runs the engine command, one history
|
||||
//! step. On empty canvas, on an open subpath, while a path is being drawn, and in Shape or Pixels
|
||||
//! mode the menu keeps today's list with no top entry; with ⌥ held the row stays, as the menu does
|
||||
//! not read the click's modifiers (pinned below). The shared path document and menu assertions
|
||||
//! come from `delete_anchor_menu_tests` (#12771).
|
||||
|
||||
use egui_kittest::kittest::{NodeT, Queryable as _};
|
||||
use serde_json::json;
|
||||
|
||||
use super::delete_anchor_menu_tests::{assert_top_entry, saved, setup, steps};
|
||||
use super::tests::{harness, pen_clicks, right_click, screen_of};
|
||||
use super::{PEN_MENU, rows};
|
||||
use crate::PhotocraftApp;
|
||||
use crate::state::Tool;
|
||||
use egui::Modifiers;
|
||||
|
||||
/// The Pen in the measured configuration: reset (Auto Add/Delete on) in Path mode, Path 1 targeted.
|
||||
fn pen_setup() -> Box<PhotocraftApp> {
|
||||
let mut app = setup(Tool::Pen);
|
||||
app.ui.tool_options.vector_mode = craft::draw::ui::VectorMode::Path;
|
||||
app.ui.tool_options.pen_auto_add_delete = true;
|
||||
app
|
||||
}
|
||||
|
||||
/// A harness over [`pen_setup`] with a Pen right-click at document point `at` done.
|
||||
fn pen_right_clicked(at: [f32; 2]) -> egui_kittest::Harness<'static, Box<PhotocraftApp>> {
|
||||
let mut h = harness(pen_setup());
|
||||
let p = screen_of(h.state(), at);
|
||||
right_click(&mut h, p, Modifiers::NONE);
|
||||
h
|
||||
}
|
||||
|
||||
/// The Pen's list is open with no anchor-point entry above it.
|
||||
fn assert_no_top_entry(h: &egui_kittest::Harness<'static, Box<PhotocraftApp>>, tool: Tool) {
|
||||
assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.tool == tool && rows(m) == PEN_MENU), "{tool:?}: the path menu is open");
|
||||
assert!(h.query_by_label("Add Anchor Point").is_none() && h.query_by_label("Delete Anchor Point").is_none(), "{tool:?}: no anchor row on top");
|
||||
}
|
||||
|
||||
/// Right-click the middle of the square's top edge (200,300): Add Anchor Point heads the menu,
|
||||
/// above Create Vector Mask; choosing it adds one anchor there, one history step of that name,
|
||||
/// and undo restores the whole path.
|
||||
#[test]
|
||||
fn pen_right_click_on_a_segment_offers_add_anchor_point_on_top_and_it_adds() {
|
||||
let mut h = pen_right_clicked([200.0, 300.0]);
|
||||
assert_top_entry(&h, Tool::Pen, "Add Anchor Point");
|
||||
let before = steps(h.state());
|
||||
let original = saved(h.state());
|
||||
h.get_by_label("Add Anchor Point").click();
|
||||
h.run_steps(2);
|
||||
let path = saved(h.state());
|
||||
assert_eq!(path.subpaths[0].knots.len(), 5);
|
||||
let added = &path.subpaths[0].knots[1].anchor;
|
||||
assert!((added.x - 200.0).abs() < 3.0 && (added.y - 300.0).abs() < 3.0, "the anchor lands where it was clicked: {added:?}");
|
||||
assert_eq!(steps(h.state()), before + 1);
|
||||
assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Add Anchor Point"));
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(&saved(h.state()), &original, "undo restores the whole path");
|
||||
}
|
||||
|
||||
/// Right-click the corner (300,300): Delete Anchor Point heads the menu; choosing it leaves the
|
||||
/// square closed with three anchors, one history step of that name.
|
||||
#[test]
|
||||
fn pen_right_click_on_an_anchor_offers_delete_anchor_point_on_top_and_it_deletes() {
|
||||
let mut h = pen_right_clicked([300.0, 300.0]);
|
||||
assert_top_entry(&h, Tool::Pen, "Delete Anchor Point");
|
||||
let before = steps(h.state());
|
||||
let original = saved(h.state());
|
||||
h.get_by_label("Delete Anchor Point").click();
|
||||
h.run_steps(2);
|
||||
let path = saved(h.state());
|
||||
assert!(path.subpaths[0].closed, "the square stays closed");
|
||||
assert_eq!(path.subpaths[0].knots.len(), 3);
|
||||
assert!(path.subpaths[0].knots.iter().all(|k| (k.anchor.x, k.anchor.y) != (300.0, 300.0)), "(300,300) is gone");
|
||||
assert_eq!(steps(h.state()), before + 1);
|
||||
assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Delete Anchor Point"));
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(&saved(h.state()), &original, "undo restores the whole path");
|
||||
}
|
||||
|
||||
/// Right-click on empty canvas: today's list, no top row, and opening it records no step.
|
||||
#[test]
|
||||
fn pen_right_click_on_empty_canvas_keeps_todays_list() {
|
||||
let mut h = harness(pen_setup());
|
||||
let before = steps(h.state());
|
||||
let p = screen_of(h.state(), [600.0, 100.0]);
|
||||
right_click(&mut h, p, Modifiers::NONE);
|
||||
assert_no_top_entry(&h, Tool::Pen);
|
||||
assert_eq!(steps(h.state()), before, "opening the menu records no history step");
|
||||
}
|
||||
|
||||
/// The click on an OPEN subpath is not measured: it keeps today's list (the guard for the
|
||||
/// closed-path gate in the menu's point entry).
|
||||
#[test]
|
||||
fn pen_right_click_on_an_open_subpath_keeps_todays_list() {
|
||||
let h = pen_right_clicked([550.0, 300.0]);
|
||||
assert_no_top_entry(&h, Tool::Pen);
|
||||
}
|
||||
|
||||
/// The issue names an open path's ENDPOINT as not measured: an anchor click there keeps today's
|
||||
/// list too.
|
||||
#[test]
|
||||
fn pen_right_click_on_an_open_paths_endpoint_keeps_todays_list() {
|
||||
let h = pen_right_clicked([700.0, 300.0]);
|
||||
assert_no_top_entry(&h, Tool::Pen);
|
||||
}
|
||||
|
||||
/// Auto Add/Delete off: the Pen's overlay then senses no part and reports no hit, and the menu
|
||||
/// invents none either - today's list stays (guard test, passes before and after).
|
||||
#[test]
|
||||
fn pen_right_click_without_auto_add_delete_keeps_todays_list() {
|
||||
let mut app = pen_setup();
|
||||
app.ui.tool_options.pen_auto_add_delete = false;
|
||||
let mut h = harness(app);
|
||||
let p = screen_of(h.state(), [200.0, 300.0]);
|
||||
right_click(&mut h, p, Modifiers::NONE);
|
||||
assert_no_top_entry(&h, Tool::Pen);
|
||||
}
|
||||
|
||||
/// While a path is being drawn, the measured case names the plain list: no anchor row, even on
|
||||
/// the open draft's own segment.
|
||||
#[test]
|
||||
fn pen_while_drawing_an_open_path_offers_no_top_entry() {
|
||||
let mut app = pen_setup();
|
||||
pen_clicks(&mut app, &[(150.0, 150.0), (350.0, 150.0)]);
|
||||
assert!(app.ui.pen.is_some(), "a path is being drawn");
|
||||
let mut h = harness(app);
|
||||
let p = screen_of(h.state(), [250.0, 150.0]);
|
||||
right_click(&mut h, p, Modifiers::NONE);
|
||||
assert_no_top_entry(&h, Tool::Pen);
|
||||
}
|
||||
|
||||
/// The Shape-mode right-click is not measured: today's list, no top row.
|
||||
#[test]
|
||||
fn pen_right_click_in_shape_mode_keeps_todays_list() {
|
||||
let mut app = setup(Tool::Pen);
|
||||
app.ui.tool_options.vector_mode = craft::draw::ui::VectorMode::Shape;
|
||||
let mut h = harness(app);
|
||||
let p = screen_of(h.state(), [200.0, 300.0]);
|
||||
right_click(&mut h, p, Modifiers::NONE);
|
||||
assert_no_top_entry(&h, Tool::Pen);
|
||||
}
|
||||
|
||||
/// Pixels mode is not measured either and keeps today's list (the gate names Path, so every other
|
||||
/// mode is out). The Pen's options bar shows Pixels disabled, so no click can select it and the
|
||||
/// option is set directly, as the shape tool's Pixels tests do.
|
||||
#[test]
|
||||
fn pen_right_click_in_pixels_mode_keeps_todays_list() {
|
||||
let mut app = setup(Tool::Pen);
|
||||
app.ui.tool_options.vector_mode = craft::draw::ui::VectorMode::Pixels;
|
||||
let mut h = harness(app);
|
||||
let p = screen_of(h.state(), [200.0, 300.0]);
|
||||
right_click(&mut h, p, Modifiers::NONE);
|
||||
assert_no_top_entry(&h, Tool::Pen);
|
||||
}
|
||||
|
||||
/// ⌥ is held for the Convert overlay (craft-libs `pen::mode::resolve`), which senses the closed
|
||||
/// square's anchors and straight segments too, and the framework reports that secondary click's
|
||||
/// hit whatever the modifiers are: the menu's gate reads the mode and the subpath, not the click's
|
||||
/// modifiers, so the row appears. Observed, and pinned as it is today; choosing it with ⌥ down is
|
||||
/// not measured.
|
||||
#[test]
|
||||
fn pen_right_click_with_option_held_still_gets_the_anchor_row() {
|
||||
let mut h = harness(pen_setup());
|
||||
let p = screen_of(h.state(), [200.0, 300.0]);
|
||||
right_click(&mut h, p, Modifiers::ALT);
|
||||
assert_top_entry(&h, Tool::Pen, "Add Anchor Point");
|
||||
}
|
||||
|
||||
/// The entry is about the path as it was when the menu opened: a control-channel edit meanwhile
|
||||
/// shifts the knots, so choosing the stale entry deletes nothing and adds no step. It is drawn
|
||||
/// disabled for the Pen as well, not only rejected on click (#12771 pattern).
|
||||
#[test]
|
||||
fn a_pen_point_entry_expires_once_the_path_is_edited() {
|
||||
let mut h = pen_right_clicked([300.0, 300.0]);
|
||||
assert_top_entry(&h, Tool::Pen, "Delete Anchor Point");
|
||||
assert!(!h.get_by_label("Delete Anchor Point").accesskit_node().is_disabled(), "enabled while the path is as it was");
|
||||
h.state_mut().run("path.addAnchor", json!({"name": "Path 1", "subpath": 0, "knot": 0, "t": 0.5})).unwrap();
|
||||
let after_add = saved(h.state());
|
||||
assert_eq!(after_add.subpaths[0].knots.len(), 5, "the anchor went in");
|
||||
h.run();
|
||||
assert!(h.get_by_label("Delete Anchor Point").accesskit_node().is_disabled(), "disabled once the path is edited");
|
||||
let n = steps(h.state());
|
||||
let ctx = h.ctx.clone();
|
||||
super::choose(h.state_mut(), &ctx, "path.deleteAnchor");
|
||||
assert_eq!(&saved(h.state()), &after_add, "the stale entry deleted nothing");
|
||||
assert_eq!(steps(h.state()), n, "and added no history step");
|
||||
}
|
||||
|
||||
/// #1056: the Path Selection tool's path menu does not cover these rows — unchanged, guard test
|
||||
/// that passes before and after this change.
|
||||
#[test]
|
||||
fn the_path_selection_tool_still_gets_no_anchor_point_row() {
|
||||
let mut app = setup(Tool::PathSelection);
|
||||
app.ui.tool_options.vector_mode = craft::draw::ui::VectorMode::Path;
|
||||
let mut h = harness(app);
|
||||
let p = screen_of(h.state(), [200.0, 300.0]);
|
||||
right_click(&mut h, p, Modifiers::NONE);
|
||||
assert_no_top_entry(&h, Tool::PathSelection);
|
||||
}
|
||||
|
||||
/// The Delete Anchor Point tool's menu keeps its point entry (the shared mechanism stays wired) —
|
||||
/// guard test that passes before and after this change.
|
||||
#[test]
|
||||
fn the_delete_anchor_point_tool_keeps_its_point_entry() {
|
||||
let mut h = harness(setup(Tool::DeleteAnchorPoint));
|
||||
let p = screen_of(h.state(), [200.0, 300.0]);
|
||||
right_click(&mut h, p, Modifiers::NONE);
|
||||
assert_top_entry(&h, Tool::DeleteAnchorPoint, "Add Anchor Point");
|
||||
}
|
||||
@@ -552,7 +552,13 @@ fn agent_can_inspect_and_choose_pen_make_selection_from_full_context_menu() {
|
||||
let inspected = call(&mut app, &ctx, "ui.inspect", json!({}));
|
||||
assert_eq!(app.ui.canvas_tool_menu.as_ref().unwrap().pos, screen_point(&app, 8.0, 8.0));
|
||||
let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap();
|
||||
assert_eq!(entries.iter().filter(|row| row.get("separator") == Some(&json!(true))).count(), 9);
|
||||
// #12915: (8,8) lies on the closed work path's diagonal, so the menu now leads with the
|
||||
// segment's Add Anchor Point entry above one more separator.
|
||||
assert_eq!(entries.iter().filter(|row| row.get("separator") == Some(&json!(true))).count(), 10);
|
||||
assert!(
|
||||
entries.iter().any(|row| row.get("id") == Some(&json!("path.addAnchor")) && row.get("enabled") == Some(&json!(true))),
|
||||
"the segment entry heads the menu"
|
||||
);
|
||||
assert!(entries.iter().any(|row| row.get("id") == Some(&json!("path.toSelection")) && row.get("enabled") == Some(&json!(true))));
|
||||
assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id":"file.new"}))["ok"], false);
|
||||
let chosen = call(&mut app, &ctx, "ui.context.choose", json!({"id":"path.toSelection"}));
|
||||
|
||||
@@ -299,6 +299,9 @@ pub(crate) mod params {
|
||||
if let (Some(action), Some(footer)) = (footer, family.and_then(|family| family.footer)) {
|
||||
footer(app, ctx, id, &action);
|
||||
}
|
||||
if key.as_deref() == Some(image_processor_ui::COMMAND) {
|
||||
image_processor_ui::take_settings_action(app, ctx, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -481,6 +484,8 @@ pub(crate) fn take_results(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
for taker in TAKERS {
|
||||
taker(app, ctx);
|
||||
}
|
||||
// Color Settings' Settings menu follows each pick and edit, a script's `ui.dialog.set` included (#14229).
|
||||
crate::filter_dialog::reconcile_color_settings(app, ctx);
|
||||
}
|
||||
|
||||
/// One pass of the dialogs: the guide edit follows its dialog, the palette shows, the filter preview and the Preferences window are fed, the
|
||||
|
||||
@@ -372,7 +372,7 @@ fn last_confirmed(app: &PhotocraftApp, kind: &str) -> Option<Value> {
|
||||
/// Opens the dialog for `command` at the kind's neutral settings, except the [`KEEPS_LAST`] ones,
|
||||
/// which keep their last confirmed value.
|
||||
pub fn open(app: &mut PhotocraftApp, command: &str) -> Result<DialogId, String> {
|
||||
let id = open_neutral(app, command).ok_or_else(|| refusal(app, command))?;
|
||||
let id = open_with_params_checked(app, command, &json!({})).map_err(|reason| reason.unwrap_or_else(|| refusal(app, command)))?;
|
||||
let kind = command.strip_prefix(PREFIX).unwrap_or_default();
|
||||
let last = last_confirmed(app, kind);
|
||||
let kept: Map<String, Value> = KEEPS_LAST
|
||||
@@ -389,11 +389,16 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Result<DialogId, String>
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Why `command` has no dialog to open: no document, or no adjustment of that name.
|
||||
/// Why `command` has no dialog to open when the editor gave no reason of its own: no document, or no adjustment of
|
||||
/// that name.
|
||||
fn refusal(app: &PhotocraftApp, command: &str) -> String {
|
||||
if app.session.active().is_none() { "no document".to_string() } else { format!("{command} has no dialog") }
|
||||
}
|
||||
|
||||
/// Why a dialog did not open: `Some` is the editor's refusal of these parameters, to show the user (a CMYK Channel
|
||||
/// Mixer, #8047); `None` means there is no dialog for them.
|
||||
pub(crate) type Refused = Option<String>;
|
||||
|
||||
/// Opens a neutral adjustment dialog using the current edit target.
|
||||
pub fn open_neutral(app: &mut PhotocraftApp, command: &str) -> Option<DialogId> {
|
||||
open_with_params(app, command, &json!({}))
|
||||
@@ -402,7 +407,12 @@ pub fn open_neutral(app: &mut PhotocraftApp, command: &str) -> Option<DialogId>
|
||||
/// Seed an Action's dialog only after resolving its recorded target, so document-space
|
||||
/// defaults cannot overwrite the target's neutral grayscale values.
|
||||
pub(crate) fn open_with_params(app: &mut PhotocraftApp, command: &str, params: &Value) -> Option<DialogId> {
|
||||
let params = if params.is_null() { json!({}) } else { Value::Object(params.as_object()?.clone()) };
|
||||
open_with_params_checked(app, command, params).ok()
|
||||
}
|
||||
|
||||
/// [`open_with_params`], with the reason it did not open.
|
||||
pub(crate) fn open_with_params_checked(app: &mut PhotocraftApp, command: &str, params: &Value) -> Result<DialogId, Refused> {
|
||||
let params = if params.is_null() { json!({}) } else { Value::Object(params.as_object().ok_or(None)?.clone()) };
|
||||
let params = complete_params(app, command, ¶ms).unwrap_or(params);
|
||||
let mut params = app.with_mask_target(command, params);
|
||||
if params.get("target").is_none()
|
||||
@@ -414,13 +424,20 @@ pub(crate) fn open_with_params(app: &mut PhotocraftApp, command: &str, params: &
|
||||
open_hosted(app, command, params, None, None)
|
||||
}
|
||||
|
||||
/// Reopen a captured Smart Filter with document-colour defaults, independent of channel targeting.
|
||||
/// Only the caller's validated snapshot may supply the Smart Filter target.
|
||||
/// [`open_smart_filter_checked`] without the reason (the tests' form).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn open_smart_filter(app: &mut PhotocraftApp, command: &str, params: &Value, target: Value) -> Option<DialogId> {
|
||||
open_smart_filter_checked(app, command, params, target).ok()
|
||||
}
|
||||
|
||||
/// Reopen a captured Smart Filter with document-colour defaults, independent of channel targeting.
|
||||
/// Only the caller's validated snapshot may supply the Smart Filter target. When it does not open, the reason: the
|
||||
/// Layers panel shows an editor's refusal (#8047).
|
||||
pub(crate) fn open_smart_filter_checked(app: &mut PhotocraftApp, command: &str, params: &Value, target: Value) -> Result<DialogId, Refused> {
|
||||
let completed = complete_params(app, command, params);
|
||||
let mut recorded = completed.as_ref().unwrap_or(params).as_object().cloned().unwrap_or_default();
|
||||
recorded.retain(|key, _| !key.starts_with("__"));
|
||||
let index = target.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok())?;
|
||||
let index = target.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or(None)?;
|
||||
open_hosted(app, command, Value::Object(recorded), Some((index, target)), Some(params.clone()))
|
||||
}
|
||||
|
||||
@@ -439,12 +456,12 @@ struct Seeded {
|
||||
/// `colors` row kept. With `normalized` (a Smart Filter edit: the captured parameters) those then replace the parameters
|
||||
/// through the engine's own reading of them, so a Lab `lightness` default cannot be read over recorded `points`. An
|
||||
/// unresolved Levels/Curves target opens with defaults and seeds again in [`take`] once it resolves.
|
||||
fn seed(app: &PhotocraftApp, kind: &str, recorded: &Value, smart: Option<&(usize, Value)>, normalized: Option<&Value>) -> Option<Seeded> {
|
||||
fn seed(app: &PhotocraftApp, kind: &str, recorded: &Value, smart: Option<&(usize, Value)>, normalized: Option<&Value>) -> Result<Seeded, Refused> {
|
||||
let resolved = target_context(app, smart, recorded);
|
||||
let valid_target = !matches!(kind, "levels" | "curves") || resolved.is_ok();
|
||||
let target = resolved.unwrap_or_else(|_| ToneTarget { layer: app.session.active().and_then(|s| s.active_layer), channel: None });
|
||||
let mode = curve_mode(app, kind, &target);
|
||||
let defaults = if valid_target { Some(photocraft_engine::adjust_params::default_for(kind, mode).ok()?) } else { None };
|
||||
let defaults = if valid_target { Some(photocraft_engine::adjust_params::default_for(kind, mode).map_err(|_| None)?) } else { None };
|
||||
let tone_kind = matches!(kind, "levels" | "curves");
|
||||
let gray_target = tone_kind && target.channel.as_ref().is_some_and(|c| c.gray.is_some());
|
||||
let color_set = if tone_kind { target.channel.as_ref().and_then(|c| c.components) } else { None };
|
||||
@@ -502,8 +519,19 @@ fn seed(app: &PhotocraftApp, kind: &str, recorded: &Value, smart: Option<&(usize
|
||||
}
|
||||
let base = Value::Object(params);
|
||||
let cx = value_cx(mode, target.channel.clone(), base.clone());
|
||||
let value = values::from_params(kind, &base, &cx).or_else(|_| values::from_params(kind, &Value::Object(defaults_only), &cx)).unwrap_or_default();
|
||||
Some(Seeded { value, cx, target, mode, unresolved: !valid_target })
|
||||
// A CMYK Channel Mixer has no framework editor yet (#8047): no dialog, rather than RGB sliders over its inks. Checked
|
||||
// before the defaults fallback too, which in an RGB or Lab document reads (RGB defaults) and would open the RGB
|
||||
// editor over a Smart Filter's ink keys.
|
||||
let value = match values::from_params(kind, &base, &cx) {
|
||||
Err(err) if err == values::CMYK_MIXER_UNAVAILABLE => return Err(Some(err)),
|
||||
read => read.or_else(|_| values::from_params(kind, &Value::Object(defaults_only), &cx)),
|
||||
};
|
||||
let value = match value {
|
||||
Ok(value) => value,
|
||||
Err(err) if err == values::CMYK_MIXER_UNAVAILABLE => return Err(Some(err)),
|
||||
Err(_) => AdjustValue::default(),
|
||||
};
|
||||
Ok(Seeded { value, cx, target, mode, unresolved: !valid_target })
|
||||
}
|
||||
|
||||
/// Whether the kind's editor shows a histogram.
|
||||
@@ -593,9 +621,9 @@ fn reset_target(kind: String) -> impl Fn(&DialogValue, &DialogValue) -> DialogVa
|
||||
}
|
||||
|
||||
/// Opens the dialog for `command` over `recorded` parameters (and a captured Smart Filter's `smart` index and target).
|
||||
fn open_hosted(app: &mut PhotocraftApp, command: &str, recorded: Value, smart: Option<(usize, Value)>, normalized: Option<Value>) -> Option<DialogId> {
|
||||
let kind = command.strip_prefix(PREFIX).filter(|k| adjust_editors::has_editor(k))?.to_owned();
|
||||
let spec = photocraft_engine::commands::find(command)?;
|
||||
fn open_hosted(app: &mut PhotocraftApp, command: &str, recorded: Value, smart: Option<(usize, Value)>, normalized: Option<Value>) -> Result<DialogId, Refused> {
|
||||
let kind = command.strip_prefix(PREFIX).filter(|k| adjust_editors::has_editor(k)).ok_or(None)?.to_owned();
|
||||
let spec = photocraft_engine::commands::find(command).ok_or(None)?;
|
||||
let seeded = seed(app, &kind, &recorded, smart.as_ref(), normalized.as_ref())?;
|
||||
// A dialog this one replaces on the host ends its Actions step with it.
|
||||
if let Some(previous) = app.adjust_open.take()
|
||||
@@ -639,14 +667,14 @@ fn open_hosted(app: &mut PhotocraftApp, command: &str, recorded: Value, smart: O
|
||||
recorded,
|
||||
normalized,
|
||||
});
|
||||
Some(id)
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Opens the dialog for `command` at the settings last confirmed in it (Photoshop's ⌥ plus the
|
||||
/// adjustment's shortcut, ⌥⌘L / ⌥⌘M, #8900), or at the neutral ones when there are none or they
|
||||
/// don't fit the current colour mode.
|
||||
pub fn open_last(app: &mut PhotocraftApp, command: &str) -> Result<DialogId, String> {
|
||||
let id = open_neutral(app, command).ok_or_else(|| refusal(app, command))?;
|
||||
let id = open_with_params_checked(app, command, &json!({})).map_err(|reason| reason.unwrap_or_else(|| refusal(app, command)))?;
|
||||
let kind = command.strip_prefix(PREFIX).unwrap_or_default();
|
||||
let Some(open) = app.adjust_open.as_ref().filter(|open| open.id == id) else { return Ok(id) };
|
||||
if matches!(kind, "levels" | "curves") && open.unresolved {
|
||||
@@ -802,7 +830,7 @@ fn follow_target(app: &mut PhotocraftApp, id: DialogId) {
|
||||
if resolved.is_err() {
|
||||
return;
|
||||
}
|
||||
let Some(seeded) = seed(app, &open.kind, &open.recorded, open.smart_filter.as_ref(), open.normalized.as_ref()) else { return };
|
||||
let Ok(seeded) = seed(app, &open.kind, &open.recorded, open.smart_filter.as_ref(), open.normalized.as_ref()) else { return };
|
||||
let kind = open.kind.clone();
|
||||
let setup = build_setup(app, &kind, &seeded.target, seeded.mode, false);
|
||||
let Some(open) = app.adjust_open.as_mut() else { return };
|
||||
|
||||
@@ -218,13 +218,20 @@ fn lifted<T>(events: EditEvents<T>, wrap: impl Fn(T) -> AdjustValue) -> AdjustOu
|
||||
AdjustOut { ask: None, edit: events.map(wrap) }
|
||||
}
|
||||
|
||||
fn reset_legacy_toggle(value: BrightnessContrast, previous_legacy: bool, reset: bool) -> BrightnessContrast {
|
||||
if reset && value.legacy != previous_legacy { BrightnessContrast::new(0.0, 0.0, value.legacy) } else { value }
|
||||
}
|
||||
|
||||
/// Shows the editor of `kind` over `value` for one pass.
|
||||
fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, cx: &mut AdjustDialogCx<'_>) -> AdjustOut {
|
||||
let context = cx.context;
|
||||
match (kind, value) {
|
||||
("brightnessContrast", AdjustValue::BrightnessContrast { value }) => {
|
||||
let out = BrightnessContrastEditor::new("Brightness/Contrast", Bind::bound(value)).context(context).show(ui);
|
||||
lifted(out.events, |value| AdjustValue::BrightnessContrast { value })
|
||||
let legacy = value.legacy;
|
||||
let out = BrightnessContrastEditor::new("Brightness/Contrast", Bind::bound(&mut *value)).context(context).show(ui);
|
||||
let reset = context.is_dialog();
|
||||
*value = reset_legacy_toggle(*value, legacy, reset);
|
||||
lifted(out.events.map(|value| reset_legacy_toggle(value, legacy, reset)), |value| AdjustValue::BrightnessContrast { value })
|
||||
}
|
||||
("levels", AdjustValue::Levels { levels }) => {
|
||||
let mut panel = LevelsPanel::new("Levels", Bind::bound(levels), setup.channels.clone())
|
||||
@@ -483,6 +490,19 @@ mod tests {
|
||||
assert!(answer_color(&mut map, &format!("{GRADIENT_STOP_KEY}1"), Srgba::rgb(0.0, 1.0, 0.0)));
|
||||
assert!(!answer_color(&mut map, &format!("{GRADIENT_STOP_KEY}9"), Srgba::BLACK), "no such stop");
|
||||
}
|
||||
|
||||
/// Toggling Use Legacy in the Brightness/Contrast dialog starts both sliders over at 0 in the
|
||||
/// new mode; an edit that keeps the mode, and the Properties panel (no reset), keep the values.
|
||||
#[test]
|
||||
fn toggling_use_legacy_in_the_dialog_resets_brightness_and_contrast() {
|
||||
for legacy in [false, true] {
|
||||
let toggled = BrightnessContrast::new(40.0, -80.0, !legacy);
|
||||
assert_eq!(reset_legacy_toggle(toggled, legacy, true), BrightnessContrast::new(0.0, 0.0, !legacy));
|
||||
assert_eq!(reset_legacy_toggle(toggled, legacy, false), toggled, "the Properties panel keeps its values");
|
||||
let kept = BrightnessContrast::new(40.0, -80.0, legacy);
|
||||
assert_eq!(reset_legacy_toggle(kept, legacy, true), kept, "an edit in the same mode is kept");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -158,6 +158,12 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj
|
||||
let vcx = value_cx(mode, &committed_params);
|
||||
let committed = match values::from_params(kind, &committed_params, &vcx) {
|
||||
Ok(value) => value,
|
||||
// A CMYK Channel Mixer has no framework editor yet (#8047): say so in the panel, like an unsupported adjustment
|
||||
// above, rather than in the status bar on every frame the layer is shown. The layer is kept as it is.
|
||||
Err(err) if err == values::CMYK_MIXER_UNAVAILABLE => {
|
||||
ui.label(egui::RichText::new(tl!(values::CMYK_MIXER_UNAVAILABLE)).color(t.text_faint));
|
||||
return;
|
||||
}
|
||||
Err(err) => {
|
||||
app.ui.status = err;
|
||||
return;
|
||||
|
||||
@@ -155,6 +155,13 @@ fn every_adjustment_layer_edits_through_properties() {
|
||||
assert_eq!(h.state().session.active().unwrap().doc.layers.len(), 2, "{kind} {mode}: the background and this kind's layer");
|
||||
let (_, before) = layer(&h);
|
||||
let steps = history_len(&h);
|
||||
if kind == "channelMixer" && mode == "cmyk" {
|
||||
// No framework editor for ink outputs yet (#8047): `cmyk_channel_mixer_is_kept_out_of_the_rgb_editor`.
|
||||
let why = crate::adjust_editors::values::CMYK_MIXER_UNAVAILABLE;
|
||||
assert!(label_rect(&h, why).is_some(), "{kind} {mode}: the Properties panel says why");
|
||||
assert_ne!(h.state().ui.status, why, "{kind} {mode}: not in the status bar");
|
||||
continue;
|
||||
}
|
||||
let slider = sliders(&h).first().copied();
|
||||
if SLIDER_KINDS.contains(&kind) {
|
||||
let r = slider.unwrap_or_else(|| panic!("{kind} {mode}: no slider in the Properties editor"));
|
||||
@@ -174,6 +181,49 @@ fn every_adjustment_layer_edits_through_properties() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #8047: the framework Channel Mixer editor has red, green and blue outputs only, so a CMYK
|
||||
/// document's mixer (cyan, magenta, yellow and black outputs) is not opened in it. The Properties
|
||||
/// panel says why and edits nothing, the Image › Adjustments dialog refuses with the same reason,
|
||||
/// and the layer keeps its ink rows. RGB mixers still open.
|
||||
#[test]
|
||||
fn cmyk_channel_mixer_is_kept_out_of_the_rgb_editor() {
|
||||
use crate::adjust_editors::values::{self, CMYK_MIXER_UNAVAILABLE, ValueCx};
|
||||
use photocraft_doc::ColorMode;
|
||||
use photocraft_engine::adjust_params;
|
||||
|
||||
// The conversion refuses ink outputs: a CMYK mixer, an imported monochrome one, a CMYK document's defaults.
|
||||
let ink = adjust_params::to_params(&adjust_params::default_for("channelMixer", ColorMode::Cmyk).unwrap());
|
||||
let mut mono = ink.clone();
|
||||
mono["monochrome"] = json!(true);
|
||||
mono["gray"] = json!([30, 30, 30, 100, 0]);
|
||||
for params in [&ink, &mono, &json!({})] {
|
||||
let read = values::from_params("channelMixer", params, &ValueCx::new(ColorMode::Cmyk, params.clone()));
|
||||
assert_eq!(read.err().as_deref(), Some(CMYK_MIXER_UNAVAILABLE), "{params}");
|
||||
}
|
||||
let rgb = json!({"red": [50, 50, 0, 0]});
|
||||
let read = values::from_params("channelMixer", &rgb, &ValueCx::new(ColorMode::Rgb, rgb.clone()));
|
||||
assert!(matches!(read, Ok(crate::adjust_editors::AdjustValue::ChannelMixer { .. })), "RGB mixers read: {read:?}");
|
||||
|
||||
// A CMYK document: the Properties panel shows no editor but a faint label saying why (not the status bar, which
|
||||
// it would overwrite on every frame), the dialog refuses with the same reason, the mixer is unchanged.
|
||||
let mut h = app_harness("channelMixer", "cmyk", 8);
|
||||
let (_, before) = layer(&h);
|
||||
assert!(matches!(&before, Adjustment::ChannelMixer { cmyk: Some(_), .. }), "{before:?}");
|
||||
let steps = history_len(&h);
|
||||
h.run_steps(4);
|
||||
assert!(label_rect(&h, CMYK_MIXER_UNAVAILABLE).is_some(), "the Properties panel says why");
|
||||
assert_ne!(h.state().ui.status, CMYK_MIXER_UNAVAILABLE, "the status bar is left alone");
|
||||
let err = crate::adjust_dialog::open(h.state_mut(), "image.adjustments.channelMixer").unwrap_err();
|
||||
assert_eq!(err, CMYK_MIXER_UNAVAILABLE);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layer(&h).1, before, "the mixer is kept as it is");
|
||||
assert_eq!(history_len(&h), steps, "nothing was edited");
|
||||
|
||||
// An RGB document's mixer still opens in the dialog.
|
||||
let mut h = app_harness("channelMixer", "rgb", 8);
|
||||
assert!(crate::adjust_dialog::open(h.state_mut(), "image.adjustments.channelMixer").is_ok(), "RGB mixers open");
|
||||
}
|
||||
|
||||
/// #3264: wheel browsing previews without recording one edit per selected LUT.
|
||||
#[test]
|
||||
fn color_lookup_picker_cycles_luts_with_the_mouse_wheel() {
|
||||
|
||||
@@ -242,6 +242,10 @@ fn object(base: &Value) -> Map<String, Value> {
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Params -> value
|
||||
|
||||
/// Why [`from_params`] refuses a CMYK document's Channel Mixer (cyan, magenta, yellow and black outputs, #8047).
|
||||
pub const CMYK_MIXER_UNAVAILABLE: &str =
|
||||
"Editing a CMYK Channel Mixer (cyan, magenta, yellow and black outputs) is not available in this editor yet; the mixer is kept as it is";
|
||||
|
||||
/// The typed value of the adjustment `kind` the engine reads from `params`.
|
||||
///
|
||||
/// The engine parses and clamps first (`adjust_params::from_params`), so the value holds what the engine would apply.
|
||||
@@ -251,8 +255,20 @@ pub fn from_params(kind: &str, params: &Value, cx: &ValueCx) -> Result<AdjustVal
|
||||
let tone = matches!(kind, "levels" | "curves");
|
||||
let given = if tone && cx.gray() { adjust_params::gray_tone_params(params) } else { params.clone() };
|
||||
let mode = if tone { cx.tone_mode() } else { cx.mode };
|
||||
// The framework Channel Mixer editor has red, green and blue outputs only. Opened on a CMYK mixer (#8047) it
|
||||
// would show RGB defaults, and its edits would be dropped: the engine keeps the ink outputs while the params carry
|
||||
// ink keys. Refuse it, so the mixer is kept as it is, until the framework has an ink-output editor. Checked on the
|
||||
// given params (an imported monochrome one fails the engine's own parse) and on the parsed ones (a CMYK
|
||||
// document's defaults).
|
||||
let cmyk_mixer = |p: &Value| kind == "channelMixer" && adjust_params::MIXER_INKS.iter().any(|k| p.get(*k).is_some());
|
||||
if cmyk_mixer(params) {
|
||||
return Err(CMYK_MIXER_UNAVAILABLE.to_owned());
|
||||
}
|
||||
let adjustment = adjust_params::from_params(kind, &given, None, mode).map_err(|e| e.to_string())?;
|
||||
let mut v = adjust_params::to_dialog_params(&adjustment);
|
||||
if cmyk_mixer(&v) {
|
||||
return Err(CMYK_MIXER_UNAVAILABLE.to_owned());
|
||||
}
|
||||
let space = space_of(&v, cx.mode);
|
||||
if tone && space == ToneSpace::Lab && cx.colour_set() {
|
||||
let pencil = flag(&v, "pencil", false);
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
//! Color Settings' Settings menu in the dialog (#14229): a picked setup loads into the controls
|
||||
//! (Blend Text Colors Using Gamma excepted), any change shows Custom, OK stores the name and
|
||||
//! Cancel discards the pick.
|
||||
|
||||
use craft::ui::dialog::DialogId;
|
||||
|
||||
use super::*;
|
||||
use crate::control::{ControlRequest, Reply};
|
||||
use crate::new_layer_ui::testing::top;
|
||||
|
||||
/// An app whose Color Settings hold `settings`.
|
||||
fn app_with(settings: ColorSettings) -> Box<PhotocraftApp> {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.session.color_mut().settings = settings;
|
||||
app
|
||||
}
|
||||
|
||||
/// Opens the dialog from the menu and runs `passes` passes of the dialog host.
|
||||
fn open_dialog(app: &mut PhotocraftApp, passes: usize) -> DialogId {
|
||||
let ctx = app.ctx().clone();
|
||||
crate::menus::invoke(app, &ctx, COMMAND, json!({})).unwrap();
|
||||
let id = top(app);
|
||||
show(app, passes);
|
||||
id
|
||||
}
|
||||
|
||||
fn show(app: &mut PhotocraftApp, passes: usize) {
|
||||
for _ in 0..passes {
|
||||
crate::dialogs::testing::show(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// The open dialog's values as JSON.
|
||||
fn fields(app: &PhotocraftApp, id: DialogId) -> Map<String, Value> {
|
||||
fields_map(crate::new_layer_ui::testing::fields(app, id))
|
||||
}
|
||||
|
||||
/// `ui.dialog.set`, as a script sends it.
|
||||
fn dialog_set(app: &mut PhotocraftApp, id: DialogId, field: &str, value: Value) {
|
||||
let ctx = app.ctx().clone();
|
||||
let (request, _) = ControlRequest::new("ui.dialog.set", json!({"dialog": id.value().to_string(), "field": field, "value": value}));
|
||||
let Reply::Done(reply) = crate::control::handle(app, &ctx, &request) else { panic!("ui.dialog.set should finish immediately") };
|
||||
assert_eq!(reply["ok"], true, "{field} = {value}: {reply}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_shows_the_stored_setup_and_keeps_its_values() {
|
||||
let stored = preset_setup(&ColorSettings::default(), "North America Prepress 2", "srgb").unwrap();
|
||||
let mut app = app_with(stored.clone());
|
||||
let id = open_dialog(&mut app, 3);
|
||||
let f = fields(&app, id);
|
||||
assert_eq!(f["preset"], "North America Prepress 2");
|
||||
let stored = serde_json::to_value(&stored).unwrap();
|
||||
let stored = stored.as_object().unwrap();
|
||||
for (k, v) in stored.iter().filter(|(k, _)| f.contains_key(*k)) {
|
||||
assert!(same(v, &f[k]), "{k}: {v} became {}", f[k]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_a_setup_loads_it_but_keeps_the_text_gamma() {
|
||||
// Blend Text Colors Using Gamma off (1.0) before the pick.
|
||||
let mut app = app_with(ColorSettings { blend_text_gamma: 1.0, ..ColorSettings::default() });
|
||||
let id = open_dialog(&mut app, 1);
|
||||
assert_eq!(fields(&app, id)["preset"], CUSTOM_SETTINGS, "PhotoCraft's defaults match no setup");
|
||||
dialog_set(&mut app, id, "preset", json!("Europe Prepress 3"));
|
||||
show(&mut app, 3);
|
||||
let f = fields(&app, id);
|
||||
assert_eq!(f["preset"], "Europe Prepress 3", "loading the values is no edit");
|
||||
assert_eq!((&f["workingRgb"], &f["workingCmyk"], &f["workingGray"]), (&json!("adobe-rgb-compat"), &json!("coated-fogra39"), &json!("dot-gain-20-compat")));
|
||||
assert_eq!((&f["askOnMismatch"], &f["askOnPaste"], &f["askOnMissing"]), (&json!(true), &json!(true), &json!(true)));
|
||||
assert!(same(&f["spotDotGain"], &json!(15.0)), "{}", f["spotDotGain"]);
|
||||
assert!(same(&f["blendTextGamma"], &json!(1.0)), "kept: {}", f["blendTextGamma"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_any_control_shows_custom() {
|
||||
for (key, value) in [
|
||||
("workingRgb", json!("display-p3")),
|
||||
("policyGray", json!("off")),
|
||||
("askOnPaste", json!(false)),
|
||||
("intent", json!("saturation")),
|
||||
("bpc", json!(false)),
|
||||
("spotDotGain", json!(30.0)),
|
||||
("blendTextGamma", json!(1.8)),
|
||||
("reset", json!(true)),
|
||||
] {
|
||||
let mut app = app_with(ColorSettings::default());
|
||||
let id = open_dialog(&mut app, 1);
|
||||
dialog_set(&mut app, id, "preset", json!("Japan Prepress 2"));
|
||||
show(&mut app, 2);
|
||||
assert_eq!(fields(&app, id)["preset"], "Japan Prepress 2");
|
||||
// As the control would change it.
|
||||
crate::new_layer_ui::testing::set(&mut app, id, key, value).unwrap();
|
||||
show(&mut app, 1);
|
||||
assert_eq!(fields(&app, id)["preset"], CUSTOM_SETTINGS, "{key}");
|
||||
// It stays Custom, and keeps the values.
|
||||
show(&mut app, 2);
|
||||
let f = fields(&app, id);
|
||||
assert_eq!(f["preset"], CUSTOM_SETTINGS, "{key}");
|
||||
assert_eq!(f["workingCmyk"], "coated-cmyk", "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_monitor_profile_is_no_change() {
|
||||
let mut app = app_with(ColorSettings::default());
|
||||
let id = open_dialog(&mut app, 1);
|
||||
dialog_set(&mut app, id, "preset", json!("North America Web/Internet"));
|
||||
show(&mut app, 2);
|
||||
dialog_set(&mut app, id, "monitorProfile", json!("display-p3"));
|
||||
show(&mut app, 2);
|
||||
assert_eq!(fields(&app, id)["preset"], "North America Web/Internet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_color_takes_the_monitor_profile_the_dialog_shows() {
|
||||
let mut app = app_with(ColorSettings { monitor_profile: "display-p3".into(), ..ColorSettings::default() });
|
||||
let id = open_dialog(&mut app, 1);
|
||||
dialog_set(&mut app, id, "preset", json!("Monitor Color"));
|
||||
show(&mut app, 2);
|
||||
let f = fields(&app, id);
|
||||
assert_eq!(f["preset"], "Monitor Color");
|
||||
assert_eq!(f["workingRgb"], app.session.color().monitor_rgb_for("display-p3"));
|
||||
assert_eq!((&f["policyRgb"], &f["policyCmyk"], &f["policyGray"]), (&json!("off"), &json!("off"), &json!("off")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_greyed_label_and_unknown_names_are_no_entry() {
|
||||
for bad in [json!("Other"), json!("Nowhere")] {
|
||||
let mut app = app_with(ColorSettings::default());
|
||||
let id = open_dialog(&mut app, 1);
|
||||
dialog_set(&mut app, id, "preset", bad.clone());
|
||||
show(&mut app, 1);
|
||||
assert_eq!(fields(&app, id)["preset"], CUSTOM_SETTINGS, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ok_stores_the_setup_and_cancel_discards_it() {
|
||||
let mut app = app_with(ColorSettings::default());
|
||||
// Cancel: nothing changes.
|
||||
let id = open_dialog(&mut app, 1);
|
||||
dialog_set(&mut app, id, "preset", json!("North America General Purpose 2"));
|
||||
show(&mut app, 2);
|
||||
crate::dialogs::testing::cancel(&mut app, id).unwrap();
|
||||
assert_eq!(app.session.color().settings, ColorSettings::default());
|
||||
// OK: the setup's name and values.
|
||||
let id = open_dialog(&mut app, 1);
|
||||
dialog_set(&mut app, id, "preset", json!("North America General Purpose 2"));
|
||||
show(&mut app, 2);
|
||||
crate::dialogs::testing::confirm(&mut app, id).unwrap();
|
||||
let c = &app.session.color().settings;
|
||||
assert_eq!(c.preset, "North America General Purpose 2");
|
||||
assert_eq!((c.ask_on_mismatch, c.ask_on_paste, c.ask_on_missing), (false, false, false));
|
||||
// Opened again, it shows that setup; an edit then OK stores Custom.
|
||||
let id = open_dialog(&mut app, 1);
|
||||
assert_eq!(fields(&app, id)["preset"], "North America General Purpose 2");
|
||||
dialog_set(&mut app, id, "dither", json!(false));
|
||||
assert_eq!(fields(&app, id)["preset"], CUSTOM_SETTINGS);
|
||||
crate::dialogs::testing::confirm(&mut app, id).unwrap();
|
||||
assert_eq!(app.session.color().settings.preset, CUSTOM_SETTINGS);
|
||||
assert!(!app.session.color().settings.dither);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setup_set_by_script_loads_before_the_next_draw() {
|
||||
let expected = preset_setup(&ColorSettings::default(), "Europe Prepress 3", "srgb").unwrap();
|
||||
let mut app = app_with(ColorSettings::default());
|
||||
let id = open_dialog(&mut app, 1);
|
||||
dialog_set(&mut app, id, "preset", json!("Europe Prepress 3"));
|
||||
crate::dialogs::testing::confirm(&mut app, id).unwrap();
|
||||
let c = &app.session.color().settings;
|
||||
assert_eq!(c.preset, "Europe Prepress 3");
|
||||
assert_eq!((&c.working_rgb, &c.working_cmyk), (&expected.working_rgb, &expected.working_cmyk));
|
||||
assert_eq!((c.ask_on_mismatch, c.ask_on_paste, c.ask_on_missing), (true, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_set_by_script_shows_custom_before_the_next_draw() {
|
||||
let name = "North America General Purpose 2";
|
||||
let stored = preset_setup(&ColorSettings::default(), name, "srgb").unwrap();
|
||||
// The engine keeps a named setup's name over the first two (gamma is no part of a setup, and
|
||||
// the setup loads over a reset), so only the dialog can tell they changed. Setting the value a
|
||||
// control already shows is no change.
|
||||
for (key, value, expected) in
|
||||
[("blendTextGamma", json!(1.8), CUSTOM_SETTINGS), ("reset", json!(true), CUSTOM_SETTINGS), ("blendTextGamma", json!(1.45), name)]
|
||||
{
|
||||
// A fresh app each time: the dialog reopens with the last confirmed values.
|
||||
let mut app = app_with(stored.clone());
|
||||
let id = open_dialog(&mut app, 1);
|
||||
dialog_set(&mut app, id, key, value.clone());
|
||||
assert_eq!(fields(&app, id)["preset"], expected, "{key} {value}");
|
||||
crate::dialogs::testing::confirm(&mut app, id).unwrap();
|
||||
assert_eq!(app.session.color().settings.preset, expected, "{key} {value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_set_before_the_first_pass_shows_custom() {
|
||||
let name = "North America General Purpose 2";
|
||||
let stored = preset_setup(&ColorSettings::default(), name, "srgb").unwrap();
|
||||
// Before the first pass the dialog has no baseline yet: a changed control is still an edit,
|
||||
// and setting the value it already shows is none.
|
||||
for (value, expected) in [(json!(1.8), CUSTOM_SETTINGS), (json!(1.45), name)] {
|
||||
let mut app = app_with(stored.clone());
|
||||
let id = open_dialog(&mut app, 0);
|
||||
dialog_set(&mut app, id, "blendTextGamma", value.clone());
|
||||
assert_eq!(fields(&app, id)["preset"], expected, "{value}");
|
||||
show(&mut app, 2);
|
||||
assert_eq!(fields(&app, id)["preset"], expected, "{value} after a draw");
|
||||
crate::dialogs::testing::confirm(&mut app, id).unwrap();
|
||||
assert_eq!(app.session.color().settings.preset, expected, "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_set_before_the_first_pass_shows_custom() {
|
||||
let name = "North America General Purpose 2";
|
||||
let stored = preset_setup(&ColorSettings::default(), name, "srgb").unwrap();
|
||||
for (value, expected) in [(json!(true), CUSTOM_SETTINGS), (json!(false), name)] {
|
||||
let mut app = app_with(stored.clone());
|
||||
let id = open_dialog(&mut app, 0);
|
||||
dialog_set(&mut app, id, "reset", value.clone());
|
||||
assert_eq!(fields(&app, id)["preset"], expected, "reset {value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_color_follows_a_monitor_profile_set_before_the_first_pass() {
|
||||
let stored = preset_setup(&ColorSettings { monitor_profile: "srgb".into(), ..ColorSettings::default() }, "Monitor Color", "srgb").unwrap();
|
||||
let mut app = app_with(stored);
|
||||
let id = open_dialog(&mut app, 0);
|
||||
dialog_set(&mut app, id, "monitorProfile", json!("display-p3"));
|
||||
let f = fields(&app, id);
|
||||
assert_eq!((&f["preset"], &f["workingRgb"]), (&json!("Monitor Color"), &json!("display-p3")), "loaded at once");
|
||||
crate::dialogs::testing::confirm(&mut app, id).unwrap();
|
||||
let c = &app.session.color().settings;
|
||||
assert_eq!((c.preset.as_str(), c.working_rgb.as_str()), ("Monitor Color", "display-p3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setup_set_before_the_first_pass_loads_too() {
|
||||
let expected = preset_setup(&ColorSettings::default(), "Europe Prepress 3", "srgb").unwrap();
|
||||
let mut app = app_with(ColorSettings::default());
|
||||
let id = open_dialog(&mut app, 0);
|
||||
dialog_set(&mut app, id, "preset", json!("Europe Prepress 3"));
|
||||
let f = fields(&app, id);
|
||||
assert_eq!((&f["workingRgb"], &f["workingCmyk"]), (&json!(expected.working_rgb), &json!(expected.working_cmyk)), "loaded at once");
|
||||
crate::dialogs::testing::confirm(&mut app, id).unwrap();
|
||||
let c = &app.session.color().settings;
|
||||
assert_eq!(c.preset, "Europe Prepress 3");
|
||||
assert_eq!((&c.working_rgb, &c.working_cmyk), (&expected.working_rgb, &expected.working_cmyk));
|
||||
assert_eq!((c.ask_on_mismatch, c.ask_on_paste, c.ask_on_missing), (true, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_color_follows_a_monitor_profile_change() {
|
||||
let mut app = app_with(ColorSettings { monitor_profile: "srgb".into(), ..ColorSettings::default() });
|
||||
let id = open_dialog(&mut app, 1);
|
||||
dialog_set(&mut app, id, "preset", json!("Monitor Color"));
|
||||
show(&mut app, 2);
|
||||
assert_eq!(fields(&app, id)["workingRgb"], "srgb");
|
||||
dialog_set(&mut app, id, "monitorProfile", json!("display-p3"));
|
||||
let f = fields(&app, id);
|
||||
assert_eq!(f["preset"], "Monitor Color");
|
||||
assert_eq!(f["workingRgb"], "display-p3", "the working RGB follows the monitor profile");
|
||||
show(&mut app, 2);
|
||||
crate::dialogs::testing::confirm(&mut app, id).unwrap();
|
||||
let c = &app.session.color().settings;
|
||||
assert_eq!((c.preset.as_str(), c.working_rgb.as_str(), c.monitor_profile.as_str()), ("Monitor Color", "display-p3", "display-p3"));
|
||||
}
|
||||
@@ -25,7 +25,9 @@ use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
|
||||
mod color_settings_presets;
|
||||
mod rows;
|
||||
pub(crate) use color_settings_presets::reconcile as reconcile_color_settings;
|
||||
pub(crate) use rows::{REPLACE_COLOR, replace_color_sample};
|
||||
|
||||
const MATCH_COLOR: &str = "image.adjustments.matchColor";
|
||||
@@ -372,7 +374,11 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec<
|
||||
list = super::rotate_canvas_ui::params();
|
||||
}
|
||||
rows::custom_rows(app, command, &mut list);
|
||||
if command == "edit.colorSettings" {
|
||||
if command == color_settings_presets::COMMAND {
|
||||
// The Settings menu: Custom, a greyed group label and the named setups in groups (#14229).
|
||||
if let Some(p) = list.iter_mut().find(|p| p.key == "preset") {
|
||||
*p = color_settings_presets::row(Label::from(tl!("Settings")));
|
||||
}
|
||||
// The monitor line under the rows: the cell holds the text each frame refreshes, which the build closure cannot read from the app.
|
||||
let note = crate::monitor_status::note_cell(app);
|
||||
list.push(craft::ui::patterns::form_dialogs::Param::custom("monitorNote", craft::ui::runtime::env::Label::Empty, move |ui, _, _| {
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Color Settings' Settings menu (#14229): picking a named setup loads its values into the
|
||||
//! dialog's controls, except Blend Text Colors Using Gamma, which keeps what it shows; changing
|
||||
//! any control afterwards shows "Custom" at once. OK sends the menu's entry as `preset`.
|
||||
//!
|
||||
//! The menu is a custom row ([`row`]); [`reconcile`] does the rest after each pass of the dialog
|
||||
//! host and after each `ui.dialog.set`, so a confirm that follows a script's set sends the same
|
||||
//! name and values a draw would have shown.
|
||||
|
||||
use craft::ui::contract::{Bind, Entry, Outcome as _, Show as _};
|
||||
use craft::ui::dialog::dialog_id;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param};
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::runtime::env::Label;
|
||||
use photocraft_engine::color_cmds::{COLOR_SETTINGS_PRESETS, CUSTOM_SETTINGS, ColorExt, ColorSettings, is_settings_preset, preset_setup};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
|
||||
pub(super) const COMMAND: &str = "edit.colorSettings";
|
||||
const KEY: &str = "preset";
|
||||
/// The menu's greyed group label: never a value.
|
||||
const OTHER: &str = "Other";
|
||||
/// The entries a separator line goes above.
|
||||
const GROUP_STARTS: [&str; 3] = [OTHER, "Europe General Purpose 3", "Japan Color for Newspaper"];
|
||||
/// The menu entry the controls last took their values from (or showed on opening).
|
||||
const APPLIED: &str = "__presetApplied";
|
||||
/// The controls' values at that moment: an edit makes them differ.
|
||||
const BASE: &str = "__presetBase";
|
||||
/// The setup whose working RGB is the monitor profile.
|
||||
const MONITOR_COLOR: &str = "Monitor Color";
|
||||
/// What a setup leaves as the controls show it.
|
||||
const KEPT: [&str; 2] = ["blendTextGamma", "monitorProfile"];
|
||||
|
||||
/// The menu entry `value` names (Custom for anything the menu doesn't have).
|
||||
fn entry_of(value: Option<&str>) -> String {
|
||||
value.filter(|n| is_settings_preset(n)).unwrap_or(CUSTOM_SETTINGS).to_string()
|
||||
}
|
||||
|
||||
/// The Settings row, in place of the spec's plain choice: Custom, the greyed Other label and the
|
||||
/// named setups in their groups.
|
||||
pub(super) fn row(label: Label) -> Param {
|
||||
let name = label.clone();
|
||||
Param::custom(KEY, label, move |ui, fields, _| {
|
||||
let mut entries = Vec::new();
|
||||
let named = COLOR_SETTINGS_PRESETS.iter().map(|n| (*n, *n));
|
||||
for (value, label) in [(CUSTOM_SETTINGS, tl!("Custom")), (OTHER, tl!("Other"))].into_iter().chain(named) {
|
||||
if GROUP_STARTS.contains(&value) {
|
||||
entries.push(Entry::separator());
|
||||
}
|
||||
entries.push(Entry::new(value.to_string(), Label::from(label)).enabled(value != OTHER));
|
||||
}
|
||||
let out = Select::new(name.clone(), Bind::given(entry_of(fields.text(KEY))), &entries).show(ui);
|
||||
if let Some(picked) = out.value().cloned() {
|
||||
fields.set(KEY, FieldValue::Text(picked));
|
||||
}
|
||||
out.response().clone()
|
||||
})
|
||||
}
|
||||
|
||||
/// After a pass or a set: shows Custom for a name the menu doesn't have, loads a newly picked setup
|
||||
/// (from the menu or `ui.dialog.set`), or shows Custom once a control differs from the values the
|
||||
/// shown setup gave.
|
||||
pub(crate) fn reconcile(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
let Some(dialog) = app.framework.dialogs.get_by_id::<HostedParamDialog>(dialog_id(COMMAND)) else { return };
|
||||
let f = fields_map(dialog.fields());
|
||||
let shown = entry_of(f.get(KEY).and_then(Value::as_str));
|
||||
if f.get(KEY).and_then(Value::as_str) != Some(shown.as_str()) {
|
||||
set_hidden(app, KEY, json!(shown));
|
||||
}
|
||||
let Some(applied) = f.get(APPLIED).and_then(Value::as_str).map(str::to_string) else {
|
||||
// Opening: the controls hold the stored setup's values. A `ui.dialog.set` that picked
|
||||
// another entry before the first pass loads it.
|
||||
if shown != entry_of(Some(&app.session.color().settings.preset)) {
|
||||
load(app, ctx, &f, &shown);
|
||||
return;
|
||||
}
|
||||
// A control a `ui.dialog.set` changed before the first pass is an edit, not the baseline.
|
||||
if shown != CUSTOM_SETTINGS && differs_from_stored(app, &f) {
|
||||
set_hidden(app, KEY, json!(CUSTOM_SETTINGS));
|
||||
set_hidden(app, APPLIED, json!(CUSTOM_SETTINGS));
|
||||
return;
|
||||
}
|
||||
let base = tracked(&f);
|
||||
// A monitor profile set before the first pass moves Monitor Color's working RGB too.
|
||||
if shown == MONITOR_COLOR && monitor_rgb_moved(app, &f, &base) {
|
||||
load(app, ctx, &f, &shown);
|
||||
return;
|
||||
}
|
||||
set_hidden(app, APPLIED, json!(shown));
|
||||
set_hidden(app, BASE, Value::Object(base));
|
||||
return;
|
||||
};
|
||||
if shown != applied {
|
||||
load(app, ctx, &f, &shown);
|
||||
return;
|
||||
}
|
||||
if shown == CUSTOM_SETTINGS {
|
||||
return;
|
||||
}
|
||||
let mut base = match f.get(BASE) {
|
||||
Some(Value::Object(b)) => b.clone(),
|
||||
_ => Map::new(),
|
||||
};
|
||||
let (mut edited, mut grew) = (false, false);
|
||||
for (k, v) in tracked(&f) {
|
||||
match base.get(&k) {
|
||||
Some(b) => edited |= !same(b, &v),
|
||||
// A control that filled in its default after opening is no edit.
|
||||
None => {
|
||||
base.insert(k, v);
|
||||
grew = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if edited {
|
||||
set_hidden(app, KEY, json!(CUSTOM_SETTINGS));
|
||||
set_hidden(app, APPLIED, json!(CUSTOM_SETTINGS));
|
||||
} else if shown == MONITOR_COLOR && monitor_rgb_moved(app, &f, &base) {
|
||||
// Monitor Color's working RGB follows the monitor profile the dialog shows.
|
||||
load(app, ctx, &f, &shown);
|
||||
} else if grew {
|
||||
set_hidden(app, BASE, Value::Object(base));
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the named setup into the controls (but the [`KEPT`] ones) and makes it the one they show.
|
||||
/// "Monitor Color" takes the monitor profile the dialog shows as its working RGB.
|
||||
fn load(app: &mut PhotocraftApp, ctx: &egui::Context, f: &Map<String, Value>, name: &str) {
|
||||
let monitor = f.get("monitorProfile").and_then(Value::as_str).unwrap_or("auto");
|
||||
let monitor_rgb = app.session.color().monitor_rgb_for(monitor);
|
||||
let id = dialog_id(COMMAND);
|
||||
if let Some(Value::Object(setup)) = preset_setup(&ColorSettings::default(), name, &monitor_rgb).and_then(|c| serde_json::to_value(c).ok()) {
|
||||
for (k, v) in setup {
|
||||
if is_tracked(&k) && !KEPT.contains(&k.as_str()) && f.contains_key(&k) {
|
||||
// A value a row refuses keeps what the row shows; the setups' values all fit the rows.
|
||||
let _ = app.framework.dialogs.set_json_field(ctx, id, &k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(dialog) = app.framework.dialogs.get_by_id::<HostedParamDialog>(id) else { return };
|
||||
let base = tracked(&fields_map(dialog.fields()));
|
||||
set_hidden(app, APPLIED, json!(name));
|
||||
set_hidden(app, BASE, Value::Object(base));
|
||||
}
|
||||
|
||||
/// A tracked control no longer shows the stored Color Settings' value (for Reset, which the
|
||||
/// settings don't hold, its opening value: off).
|
||||
fn differs_from_stored(app: &PhotocraftApp, f: &Map<String, Value>) -> bool {
|
||||
let Ok(Value::Object(stored)) = serde_json::to_value(&app.session.color().settings) else { return false };
|
||||
let opening = |k: &str| stored.get(k).cloned().or_else(|| (k == "reset").then_some(Value::Bool(false)));
|
||||
tracked(f).iter().any(|(k, v)| opening(k).is_some_and(|s| !same(&s, v)))
|
||||
}
|
||||
|
||||
/// The working RGB Monitor Color gave (in `base`) is no longer the one the shown monitor profile gives.
|
||||
fn monitor_rgb_moved(app: &PhotocraftApp, f: &Map<String, Value>, base: &Map<String, Value>) -> bool {
|
||||
let monitor = f.get("monitorProfile").and_then(Value::as_str).unwrap_or("auto");
|
||||
base.get("workingRgb").and_then(Value::as_str) != Some(app.session.color().monitor_rgb_for(monitor).as_str())
|
||||
}
|
||||
|
||||
/// Writes `value` under `key` of the open dialog: the menu's entry as text, the bookkeeping as JSON.
|
||||
fn set_hidden(app: &mut PhotocraftApp, key: &str, value: Value) {
|
||||
let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedParamDialog>(dialog_id(COMMAND)) else { return };
|
||||
match value {
|
||||
Value::String(text) => dialog.set_field(key, FieldValue::Text(text)),
|
||||
value => dialog.set_field(key, FieldValue::Json(value)),
|
||||
}
|
||||
}
|
||||
|
||||
fn fields_map(fields: &DialogFields) -> Map<String, Value> {
|
||||
match serde_json::to_value(fields) {
|
||||
Ok(Value::Object(map)) => map,
|
||||
_ => Map::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keys whose change makes the values Custom: the params but the menu and the monitor profile.
|
||||
fn is_tracked(k: &str) -> bool {
|
||||
!k.starts_with("__") && k != KEY && k != "monitorProfile"
|
||||
}
|
||||
|
||||
fn tracked(f: &Map<String, Value>) -> Map<String, Value> {
|
||||
f.iter().filter(|(k, _)| is_tracked(k)).map(|(k, v)| (k.clone(), v.clone())).collect()
|
||||
}
|
||||
|
||||
/// Equal values; numbers within the controls' rounding (a stored f32 gamma reads back as
|
||||
/// 1.4500000476837158, the field shows 1.45).
|
||||
fn same(a: &Value, b: &Value) -> bool {
|
||||
match (a.as_f64(), b.as_f64()) {
|
||||
(Some(x), Some(y)) => (x - y).abs() <= 1e-4,
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../color_settings_presets_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,268 @@
|
||||
use std::cell::RefCell;
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::host::{FileFilter, PickKind, Picked, ScriptedFiles};
|
||||
use craft::ui::dialog::DialogId;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog};
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{COMMAND, settings};
|
||||
use crate::{PhotocraftApp, Services};
|
||||
|
||||
#[test]
|
||||
fn settings_xml_follows_the_reference_order_and_formats() {
|
||||
let mut fields = DialogFields::from_pairs([("source", "folder"), ("input", "C:\\é & <source>\r\n"), ("output", "C:\\résultats")]);
|
||||
fields.set("jpeg/quality", 5.25);
|
||||
fields.set("jpeg/resize", true);
|
||||
fields.set("jpeg/width", 100_i64);
|
||||
fields.set("jpeg/height", 80_i64);
|
||||
let xml = settings::encode(&fields).unwrap();
|
||||
let text = std::str::from_utf8(&xml).unwrap();
|
||||
assert_eq!(
|
||||
text,
|
||||
concat!(
|
||||
"\u{feff}<ImageProcessor>\n",
|
||||
"\t<version>1</version>\n",
|
||||
"\t<useopen>false</useopen>\n",
|
||||
"\t<includesub>false</includesub>\n",
|
||||
"\t<source>C:\\é & <source> </source>\n",
|
||||
"\t<open>false</open>\n",
|
||||
"\t<saveinsame>false</saveinsame>\n",
|
||||
"\t<dest>C:\\résultats</dest>\n",
|
||||
"\t<jpeg>true</jpeg>\n",
|
||||
"\t<psd>false</psd>\n",
|
||||
"\t<tiff>false</tiff>\n",
|
||||
"\t<lzw>false</lzw>\n",
|
||||
"\t<converticc>false</converticc>\n",
|
||||
"\t<q>5.25</q>\n",
|
||||
"\t<max>true</max>\n",
|
||||
"\t<jpegresize>true</jpegresize>\n",
|
||||
"\t<jpegw>100</jpegw>\n",
|
||||
"\t<jpegh>80</jpegh>\n",
|
||||
"\t<psdresize>false</psdresize>\n",
|
||||
"\t<psdw>1</psdw>\n",
|
||||
"\t<psdh>1</psdh>\n",
|
||||
"\t<tiffresize>false</tiffresize>\n",
|
||||
"\t<tiffw>1</tiffw>\n",
|
||||
"\t<tiffh>1</tiffh>\n",
|
||||
"\t<runaction>false</runaction>\n",
|
||||
"\t<actionset></actionset>\n",
|
||||
"\t<action></action>\n",
|
||||
"\t<info></info>\n",
|
||||
"\t<icc>true</icc>\n",
|
||||
"\t<keepstructure>true</keepstructure>\n",
|
||||
"</ImageProcessor>\n",
|
||||
)
|
||||
);
|
||||
let decoded = settings::decode(&xml).unwrap();
|
||||
assert_eq!(decoded.text("input"), fields.text("input"));
|
||||
assert_eq!(decoded.text("output"), fields.text("output"));
|
||||
assert_eq!(decoded.number("jpeg/quality"), Some(5.25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_xml_keeps_missing_fields_and_ignores_unknown_elements() {
|
||||
let fields = settings::decode(
|
||||
br#"<ImageProcessor><useopen>true</useopen><source/><future><q>invalid</q></future><actionset>Missing set </actionset></ImageProcessor>"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(fields, DialogFields::from_pairs([("source", "open"), ("input", "")]));
|
||||
for source in ["current", "open", "folder"] {
|
||||
let current = DialogFields::from_pairs([("source", source)]);
|
||||
let encoded = settings::encode(¤t).unwrap();
|
||||
assert_eq!(settings::decode(&encoded).unwrap().text("source"), Some(source));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_settings_are_rejected() {
|
||||
for invalid in [
|
||||
"",
|
||||
"<Other/>",
|
||||
"<ImageProcessor xmlns='urn:other'/>",
|
||||
"<!DOCTYPE ImageProcessor><ImageProcessor/>",
|
||||
"<ImageProcessor>",
|
||||
"<ImageProcessor><q>abc</q></ImageProcessor>",
|
||||
"<ImageProcessor><q>NaN</q></ImageProcessor>",
|
||||
"<ImageProcessor><q>12.01</q></ImageProcessor>",
|
||||
"<ImageProcessor><jpegw>30001</jpegw></ImageProcessor>",
|
||||
"<ImageProcessor><psdw>0</psdw></ImageProcessor>",
|
||||
"<ImageProcessor><jpeg>maybe</jpeg></ImageProcessor>",
|
||||
"<ImageProcessor><tiff>tr<something/>ue</tiff></ImageProcessor>",
|
||||
"<ImageProcessor><icc>false</icc><icc>true</icc></ImageProcessor>",
|
||||
"<ImageProcessor><source>&bad;</source></ImageProcessor>",
|
||||
"<ImageProcessor><dest>A & B</dest></ImageProcessor>",
|
||||
"<ImageProcessor><dest>A &</dest></ImageProcessor>",
|
||||
"<ImageProcessor><future label='A & B'/></ImageProcessor>",
|
||||
"<ImageProcessor/><Another/>",
|
||||
] {
|
||||
assert!(settings::decode(invalid.as_bytes()).is_err(), "{invalid}");
|
||||
}
|
||||
assert!(settings::decode(&[0xff]).is_err());
|
||||
assert!(settings::decode(&vec![b' '; settings::MAX_BYTES + 1]).is_err());
|
||||
assert!(settings::encode(&DialogFields::from_pairs([("input", "bad\0path")])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escaped_ampersands_and_literal_cdata_remain_valid() {
|
||||
let xml = concat!(
|
||||
"\u{feff}<ImageProcessor><!-- A & B --><?note A & B?>",
|
||||
"<future label='A & B'/>",
|
||||
"<dest>A & B & C &amp;</dest>",
|
||||
"<source><![CDATA[A & B]]></source></ImageProcessor>",
|
||||
);
|
||||
let fields = settings::decode(xml.as_bytes()).unwrap();
|
||||
assert_eq!(fields.text("output"), Some("A & B & C &"));
|
||||
assert_eq!(fields.text("input"), Some("A & B"));
|
||||
}
|
||||
|
||||
type AppHarness = Harness<'static, Box<PhotocraftApp>>;
|
||||
type Written = Rc<RefCell<Vec<(String, Vec<u8>)>>>;
|
||||
|
||||
fn open(app: &mut PhotocraftApp) -> DialogId {
|
||||
let ctx = app.ctx().clone();
|
||||
crate::menus::invoke(app, &ctx, COMMAND, json!({})).unwrap();
|
||||
app.framework.dialogs.stack().top().unwrap()
|
||||
}
|
||||
|
||||
fn harness() -> (AppHarness, DialogId, Arc<ScriptedFiles>, Written) {
|
||||
let files = Arc::new(ScriptedFiles::held());
|
||||
let written: Written = Default::default();
|
||||
let log = written.clone();
|
||||
let services = Services {
|
||||
files: Some(files.clone()),
|
||||
write: Some(Box::new(move |path, bytes| {
|
||||
log.borrow_mut().push((path.to_owned(), bytes.to_vec()));
|
||||
Ok(())
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
|
||||
app.run("file.new", json!({"width": 40, "height": 20})).unwrap();
|
||||
let id = open(&mut app);
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 1000.0)).with_context(app.ctx().clone()).build_ui_state(
|
||||
|ui, app: &mut Box<PhotocraftApp>| {
|
||||
app.poll_file_dialog();
|
||||
crate::dialogs::run(app, ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
PhotocraftApp::setup_context(&h.ctx, Default::default());
|
||||
h.run_steps(4);
|
||||
(h, id, files, written)
|
||||
}
|
||||
|
||||
fn fields(h: &AppHarness, id: DialogId) -> &DialogFields {
|
||||
h.state().framework.dialogs.get_by_id::<HostedParamDialog>(id).unwrap().fields()
|
||||
}
|
||||
|
||||
fn set(h: &mut AppHarness, id: DialogId, key: &str, value: Value) {
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().framework.dialogs.set_json_field(&ctx, id, key, value).unwrap_or_else(|error| panic!("{key}: {error}"));
|
||||
}
|
||||
|
||||
fn click(h: &mut AppHarness, label: &str) {
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Button, label).click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_footer_saves_and_loads_pending_values_without_running_image_processor() {
|
||||
let (mut h, id, files, written) = harness();
|
||||
for (key, value) in [
|
||||
("source", json!("folder")),
|
||||
("input", json!("pictures & sketches")),
|
||||
("output", json!("exports")),
|
||||
("includeSubfolders", json!(true)),
|
||||
("jpeg/quality", json!(9.75)),
|
||||
("jpeg/convertToSrgb", json!(true)),
|
||||
("jpeg/resize", json!(true)),
|
||||
("jpeg/width", json!(2048)),
|
||||
("jpeg/height", json!(1536)),
|
||||
("psd/enabled", json!(true)),
|
||||
("psd/maximizeCompatibility", json!(false)),
|
||||
("psd/resize", json!(true)),
|
||||
("psd/width", json!(1024)),
|
||||
("psd/height", json!(768)),
|
||||
("tiff/enabled", json!(true)),
|
||||
("tiff/lzw", json!(true)),
|
||||
("tiff/resize", json!(true)),
|
||||
("tiff/width", json!(4096)),
|
||||
("tiff/height", json!(3072)),
|
||||
] {
|
||||
set(&mut h, id, key, value);
|
||||
}
|
||||
h.run_steps(3);
|
||||
let buttons = ["Load…", "Save…", "Cancel", "Run"].map(|label| h.get_by_role_and_label(egui::accesskit::Role::Button, label).rect());
|
||||
for (index, button) in buttons.iter().enumerate() {
|
||||
assert!(button.is_positive(), "button {index} is visible");
|
||||
assert!(buttons.iter().skip(index + 1).all(|other| !button.intersects(*other)), "footer buttons must not overlap");
|
||||
}
|
||||
let original = fields(&h, id).clone();
|
||||
click(&mut h, "Save…");
|
||||
let request = files.requests().pop().unwrap();
|
||||
assert_eq!(request.kind, PickKind::Save);
|
||||
assert_eq!(request.title.as_deref(), Some("Pick an XML file to save"));
|
||||
assert_eq!(request.filters, [FileFilter::new("XML Files (*.xml)", &["xml"])]);
|
||||
files.answer(Picked::Paths(vec![PathBuf::from("preset.xml")])).unwrap();
|
||||
h.run_steps(3);
|
||||
assert_eq!(fields(&h, id), &original);
|
||||
let (path, saved) = written.borrow_mut().pop().unwrap();
|
||||
assert_eq!(path, "preset.xml");
|
||||
|
||||
set(&mut h, id, "source", json!("open"));
|
||||
set(&mut h, id, "jpeg/quality", json!(2.0));
|
||||
set(&mut h, id, "psd/enabled", json!(false));
|
||||
set(&mut h, id, "tiff/width", json!(16));
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Load…");
|
||||
let request = files.requests().pop().unwrap();
|
||||
assert_eq!(request.kind, PickKind::Open);
|
||||
assert_eq!(request.title.as_deref(), Some("Pick an XML file to load"));
|
||||
assert_eq!(request.filters, [FileFilter::new("XML Files (*.xml)", &["xml"])]);
|
||||
files.answer(Picked::Contents(vec![(path, saved)])).unwrap();
|
||||
h.run_steps(3);
|
||||
assert_eq!(fields(&h, id), &original);
|
||||
assert!(written.borrow().is_empty(), "Load does not write output or close the dialog");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_and_cancelled_picks_leave_the_form_unchanged() {
|
||||
let (mut h, id, files, written) = harness();
|
||||
let original = fields(&h, id).clone();
|
||||
|
||||
click(&mut h, "Save…");
|
||||
files.answer(Picked::Cancelled).unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(written.borrow().is_empty());
|
||||
click(&mut h, "Load…");
|
||||
files.answer(Picked::Cancelled).unwrap();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().framework.dialogs.stack().top(), Some(id));
|
||||
|
||||
let path = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(path.path(), b"<ImageProcessor><useopen>true</useopen><dest>A & B</dest></ImageProcessor>").unwrap();
|
||||
click(&mut h, "Load…");
|
||||
files.answer(Picked::Paths(vec![path.path().to_path_buf()])).unwrap();
|
||||
h.run_steps(3);
|
||||
assert_eq!(fields(&h, id), &original);
|
||||
let alert = h.state().framework.dialogs.stack().top().unwrap();
|
||||
assert_ne!(alert, id, "an error is shown over the form");
|
||||
assert!(h.state().ui.status.contains("unescaped ampersand"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_load_answer_for_a_closed_dialog_does_not_edit_a_reopened_dialog() {
|
||||
let (mut h, id, files, _) = harness();
|
||||
click(&mut h, "Load…");
|
||||
let ctx = h.ctx.clone();
|
||||
crate::dialogs::cancel(h.state_mut(), &ctx, id).unwrap();
|
||||
let reopened = open(h.state_mut());
|
||||
let original = fields(&h, reopened).clone();
|
||||
files.answer(Picked::Contents(vec![("preset.xml".into(), b"<ImageProcessor><q>12</q></ImageProcessor>".to_vec())])).unwrap();
|
||||
h.run_steps(4);
|
||||
assert_eq!(fields(&h, reopened), &original);
|
||||
}
|
||||
@@ -2,7 +2,12 @@
|
||||
//! built with the rest of the form by `view_cmds::dialogs::params_for`; this module folds their values into the
|
||||
//! per-format objects the command takes and refuses an OK with no format ticked.
|
||||
|
||||
use craft::ui::patterns::form_dialogs::ParamResult;
|
||||
use craft::host::{PickRequest, Picked};
|
||||
use craft::theme::Variant;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::contract::{LeastWidth, Props as _, Show as _, TooltipSpec, clicked};
|
||||
use craft::ui::dialog::DialogId;
|
||||
use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamDialog, ParamResult};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
@@ -56,5 +61,120 @@ pub(crate) fn check(app: &mut PhotocraftApp, result: &ParamResult) -> Result<(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum SettingsAction {
|
||||
Load,
|
||||
Save,
|
||||
}
|
||||
|
||||
fn settings_action_id() -> egui::Id {
|
||||
egui::Id::unique("pc-image-processor-settings-action")
|
||||
}
|
||||
|
||||
fn generation_id() -> egui::Id {
|
||||
egui::Id::unique("pc-image-processor-settings-generation")
|
||||
}
|
||||
|
||||
pub(crate) fn settings_footer(dialog: ParamDialog<'_>) -> ParamDialog<'_> {
|
||||
dialog.ok_label(Label::from(tl!("Run"))).shaped(|dialog| {
|
||||
dialog.footer(|ui, _| {
|
||||
for (action, label, tip) in [
|
||||
(SettingsAction::Load, tl!("Load…"), tl!("Load a settings file from disk")),
|
||||
(SettingsAction::Save, tl!("Save…"), tl!("Save the current dialog settings to disk")),
|
||||
] {
|
||||
let button = Button::new(label).variant(Variant::SECONDARY).least_width(LeastWidth::DialogButton).tooltip(TooltipSpec::new(tip));
|
||||
if clicked(&button.show(ui)) {
|
||||
ui.ctx().data_mut(|data| data.insert_temp(settings_action_id(), action));
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The dialog's id is reused when it reopens. A picker left over from a previous opening must not touch the new form.
|
||||
pub(crate) fn settings_opened(ctx: &egui::Context) {
|
||||
ctx.data_mut(|data| {
|
||||
let generation = data.get_temp_mut_or_default::<u64>(generation_id());
|
||||
*generation = generation.wrapping_add(1);
|
||||
data.remove::<SettingsAction>(settings_action_id());
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn take_settings_action(app: &mut PhotocraftApp, ctx: &egui::Context, id: DialogId) {
|
||||
let action = ctx.data_mut(|data| {
|
||||
let id = settings_action_id();
|
||||
let action = data.get_temp::<SettingsAction>(id)?;
|
||||
data.remove::<SettingsAction>(id);
|
||||
Some(action)
|
||||
});
|
||||
let Some(action) = action else { return };
|
||||
let result = pick_settings(app, id, action);
|
||||
if let Err(error) = result
|
||||
&& error != crate::file_dialog::CANCELLED
|
||||
{
|
||||
crate::dialogs::alerts::alert(app, error);
|
||||
}
|
||||
}
|
||||
|
||||
fn pick_settings(app: &mut PhotocraftApp, id: DialogId, action: SettingsAction) -> Result<Value, String> {
|
||||
const PURPOSE: &str = "imageProcessorSettings";
|
||||
let generation = app.ctx().data(|data| data.get_temp::<u64>(generation_id()));
|
||||
let (request, bytes) = match action {
|
||||
SettingsAction::Load => (PickRequest::open(PURPOSE).title(tl!("Pick an XML file to load")), None),
|
||||
SettingsAction::Save => {
|
||||
let Some(dialog) = app.framework.dialogs.get_by_id::<HostedParamDialog>(id) else { return Ok(Value::Null) };
|
||||
let request = PickRequest::save(PURPOSE).title(tl!("Pick an XML file to save")).file_name("Image Processor.xml").suggested_extension("xml");
|
||||
(request, Some(settings::encode(dialog.fields())?))
|
||||
}
|
||||
};
|
||||
app.ask_file(request.filter(tl!("XML Files (*.xml)"), &["xml"]), move |app, picked| {
|
||||
if app.ctx().data(|data| data.get_temp::<u64>(generation_id())) != generation || app.framework.dialogs.get_by_id::<HostedParamDialog>(id).is_none() {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let result = match bytes {
|
||||
Some(bytes) => write_settings(app, picked, &bytes),
|
||||
None => load_settings(app, id, picked),
|
||||
};
|
||||
result.inspect_err(|error| {
|
||||
if error != crate::file_dialog::CANCELLED {
|
||||
crate::dialogs::alerts::alert(app, error.clone());
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn load_settings(app: &mut PhotocraftApp, id: DialogId, picked: Picked) -> Result<Value, String> {
|
||||
let bytes = match picked {
|
||||
Picked::Contents(files) => files.into_iter().next().map(|(_, bytes)| bytes).ok_or(crate::file_dialog::CANCELLED)?,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Picked::Paths(paths) => {
|
||||
let path = paths.first().ok_or(crate::file_dialog::CANCELLED)?;
|
||||
photocraft_format::read_file_limited(path, settings::MAX_BYTES as u64).map_err(|error| format!("{}: {error}", path.display()))?
|
||||
}
|
||||
_ => return Err(tl!("Could not open the Image Processor settings file.").into()),
|
||||
};
|
||||
let fields = settings::decode(&bytes)?;
|
||||
if let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedParamDialog>(id) {
|
||||
for (key, value) in fields.iter() {
|
||||
dialog.set_field(key, value.clone());
|
||||
}
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn write_settings(app: &mut PhotocraftApp, picked: Picked, bytes: &[u8]) -> Result<Value, String> {
|
||||
let path = picked.first_path().ok_or(crate::file_dialog::CANCELLED)?;
|
||||
let path = path.to_str().ok_or(tl!("The settings file name is not valid text."))?;
|
||||
let write = app.services.write.as_mut().ok_or(tl!("Saving Image Processor settings is unavailable."))?;
|
||||
write(path, bytes)?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
mod settings;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "image_processor_settings_tests.rs"]
|
||||
mod settings_tests;
|
||||
@@ -0,0 +1,202 @@
|
||||
//! XML presets for the Image Processor dialog. The element names and order follow the measured settings file.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fmt::Write;
|
||||
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue};
|
||||
use craft_xml::{Doctype, Event, Limits, Node, Options};
|
||||
|
||||
pub(super) const MAX_BYTES: usize = 256 * 1024;
|
||||
|
||||
const ROOT: &str = "ImageProcessor";
|
||||
// XML has only an open-documents/folder switch. A processing instruction preserves PhotoCraft's
|
||||
// third choice without adding an element to the reference format.
|
||||
const CURRENT_SOURCE: &str = r#"source="current""#;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Kind {
|
||||
OpenDocuments,
|
||||
Bool(bool),
|
||||
Text,
|
||||
Int(i64),
|
||||
Quality,
|
||||
}
|
||||
|
||||
use Kind::{Bool, Int, OpenDocuments, Quality, Text};
|
||||
|
||||
// Fields without a dialog key use the current processor behavior. Load validates those settings too.
|
||||
const ELEMENTS: &[(&str, Option<&str>, Kind)] = &[
|
||||
("version", None, Int(1)),
|
||||
("useopen", Some("source"), OpenDocuments),
|
||||
("includesub", Some("includeSubfolders"), Bool(false)),
|
||||
("source", Some("input"), Text),
|
||||
("open", None, Bool(false)),
|
||||
("saveinsame", None, Bool(false)),
|
||||
("dest", Some("output"), Text),
|
||||
("jpeg", Some("jpeg/enabled"), Bool(true)),
|
||||
("psd", Some("psd/enabled"), Bool(false)),
|
||||
("tiff", Some("tiff/enabled"), Bool(false)),
|
||||
("lzw", Some("tiff/lzw"), Bool(false)),
|
||||
("converticc", Some("jpeg/convertToSrgb"), Bool(false)),
|
||||
("q", Some("jpeg/quality"), Quality),
|
||||
("max", Some("psd/maximizeCompatibility"), Bool(true)),
|
||||
("jpegresize", Some("jpeg/resize"), Bool(false)),
|
||||
("jpegw", Some("jpeg/width"), Int(30_000)),
|
||||
("jpegh", Some("jpeg/height"), Int(30_000)),
|
||||
("psdresize", Some("psd/resize"), Bool(false)),
|
||||
("psdw", Some("psd/width"), Int(30_000)),
|
||||
("psdh", Some("psd/height"), Int(30_000)),
|
||||
("tiffresize", Some("tiff/resize"), Bool(false)),
|
||||
("tiffw", Some("tiff/width"), Int(30_000)),
|
||||
("tiffh", Some("tiff/height"), Int(30_000)),
|
||||
("runaction", None, Bool(false)),
|
||||
("actionset", None, Text),
|
||||
("action", None, Text),
|
||||
("info", None, Text),
|
||||
("icc", None, Bool(true)),
|
||||
("keepstructure", None, Bool(true)),
|
||||
];
|
||||
|
||||
fn invalid(tag: &str) -> String {
|
||||
crate::i18n::fmt(tl!("Invalid Image Processor setting: {setting}"), &[("setting", tag)])
|
||||
}
|
||||
|
||||
fn too_large() -> String {
|
||||
tl!("The Image Processor settings file is too large.").into()
|
||||
}
|
||||
|
||||
pub(super) fn encode(fields: &DialogFields) -> Result<Vec<u8>, String> {
|
||||
let mut xml = String::from('\u{feff}');
|
||||
let _ = writeln!(xml, "<{ROOT}>");
|
||||
if fields.text("source") == Some("current") {
|
||||
let _ = writeln!(xml, "\t<?PhotoCraft {CURRENT_SOURCE}?>");
|
||||
}
|
||||
for &(tag, field, kind) in ELEMENTS {
|
||||
let field = field.unwrap_or_default();
|
||||
let _ = write!(xml, "\t<{tag}>");
|
||||
match kind {
|
||||
OpenDocuments => xml.push_str(if fields.text(field) == Some("open") { "true" } else { "false" }),
|
||||
Bool(default) => {
|
||||
let _ = write!(xml, "{}", fields.bool(field).unwrap_or(default));
|
||||
}
|
||||
Int(max) => {
|
||||
let value = fields.int(field).unwrap_or(1);
|
||||
if !(1..=max).contains(&value) {
|
||||
return Err(invalid(tag));
|
||||
}
|
||||
let _ = write!(xml, "{value}");
|
||||
}
|
||||
Quality => {
|
||||
let value = fields.number(field).unwrap_or(5.0);
|
||||
if !(1.0..=12.0).contains(&value) {
|
||||
return Err(invalid(tag));
|
||||
}
|
||||
let _ = write!(xml, "{value}");
|
||||
}
|
||||
Text => {
|
||||
let text = fields.text(field).unwrap_or_default();
|
||||
if text.len() > MAX_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
if !text.chars().all(craft_xml::is_xml_char) {
|
||||
return Err(invalid(tag));
|
||||
}
|
||||
// Keep the preset's one element per line even for paths containing line breaks.
|
||||
xml.push_str(&craft_xml::esc(text).replace('\n', " "));
|
||||
}
|
||||
}
|
||||
let _ = writeln!(xml, "</{tag}>");
|
||||
}
|
||||
let _ = writeln!(xml, "</{ROOT}>");
|
||||
if xml.len() > MAX_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
Ok(xml.into_bytes())
|
||||
}
|
||||
|
||||
pub(super) fn decode(bytes: &[u8]) -> Result<DialogFields, String> {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| tl!("Image Processor settings must be UTF-8.").to_string())?;
|
||||
let options = Options { doctype: Doctype::Reject, pis: true, ..Options::default() }.strict().with_limits(Limits {
|
||||
max_input: MAX_BYTES,
|
||||
max_depth: 32,
|
||||
max_nodes: 4096,
|
||||
..Limits::default()
|
||||
});
|
||||
if text.contains('&') {
|
||||
validate_references(text.strip_prefix('\u{feff}').unwrap_or(text), &options)?;
|
||||
}
|
||||
let root = options.parse(bytes).map_err(xml_error)?;
|
||||
if root.name != ROOT || root.attr("xmlns").is_some_and(|ns| !ns.is_empty()) {
|
||||
return Err(tl!("This file does not contain Image Processor settings.").into());
|
||||
}
|
||||
let current = root.children.iter().any(|node| matches!(node, Node::Pi { target, data } if target == "PhotoCraft" && data == CURRENT_SOURCE));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut updates = DialogFields::new();
|
||||
for node in &root.children {
|
||||
let child = match node {
|
||||
Node::El(child) if child.attr("xmlns").is_none_or(str::is_empty) => child,
|
||||
Node::Text(text) if !text.trim().is_empty() => return Err(invalid(ROOT)),
|
||||
_ => continue,
|
||||
};
|
||||
let tag = child.name.as_str();
|
||||
let Some(&(_, field, kind)) = ELEMENTS.iter().find(|(name, _, _)| *name == tag) else { continue };
|
||||
if !seen.insert(tag) || child.children.iter().any(|node| matches!(node, Node::El(_))) {
|
||||
return Err(invalid(tag));
|
||||
}
|
||||
let value = parse_value(kind, child.text(), current).ok_or_else(|| invalid(tag))?;
|
||||
if let Some(field) = field {
|
||||
updates.set(field, value);
|
||||
}
|
||||
}
|
||||
Ok(updates)
|
||||
}
|
||||
|
||||
fn xml_error(error: craft_xml::Error) -> String {
|
||||
crate::i18n::fmt(tl!("Could not read Image Processor settings: {error}"), &[("error", &error.to_string())])
|
||||
}
|
||||
|
||||
/// The shared reader accepts bare ampersands even in strict mode. Its event spans let us
|
||||
/// check the original text and attributes without treating CDATA, comments or instructions as XML text.
|
||||
fn validate_references(text: &str, options: &Options<'_>) -> Result<(), String> {
|
||||
let mut events = options.events(text.as_bytes());
|
||||
while let Some(event) = events.next().map_err(xml_error)? {
|
||||
if !matches!(event, Event::Text(_) | Event::Start { .. }) {
|
||||
continue;
|
||||
}
|
||||
let raw = text.get(events.span()).ok_or_else(|| invalid(ROOT))?;
|
||||
if raw.split('&').skip(1).any(|tail| tail.split_once(';').and_then(|(name, _)| craft_xml::entity(name)).is_none()) {
|
||||
return Err(tl!("Image Processor settings contain an unescaped ampersand.").into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_value(kind: Kind, text: Cow<'_, str>, current: bool) -> Option<FieldValue> {
|
||||
let trimmed = text.trim();
|
||||
Some(match kind {
|
||||
OpenDocuments => {
|
||||
let open = trimmed.parse::<bool>().ok()?;
|
||||
if open {
|
||||
"open"
|
||||
} else if current {
|
||||
"current"
|
||||
} else {
|
||||
"folder"
|
||||
}
|
||||
.into()
|
||||
}
|
||||
Bool(_) => trimmed.parse::<bool>().ok()?.into(),
|
||||
Text => text.into_owned().into(),
|
||||
Int(max) => {
|
||||
let value = trimmed.parse::<i64>().ok()?;
|
||||
(1..=max).contains(&value).then_some(value)?.into()
|
||||
}
|
||||
Quality => {
|
||||
let value = trimmed.parse::<f64>().ok()?;
|
||||
(1.0..=12.0).contains(&value).then_some(value)?.into()
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -718,6 +718,29 @@ fn style_click_does_not_mutate_document_until_confirm() {
|
||||
assert_eq!(layer_effects(&h.state().session).len(), 1);
|
||||
}
|
||||
|
||||
/// #14977: a Satin the dialog creates starts at the measured factory values. The page's rows and
|
||||
/// their default table now live in the UI framework, whose Satin defaults are still 19 / 11 / 14;
|
||||
/// `specs` lays the app's engine defaults OVER that table, so the instance the page adds starts at
|
||||
/// the engine's 90 / 50 / 80.
|
||||
#[test]
|
||||
fn a_new_satin_in_the_dialog_starts_at_the_factory_values() {
|
||||
let mut app = app_with_layer(32);
|
||||
let id = open(&mut app, Some(EffectKind::Satin.key())).unwrap();
|
||||
let satin = first_of(&app, id, EffectKind::Satin);
|
||||
let style = &draft(&app, id).style;
|
||||
assert_eq!(
|
||||
(num(style, satin, "angle"), num(style, satin, "distance"), num(style, satin, "size")),
|
||||
(Some(90.0), Some(50.0), Some(80.0)),
|
||||
"the new Satin page starts at the measured values"
|
||||
);
|
||||
assert_eq!(text(style, satin, "blend").as_deref(), Some("Multiply"), "blend mode");
|
||||
assert_eq!(num(style, satin, "opacity"), Some(50.0), "opacity");
|
||||
assert_eq!(param(style, satin, "invert"), Some(StyleValue::Bool(true)), "invert");
|
||||
assert_eq!(param(style, satin, "antiAlias"), Some(StyleValue::Bool(true)), "anti-aliased");
|
||||
cancel(&mut app, id);
|
||||
assert!(layer_effects(&app.session).is_empty(), "Cancel added no effect");
|
||||
}
|
||||
|
||||
/// #14944: the Outer Glow page is grouped Photoshop-style - Noise right under Opacity, the rows of
|
||||
/// the Structure, Elements and Quality blocks. The hosted page draws `specs()` rows in order, so
|
||||
/// the page order is pinned here; the group TITLES belong to the framework's page (craft-libs has
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::dispatch::no_params;
|
||||
use super::{PhotocraftApp, Value, json};
|
||||
use crate::dialogs::image_processor_ui;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Outcome as _, Props as _, Show as _};
|
||||
use craft::ui::dialog::DialogId;
|
||||
@@ -56,9 +57,14 @@ fn opened(id: DialogId) -> Value {
|
||||
fn open_form(app: &mut PhotocraftApp, id: &str, title: &str, params: Vec<Param>, fields: DialogFields, fixed: Value) -> DialogId {
|
||||
let title = crate::dialogs::filter_dialog::title_of(title);
|
||||
let key = id.to_owned();
|
||||
let image_processor = id == image_processor_ui::COMMAND;
|
||||
if image_processor {
|
||||
image_processor_ui::settings_opened(app.ctx());
|
||||
}
|
||||
crate::dialogs::params::open_param(app, id, fields, fixed, move |fields: &mut DialogFields| {
|
||||
derive(&key, fields);
|
||||
ParamDialog::command(key.clone(), title.clone(), params.clone()).values(Bind::bound(fields))
|
||||
let dialog = ParamDialog::command(key.clone(), title.clone(), params.clone()).values(Bind::bound(fields));
|
||||
if image_processor { image_processor_ui::settings_footer(dialog) } else { dialog }
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -191,10 +191,14 @@ pub(crate) fn open_recorded_editor(app: &mut PhotocraftApp, id: &str, params: &V
|
||||
// Private keys belong to the dialog, not the recorded Action step.
|
||||
object.retain(|key, _| !key.starts_with("__"));
|
||||
}
|
||||
if let Some(dialog) = crate::adjust_dialog::open_with_params(app, id, &values) {
|
||||
match crate::adjust_dialog::open_with_params_checked(app, id, &values) {
|
||||
// Adjustment dialogs normalized their effective target already. Raw parameters here
|
||||
// would restore discarded Lab/CMYK records or override the normalized tone controls.
|
||||
return Ok(dialog);
|
||||
Ok(dialog) => return Ok(dialog),
|
||||
// The editor refuses these parameters (a CMYK Channel Mixer, #8047): say why instead of
|
||||
// opening the generic step editor over them.
|
||||
Err(Some(reason)) => return Err(reason),
|
||||
Err(None) => {}
|
||||
}
|
||||
let dialog = open_step_editor(app, id, &values)?;
|
||||
if !crate::sizing::is_sizing(id) {
|
||||
|
||||
@@ -2157,3 +2157,15 @@ fn save_hook_closing_the_target_stops_an_imported_close_with_save() {
|
||||
assert!(app.session.recording.playback_stack.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// #8047: a recorded Channel Mixer step with ink outputs reopened in an RGB document is refused by
|
||||
/// the RGB-only editor. Playback must say why, not fall back to the generic step editor over it.
|
||||
#[test]
|
||||
fn a_recorded_cmyk_channel_mixer_step_reports_the_editors_refusal() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 4, "height": 4})).unwrap();
|
||||
let open = app.framework.dialogs.open_dialogs().len();
|
||||
let result = open_recorded_editor(&mut app, "image.adjustments.channelMixer", &json!({"cyan": [80, 0, 0, 0, 0]}));
|
||||
assert_eq!(result, Err(crate::adjust_editors::values::CMYK_MIXER_UNAVAILABLE.to_string()));
|
||||
assert_eq!(app.framework.dialogs.open_dialogs().len(), open, "no editor opened");
|
||||
}
|
||||
@@ -165,8 +165,15 @@ pub fn open_editor(app: &mut PhotocraftApp, ctx: &egui::Context, layer: u64, sm:
|
||||
return;
|
||||
}
|
||||
};
|
||||
if crate::adjust_dialog::open_smart_filter(app, &f.command, &f.params, target.clone()).is_some() || !crate::filter_dialog::has_dialog(&f.command) {
|
||||
return;
|
||||
match crate::adjust_dialog::open_smart_filter_checked(app, &f.command, &f.params, target.clone()) {
|
||||
Ok(_) => return,
|
||||
// The editor refuses these parameters (a CMYK Channel Mixer, #8047): say why instead of opening nothing.
|
||||
Err(Some(reason)) => {
|
||||
crate::notices::error(app, reason);
|
||||
return;
|
||||
}
|
||||
Err(None) if !crate::filter_dialog::has_dialog(&f.command) => return,
|
||||
Err(None) => {}
|
||||
}
|
||||
// The hosted filter dialog carries the target as its captured value; the recorded parameters
|
||||
// overlay the schema defaults, not the user's last-used values.
|
||||
|
||||
@@ -587,11 +587,27 @@ fn a_channel_mixer_smart_filter_turned_off_monochrome_keeps_its_red_row() {
|
||||
let sm = recorded(h.state(), id);
|
||||
assert_eq!(sm.smart_filters.len(), 1, "no filter was stacked");
|
||||
let adjustment = photocraft_engine::adjust_params::from_params("channelMixer", &sm.smart_filters[0].params, None, photocraft_doc::ColorMode::Rgb).unwrap();
|
||||
let photocraft_doc::Adjustment::ChannelMixer { matrix, monochrome } = adjustment else { panic!("Channel Mixer params") };
|
||||
let photocraft_doc::Adjustment::ChannelMixer { matrix, monochrome, .. } = adjustment else { panic!("Channel Mixer params") };
|
||||
assert!(!monochrome);
|
||||
assert!(matrix[0].iter().zip([0.7, 0.3, 0.0, 0.0]).all(|(a, b)| (a - b).abs() < 1e-5), "the edited Red row renders: {:?}", matrix[0]);
|
||||
}
|
||||
|
||||
/// #8047: the framework Channel Mixer editor has red, green and blue outputs only. A Channel Mixer
|
||||
/// smart filter with ink outputs (`cyan`..`black` keys, accepted in any document mode) reopened in
|
||||
/// an RGB document must not open it over RGB defaults, whose edits the engine would drop beside the
|
||||
/// ink keys: nothing opens, the reason is shown, and the filter keeps its params.
|
||||
#[test]
|
||||
fn a_cmyk_channel_mixer_smart_filter_is_not_opened_in_the_rgb_editor() {
|
||||
let (app, id) = adjustment_filter("rgb", "image.adjustments.channelMixer", json!({"cyan": [80, 0, 0, 0, 0]}));
|
||||
let before = recorded(&app, id).smart_filters[0].params.clone();
|
||||
assert!(photocraft_engine::adjust_params::MIXER_INKS.iter().any(|k| before.get(*k).is_some()), "an ink-output filter: {before}");
|
||||
let h = edit_first_filter(app, id);
|
||||
assert!(h.state().adjust_open.is_none(), "no Channel Mixer editor opened");
|
||||
assert_eq!(h.state().ui.status, crate::adjust_editors::values::CMYK_MIXER_UNAVAILABLE, "the reason is shown");
|
||||
assert!(h.state().ui.status_error);
|
||||
assert_eq!(recorded(h.state(), id).smart_filters[0].params, before, "the filter is kept as it is");
|
||||
}
|
||||
|
||||
/// In Lab, top-level `points` aliases Lightness and the editor writes both on an edit. A stored
|
||||
/// one must not override the edit: the Lightness the editor sends is what the filter renders.
|
||||
#[test]
|
||||
|
||||
@@ -68,6 +68,14 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V
|
||||
crate::monitor_status::read_now(app);
|
||||
dialog(crate::filter_dialog::open(app, "edit.colorSettings"))
|
||||
}
|
||||
"edit.findAndReplaceText"
|
||||
if app
|
||||
.session
|
||||
.active()
|
||||
.is_some_and(|st| st.doc.walk().iter().all(|(_, _, layer)| !matches!(layer.content, photocraft_doc::LayerContent::Text(_)))) =>
|
||||
{
|
||||
Some(Ok(Value::Null))
|
||||
}
|
||||
"edit.fade" | "edit.findAndReplaceText" | "edit.defineBrushPreset" | "edit.defineCustomShape" | "edit.autoAlignLayers" | "edit.autoBlendLayers" => {
|
||||
if !app.session.is_enabled(id) {
|
||||
return Some(Err(photocraft_engine::commands::find(id)
|
||||
@@ -354,3 +362,40 @@ pub(crate) fn set_draft(app: &mut PhotocraftApp, key: &str, value: PrefValue) ->
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod find_replace_empty_tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn find_replace_empty_menu_invocation_is_silent() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let ctx = app.ctx().clone();
|
||||
let command = "edit.findAndReplaceText";
|
||||
assert!(!crate::menus::is_enabled(&app, command));
|
||||
assert!(crate::menus::invoke(&mut app, &ctx, command, json!({})).is_err());
|
||||
|
||||
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
assert!(crate::menus::is_enabled(&app, command));
|
||||
let before = app.session.active().unwrap().doc.clone();
|
||||
let history = app.session.active().unwrap().history.entries();
|
||||
let status = (app.ui.status.clone(), app.ui.status_error);
|
||||
assert_eq!(crate::menus::invoke(&mut app, &ctx, command, json!({})).unwrap(), Value::Null);
|
||||
assert!(!app.dialog_open());
|
||||
assert_eq!((app.ui.status.clone(), app.ui.status_error), status);
|
||||
assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));
|
||||
assert_eq!(app.session.active().unwrap().history.entries(), history);
|
||||
|
||||
app.run("type.create", json!({"text": "word", "size": 8})).unwrap();
|
||||
app.run("layer.setProps", json!({"locked": true})).unwrap();
|
||||
assert!(!crate::menus::is_enabled(&app, command));
|
||||
assert!(crate::menus::invoke(&mut app, &ctx, command, json!({})).is_err());
|
||||
assert!(!app.dialog_open());
|
||||
app.run("layer.setProps", json!({"locked": false})).unwrap();
|
||||
assert!(crate::menus::is_enabled(&app, command));
|
||||
let result = crate::menus::invoke(&mut app, &ctx, command, json!({})).unwrap();
|
||||
assert!(result.get("dialog").is_some(), "{result}");
|
||||
assert!(app.dialog_open());
|
||||
}
|
||||
}
|
||||
@@ -146,3 +146,23 @@ fn an_edit_still_marks_the_set_modified_and_sets_save_no_action_keys() {
|
||||
h.state_mut().run("edit.keyboardShortcuts", json!({"set": {"edit.cut": "F7"}})).unwrap();
|
||||
assert!(modified(h.state().session.prefs()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_custom_set_waits_for_confirmation_and_dialog_ok() {
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
let mut h = harness();
|
||||
h.state_mut().run("edit.keyboardShortcuts", json!({"set":{"edit.copy":"F9"},"saveSet":"Painting"})).unwrap();
|
||||
open(&mut h);
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Delete").click();
|
||||
h.run_steps(3);
|
||||
let question = h.get_by_label("Delete the set “Painting”?");
|
||||
assert!(h.state().prefs_rt.shortcuts.as_ref().unwrap().profiles.sets().contains_key("Painting"));
|
||||
let cancel = std::iter::successors(question.parent(), |node| node.parent())
|
||||
.find_map(|scope| scope.query_by_label("Cancel"))
|
||||
.expect("the confirmation offers Cancel");
|
||||
cancel.click();
|
||||
h.run_steps(3);
|
||||
assert!(h.query_by_label("Delete the set “Painting”?").is_none(), "Cancel closes the confirmation");
|
||||
assert!(h.state().prefs_rt.shortcuts.as_ref().unwrap().profiles.sets().contains_key("Painting"));
|
||||
}
|
||||
@@ -113,15 +113,25 @@ pub(crate) fn drain(app: &mut PhotocraftApp, state: &mut AnalysisTools, _respons
|
||||
}
|
||||
for event in state.sampler.take_events() {
|
||||
let result = match event {
|
||||
SamplerEvent::Add { at, .. } => app.run("view.colorSamplers.add", json!({"x": at[0], "y": at[1]})),
|
||||
SamplerEvent::Add { at, .. } => {
|
||||
if app.session.active().is_some_and(|st| st.color_samplers.len() >= photocraft_engine::sampler_cmds::MAX_SAMPLERS) {
|
||||
open_max_samplers_alert(app);
|
||||
continue;
|
||||
}
|
||||
let r = app.run("view.colorSamplers.add", json!({"x": at[0], "y": at[1]}));
|
||||
if r.is_ok() {
|
||||
reveal_info_panel(app);
|
||||
}
|
||||
r
|
||||
}
|
||||
SamplerEvent::Move { index, to, .. } => app.run("view.colorSamplers.move", json!({"index": index, "x": to[0], "y": to[1]})),
|
||||
SamplerEvent::Remove { index, .. } => app.run("view.colorSamplers.delete", json!({"index": index})),
|
||||
_ => continue,
|
||||
};
|
||||
status_on_err(app, result);
|
||||
}
|
||||
if let Some(toast) = state.sampler.take_error() {
|
||||
crate::notices::post(app, toast.message.as_str().to_owned(), Vec::new(), toast.tone, None);
|
||||
if let Some(_toast) = state.sampler.take_error() {
|
||||
open_max_samplers_alert(app);
|
||||
}
|
||||
for event in std::mem::take(&mut state.count.events) {
|
||||
match event {
|
||||
@@ -162,6 +172,28 @@ pub(crate) fn drain(app: &mut PhotocraftApp, state: &mut AnalysisTools, _respons
|
||||
}
|
||||
}
|
||||
|
||||
/// The alert when the 11th Color Sampler is clicked (#11743).
|
||||
#[cfg(test)]
|
||||
pub const MAX_SAMPLERS_ALERT: &str = "Could not create a new sampler because the maximum number of samplers is 10.";
|
||||
|
||||
/// Open the alert dialog when the Color Sampler limit is reached (#11743).
|
||||
fn open_max_samplers_alert(app: &mut PhotocraftApp) {
|
||||
app.ui.status.clear();
|
||||
app.ui.status_error = false;
|
||||
let message = crate::i18n::fmt(
|
||||
tl!("Could not create a new sampler because the maximum number of samplers is {max}."),
|
||||
&[("max", &photocraft_engine::sampler_cmds::MAX_SAMPLERS.to_string())],
|
||||
);
|
||||
let _ = crate::dialogs::alerts::alert(app, message);
|
||||
}
|
||||
|
||||
/// Open the closed Info panel when a Color Sampler point is placed (#11745).
|
||||
pub(crate) fn reveal_info_panel(app: &mut PhotocraftApp) {
|
||||
if !crate::panel_docking::is_checked(app, "info") {
|
||||
let _ = crate::panel_docking::show_panel(app, "info", Some(true));
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores the Ruler line in the document: `None` clears it.
|
||||
fn set_ruler(app: &mut PhotocraftApp, line: Option<RulerLine>) {
|
||||
let params = match line {
|
||||
|
||||
@@ -295,6 +295,143 @@ fn a_hidden_layer_keeps_the_button_and_the_click_shows_the_alert() {
|
||||
assert!(ruler(st).is_some(), "the ruler line is still there");
|
||||
}
|
||||
|
||||
/// The messages of the alerts open on the host.
|
||||
fn alerts(app: &PhotocraftApp) -> Vec<String> {
|
||||
app.framework
|
||||
.dialogs
|
||||
.open_dialogs()
|
||||
.into_iter()
|
||||
.filter(|d| d.key.as_deref() == Some("alert"))
|
||||
.filter_map(|d| Some(d.fields.as_ref()?["message"].as_str()?.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Closes every alert the host has open.
|
||||
fn close_alerts(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
let ids: Vec<_> = app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")).map(|d| d.id).collect();
|
||||
for id in ids {
|
||||
app.framework.dialogs.cancel_by_id(ctx, id);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_color_sampler_reveals_closed_info_panel() {
|
||||
let (mut app, _) = app();
|
||||
app.ui.tool = Tool::ColorSampler;
|
||||
// Close the Info panel.
|
||||
let _ = crate::panel_docking::show_panel(&mut app, "info", Some(false));
|
||||
assert!(!crate::panel_docking::is_checked(&app, "info"));
|
||||
|
||||
// Placing a sampler inside the canvas opens the Info panel (#11745).
|
||||
down(&mut app, 25.0, 30.0, egui::Modifiers::NONE);
|
||||
up(&mut app, 25.0, 30.0);
|
||||
assert!(crate::panel_docking::is_checked(&app, "info"));
|
||||
|
||||
// Placing a second sampler while the panel is already open leaves it open without error.
|
||||
down(&mut app, 45.0, 50.0, egui::Modifiers::NONE);
|
||||
up(&mut app, 45.0, 50.0);
|
||||
assert!(crate::panel_docking::is_checked(&app, "info"));
|
||||
|
||||
// A click on an existing sampler (starting a move or selection) does not reopen a closed panel.
|
||||
let _ = crate::panel_docking::show_panel(&mut app, "info", Some(false));
|
||||
assert!(!crate::panel_docking::is_checked(&app, "info"));
|
||||
down(&mut app, 25.0, 30.0, egui::Modifiers::NONE);
|
||||
up(&mut app, 25.0, 30.0);
|
||||
assert!(!crate::panel_docking::is_checked(&app, "info"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_color_sampler_in_docked_workspace_leaves_info_panel_open() {
|
||||
let (mut app, _) = app();
|
||||
app.ui.tool = Tool::ColorSampler;
|
||||
// Dock the Info panel in an expanded column and close it.
|
||||
app.run("window.panel.move", json!({"panel": "info", "anchor": "layers", "zone": "top"})).unwrap();
|
||||
let _ = crate::panel_docking::show_panel(&mut app, "info", Some(false));
|
||||
assert!(!crate::panel_docking::is_checked(&app, "info"));
|
||||
|
||||
// Placing a sampler inside the canvas reveals the Info panel (#11745).
|
||||
down(&mut app, 25.0, 30.0, egui::Modifiers::NONE);
|
||||
up(&mut app, 25.0, 30.0);
|
||||
assert!(crate::panel_docking::is_checked(&app, "info"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_sampler_limit_opens_alert_dialog_instead_of_status_note() {
|
||||
let (mut app, _) = app();
|
||||
app.ui.tool = Tool::ColorSampler;
|
||||
for i in 0..10 {
|
||||
let x = 10.0 + (i as f64) * 10.0;
|
||||
down(&mut app, x, 20.0, egui::Modifiers::NONE);
|
||||
up(&mut app, x, 20.0);
|
||||
}
|
||||
assert_eq!(app.session.active().unwrap().color_samplers.len(), 10);
|
||||
assert!(alerts(&app).is_empty());
|
||||
|
||||
// Prepare non-empty status and closed Info panel to verify state is cleared and panel is untouched.
|
||||
app.ui.status = "Previous status".into();
|
||||
app.ui.status_error = true;
|
||||
let _ = crate::panel_docking::show_panel(&mut app, "info", Some(false));
|
||||
assert!(!crate::panel_docking::is_checked(&app, "info"));
|
||||
|
||||
// The 11th click opens the limit alert dialog instead of a status-bar note (#11743).
|
||||
down(&mut app, 150.0, 20.0, egui::Modifiers::NONE);
|
||||
up(&mut app, 150.0, 20.0);
|
||||
assert_eq!(app.session.active().unwrap().color_samplers.len(), 10);
|
||||
assert_eq!(app.ui.status, "");
|
||||
assert!(!app.ui.status_error);
|
||||
// Limit rejection does not reveal or change the Info panel.
|
||||
assert!(!crate::panel_docking::is_checked(&app, "info"));
|
||||
|
||||
let dialogs = alerts(&app);
|
||||
assert_eq!(dialogs, ["Could not create a new sampler because the maximum number of samplers is 10."]);
|
||||
assert_eq!(dialogs, [super::canvas::MAX_SAMPLERS_ALERT]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_sampler_limit_alert_also_for_alt_click_off_a_point() {
|
||||
// Measured in the reference application: Alt+click off a point adds a point like a plain
|
||||
// click, so at 10 points it opens the same alert; Alt+click on a point deletes it, no alert.
|
||||
let (mut app, ctx) = app();
|
||||
app.ui.tool = Tool::ColorSampler;
|
||||
for i in 0..10 {
|
||||
let x = 10.0 + (i as f64) * 10.0;
|
||||
down(&mut app, x, 20.0, egui::Modifiers::NONE);
|
||||
up(&mut app, x, 20.0);
|
||||
}
|
||||
down(&mut app, 150.0, 20.0, egui::Modifiers::ALT);
|
||||
up(&mut app, 150.0, 20.0);
|
||||
assert_eq!(app.session.active().unwrap().color_samplers.len(), 10);
|
||||
let dialogs = alerts(&app);
|
||||
assert_eq!(dialogs, ["Could not create a new sampler because the maximum number of samplers is 10."]);
|
||||
assert_eq!(dialogs, [super::canvas::MAX_SAMPLERS_ALERT]);
|
||||
|
||||
close_alerts(&mut app, &ctx);
|
||||
down(&mut app, 10.0, 20.0, egui::Modifiers::ALT);
|
||||
up(&mut app, 10.0, 20.0);
|
||||
assert_eq!(app.session.active().unwrap().color_samplers.len(), 9);
|
||||
assert!(alerts(&app).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_sampler_drag_error_reports_to_status_bar_without_dialog() {
|
||||
let (mut app, _) = app();
|
||||
app.ui.tool = Tool::ColorSampler;
|
||||
// Place a sampler
|
||||
down(&mut app, 25.0, 30.0, egui::Modifiers::NONE);
|
||||
up(&mut app, 25.0, 30.0);
|
||||
assert_eq!(app.session.active().unwrap().color_samplers.len(), 1);
|
||||
|
||||
// Start dragging the sampler point
|
||||
down(&mut app, 25.0, 30.0, egui::Modifiers::NONE);
|
||||
// Clear samplers while drag is in flight
|
||||
app.run("view.colorSamplers.clear", json!({})).unwrap();
|
||||
|
||||
// Release the drag inside canvas: move fails because point no longer exists
|
||||
up(&mut app, 50.0, 50.0);
|
||||
assert!(app.ui.status.contains("no sample point"), "status was: {}", app.ui.status);
|
||||
assert!(alerts(&app).is_empty());
|
||||
}
|
||||
|
||||
/// The height of the number painted beside the first Count marker of a document whose group has `label_size`, read
|
||||
/// from the frame's text shapes.
|
||||
fn count_number_height(label_size: u32) -> f32 {
|
||||
|
||||
@@ -92,6 +92,45 @@ pub(super) fn default_style_params(app: &PhotocraftApp) -> serde_json::Value {
|
||||
p
|
||||
}
|
||||
|
||||
/// The `type.create` keys a new Type Mask takes from the document's active text layer (#12077):
|
||||
/// the font, style and size the options bar shows for that layer, so the mask starts in the same
|
||||
/// type settings instead of the tool's fresh defaults. Measured is only a click (not a paragraph
|
||||
/// box) with the Horizontal Type Mask over a horizontal text layer, so any other active layer
|
||||
/// gives `None` and today's tool options apply. The colour stays the foreground colour, as the
|
||||
/// rest of the create parameters do.
|
||||
pub(super) fn mask_style_from_active_layer(app: &PhotocraftApp) -> Option<serde_json::Value> {
|
||||
let st = app.session.active()?;
|
||||
let t = text_layer(&st.doc, st.active_layer?)?;
|
||||
if t.orientation != photocraft_doc::text::Orientation::Horizontal {
|
||||
return None;
|
||||
}
|
||||
// The same first run the options bar names the layer by (`bar_character_values`), at the same
|
||||
// shown size: a 12 pt layer scaled 200 % shows 24 pt. Only reached with no type session open,
|
||||
// where `shown_scale` reads this very layer.
|
||||
let c = t.char_runs().into_iter().next()?.style;
|
||||
let mut p = json!({});
|
||||
// An empty name is the layer's placeholder for the default family, not a name to hand to
|
||||
// `type.create`: the key is only taken when the layer names one.
|
||||
if !c.font_family.is_empty() {
|
||||
p["font"] = json!(c.font_family);
|
||||
}
|
||||
if !c.font_style.is_empty() {
|
||||
p["fontStyle"] = json!(c.font_style);
|
||||
}
|
||||
let size = c.size_pt * shown_scale(app);
|
||||
// Only inherit a size `type.create` would itself accept, asked through the engine's own
|
||||
// `check_size_tracking` so the range stays single-sourced (0.1-1296 pt today). `json!` turns
|
||||
// a non-finite product into `null`, which the check refuses; a FINITE shown size can leave
|
||||
// the range too: an 800 pt layer under a 2x transform shows 1600 pt, and a corrupt document
|
||||
// can carry a 0 pt run. A refused parameter fails the whole create, and the click would make
|
||||
// no mask at all - so such a size stays out of the parameters and the tool's own applies, as
|
||||
// it does for a family or style the layer does not name.
|
||||
if photocraft_engine::type_cmds::check_size_tracking(&json!({ "size": size })).is_ok() {
|
||||
p["size"] = json!(size);
|
||||
}
|
||||
Some(p)
|
||||
}
|
||||
|
||||
/// Style numbers become f32 in the engine. JSON itself permits finite f64 values too large
|
||||
/// for that conversion; a hand-edited setting must not inject infinity into a new layer.
|
||||
/// Style collections (features, axes, colour) contain only scalar values, so no recursion.
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
//! #12077: with a text layer active, the Horizontal Type Mask starts a new mask in that layer's
|
||||
//! type settings - the font, style and size the options bar shows for the layer - and not in the
|
||||
//! tool's fresh defaults. The measured document (800x600 RGB/8, an 80 pt "TXT" active) gives the
|
||||
//! same selection size as the same text typed with the tool itself set to 80 pt and a pixel layer
|
||||
//! active; the text layer is not changed and stays active after the commit.
|
||||
//!
|
||||
//! The issue's *not measured* rows keep today's behaviour, pinned here: the Vertical Type Mask, a
|
||||
//! paragraph (box) drag, a mixed orientation (a vertical text layer active), a non-text active
|
||||
//! layer, and the tool options after the mask. Clicks and the box drag go through the canvas's
|
||||
//! tool events.
|
||||
|
||||
use egui::Modifiers;
|
||||
use photocraft_doc::LayerId;
|
||||
use serde_json::json;
|
||||
|
||||
use super::super::commit;
|
||||
use super::super::mask_replace_selection_tests::{bounds, click, new_app, selection};
|
||||
use super::super::{current_text, text_layer};
|
||||
use crate::PhotocraftApp;
|
||||
use crate::canvas::testing::{ToolEvent, tool_event};
|
||||
use crate::state::Tool;
|
||||
|
||||
/// The layer's first character run, which is what `bar_character_values` names the layer by.
|
||||
fn char_style(app: &PhotocraftApp, id: LayerId) -> photocraft_doc::text::CharStyle {
|
||||
let t = text_layer(&app.session.active().unwrap().doc, id).expect("a type layer");
|
||||
t.char_runs().into_iter().next().expect("a first character run").style
|
||||
}
|
||||
|
||||
/// What the options bar shows for the layer: its first character run's family, style name and size.
|
||||
fn style(app: &PhotocraftApp, id: LayerId) -> (String, String, f32) {
|
||||
let c = char_style(app, id);
|
||||
(c.font_family, c.font_style, c.size_pt)
|
||||
}
|
||||
|
||||
/// The working layer the open mask session is typing into.
|
||||
fn mask_style(app: &PhotocraftApp) -> (String, String, f32) {
|
||||
let ed = app.ui.text_edit.as_ref().expect("an open mask session");
|
||||
style(app, LayerId(ed.layer))
|
||||
}
|
||||
|
||||
fn active_layer(app: &PhotocraftApp) -> Option<LayerId> {
|
||||
app.session.active().and_then(|st| st.active_layer)
|
||||
}
|
||||
|
||||
fn layers(app: &PhotocraftApp) -> usize {
|
||||
app.session.active().unwrap().doc.layers.len()
|
||||
}
|
||||
|
||||
/// [`new_app`]'s document, whose active layer is a type layer named `TXT` with the family
|
||||
/// `"Inter"`, the style `"Bold"` and `pt` points - the issue's 80 pt text layer.
|
||||
fn txt_active(pt: f32) -> (Box<PhotocraftApp>, LayerId) {
|
||||
let mut app = new_app();
|
||||
let id =
|
||||
app.run("type.create", json!({"text": "TXT", "x": 60, "y": 120, "font": "Inter", "fontStyle": "Bold", "size": pt})).unwrap()["layer"].as_u64().unwrap();
|
||||
let id = LayerId(id);
|
||||
// The tool's own options, deliberately different from the layer's.
|
||||
app.ui.tool_options.type_font = "Tool Font".into();
|
||||
app.ui.tool_options.type_style = "Regular".into();
|
||||
app.ui.tool_options.type_size = 48.0;
|
||||
(app, id)
|
||||
}
|
||||
|
||||
/// Start a mask with a click at `at` and type `s`.
|
||||
fn mask(app: &mut PhotocraftApp, at: (f64, f64), s: &str) {
|
||||
click(app, at.0, at.1, Modifiers::NONE);
|
||||
assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask && ed.created), "a new mask session at {at:?}");
|
||||
super::super::host::type_text(app, s);
|
||||
}
|
||||
|
||||
/// A paragraph mask dragged from `from` to `to` (both ways over 4 screen pixels).
|
||||
fn box_mask(app: &mut PhotocraftApp, from: (f64, f64), to: (f64, f64), s: &str) {
|
||||
tool_event(app, ToolEvent::Down { x: from.0, y: from.1, pressure: 1.0 }, Modifiers::NONE);
|
||||
tool_event(app, ToolEvent::Up { x: to.0, y: to.1 }, Modifiers::NONE);
|
||||
assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask && ed.created), "a new mask box {from:?} to {to:?}");
|
||||
super::super::host::type_text(app, s);
|
||||
}
|
||||
|
||||
/// The size of the committed mask's selection, in whole pixels.
|
||||
fn selection_size(app: &PhotocraftApp) -> (u32, u32) {
|
||||
let r = bounds(&selection(app)).expect("a Type Mask selection");
|
||||
(r.width(), r.height())
|
||||
}
|
||||
|
||||
/// The measured row: an 80 pt text layer active and a click on empty canvas starts the mask at
|
||||
/// 80 pt, not at the tool's 48 pt.
|
||||
#[test]
|
||||
fn a_mask_click_with_an_active_text_layer_starts_at_that_layers_size() {
|
||||
let (mut app, _) = txt_active(80.0);
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
assert_eq!(mask_style(&app).2, 80.0, "the active layer's size, not the tool's 48");
|
||||
}
|
||||
|
||||
/// The measured acceptance "font, size and style as the options bar shows them for that layer".
|
||||
#[test]
|
||||
fn a_mask_click_takes_the_active_layers_font_and_style() {
|
||||
let (mut app, _) = txt_active(80.0);
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
assert_eq!(mask_style(&app), ("Inter".into(), "Bold".into(), 80.0), "the layer's font, style and size");
|
||||
}
|
||||
|
||||
/// A 12 pt layer scaled 200 % shows 24 pt in the options bar and the Character panel, so that is
|
||||
/// the size the mask takes.
|
||||
#[test]
|
||||
fn a_mask_click_takes_the_size_the_options_bar_shows_for_the_layer() {
|
||||
let (mut app, id) = txt_active(12.0);
|
||||
app.run("type.edit", json!({"layer": id.0, "transform": [2.0, 0.0, 0.0, 2.0, 60.0, 120.0]})).unwrap();
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
assert_eq!(mask_style(&app).2, 24.0, "12 pt at 200 % reads 24 pt, as the bar shows it");
|
||||
}
|
||||
|
||||
/// The issue's comparison rows: the mask started by an active 80 pt text layer and the mask the
|
||||
/// same text makes with a pixel layer active and the tool set to what the bar shows for that layer
|
||||
/// (font, style and size) have the same selection size, and both differ from today's 48 pt result
|
||||
/// made at the same point.
|
||||
#[test]
|
||||
fn the_active_layer_mask_selects_the_same_glyphs_as_the_tool_at_the_same_size() {
|
||||
let (mut from_layer, _) = txt_active(80.0);
|
||||
mask(&mut from_layer, (60.0, 300.0), "MASK");
|
||||
commit(&mut from_layer);
|
||||
let from_layer = selection_size(&from_layer);
|
||||
|
||||
let (mut from_tool, _) = txt_active(80.0);
|
||||
from_tool.run("layer.new.layer", json!({})).unwrap();
|
||||
// The bar shows "Inter" "Bold" 80 pt for the layer, so the comparison tool is set to all three.
|
||||
from_tool.ui.tool_options.type_font = "Inter".into();
|
||||
from_tool.ui.tool_options.type_style = "Bold".into();
|
||||
from_tool.ui.tool_options.type_size = 80.0;
|
||||
mask(&mut from_tool, (60.0, 300.0), "MASK");
|
||||
commit(&mut from_tool);
|
||||
let from_tool = selection_size(&from_tool);
|
||||
|
||||
let (mut at_48, _) = txt_active(80.0);
|
||||
at_48.run("layer.new.layer", json!({})).unwrap();
|
||||
mask(&mut at_48, (60.0, 300.0), "MASK");
|
||||
commit(&mut at_48);
|
||||
let at_48 = selection_size(&at_48);
|
||||
|
||||
assert_eq!(from_layer, from_tool, "the same size as the tool set to the layer's size");
|
||||
assert_ne!(from_layer, at_48, "and not today's 48 pt outline {at_48:?}");
|
||||
}
|
||||
|
||||
/// The second measured row: the text layer is not changed and stays active after the commit, and
|
||||
/// the session still leaves only the selection behind.
|
||||
#[test]
|
||||
fn the_text_layer_is_unchanged_and_stays_active_after_the_commit() {
|
||||
let (mut app, id) = txt_active(80.0);
|
||||
let (before_style, before_text, count) = (style(&app, id), current_text(&app, id), layers(&app));
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
commit(&mut app);
|
||||
assert!(app.ui.text_edit.is_none(), "the session ended");
|
||||
assert_eq!(current_text(&app, id), before_text, "\"TXT\" is not changed");
|
||||
assert_eq!(style(&app, id), before_style, "nor its font, style or size");
|
||||
assert_eq!(active_layer(&app), Some(id), "and it is the active layer again after the commit");
|
||||
assert_eq!(layers(&app), count, "no layer is left behind");
|
||||
assert!(selection(&app).is_some(), "the selection is what the commit made");
|
||||
}
|
||||
|
||||
/// The third measured row, and the case with no active layer at all: today's tool options still
|
||||
/// apply. Guard test: passes before and after the change.
|
||||
#[test]
|
||||
fn a_non_text_active_layer_keeps_todays_tool_options() {
|
||||
// A document whose only layer is the Background pixel layer.
|
||||
let mut background = new_app();
|
||||
background.ui.tool_options.type_font = "Tool Font".into();
|
||||
background.ui.tool_options.type_style = "Regular".into();
|
||||
background.ui.tool_options.type_size = 48.0;
|
||||
// The empty pixel layer above "TXT" is active.
|
||||
let (mut pixel, _) = txt_active(80.0);
|
||||
pixel.run("layer.new.layer", json!({})).unwrap();
|
||||
// "TXT" is present but nothing is the active layer.
|
||||
let (mut none_active, _) = txt_active(80.0);
|
||||
none_active.run("select.deselectLayers", json!({})).unwrap();
|
||||
assert_eq!(active_layer(&none_active), None, "no active layer");
|
||||
let cases: Vec<(&str, Box<PhotocraftApp>)> = vec![("Background", background), ("pixel layer", pixel), ("no active layer", none_active)];
|
||||
for (what, mut app) in cases {
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
assert_eq!(mask_style(&app), ("Tool Font".into(), "Regular".into(), 48.0), "{what}: the tool options as today");
|
||||
}
|
||||
}
|
||||
|
||||
/// Not measured and keeping today's behaviour, as a whole: the Vertical Type Mask, and a click
|
||||
/// whose active text layer is vertical; a paragraph drag with a horizontal text layer active.
|
||||
#[test]
|
||||
fn the_vertical_mask_and_a_paragraph_drag_keep_todays_tool_options() {
|
||||
// The Vertical Type Mask with a horizontal text layer active.
|
||||
let (mut vertical, _) = txt_active(80.0);
|
||||
vertical.ui.tool = Tool::VerticalTypeMask;
|
||||
mask(&mut vertical, (600.0, 100.0), "MASK");
|
||||
assert_eq!(mask_style(&vertical), ("Tool Font".into(), "Regular".into(), 48.0), "the vertical mask keeps today's defaults");
|
||||
// The Horizontal Type Mask with a vertical text layer active.
|
||||
let (mut mixed, _) = new_vertical();
|
||||
mixed.ui.tool = Tool::HorizontalTypeMask;
|
||||
mask(&mut mixed, (600.0, 300.0), "MASK");
|
||||
assert_eq!(mask_style(&mixed), ("Tool Font".into(), "Regular".into(), 48.0), "a mixed orientation keeps today's defaults");
|
||||
// A paragraph (box) drag with a horizontal text layer active.
|
||||
let (mut dragged, _) = txt_active(80.0);
|
||||
box_mask(&mut dragged, (60.0, 250.0), (400.0, 340.0), "MASK");
|
||||
assert_eq!(mask_style(&dragged), ("Tool Font".into(), "Regular".into(), 48.0), "a box drag keeps today's defaults");
|
||||
}
|
||||
|
||||
/// [`txt_active`] with a vertical type layer active instead.
|
||||
fn new_vertical() -> (Box<PhotocraftApp>, LayerId) {
|
||||
let mut app = new_app();
|
||||
let id = app
|
||||
.run("type.create", json!({"text": "TXT", "x": 60, "y": 120, "font": "Inter", "fontStyle": "Bold", "size": 80.0, "orientation": "vertical"}))
|
||||
.unwrap()["layer"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
app.ui.tool_options.type_font = "Tool Font".into();
|
||||
app.ui.tool_options.type_style = "Regular".into();
|
||||
app.ui.tool_options.type_size = 48.0;
|
||||
(app, LayerId(id))
|
||||
}
|
||||
|
||||
/// The plain Type tool is not a Type Mask: with the same 80 pt layer active its click still uses
|
||||
/// the tool options (#10824 covers the settings of a type target, not this). Guard test: passes
|
||||
/// before and after the change.
|
||||
#[test]
|
||||
fn the_plain_type_tool_still_starts_at_the_tool_options() {
|
||||
let (mut app, _) = txt_active(80.0);
|
||||
app.ui.tool = Tool::Type;
|
||||
click(&mut app, 60.0, 300.0, Modifiers::NONE);
|
||||
let ed = app.ui.text_edit.clone().expect("a new type session");
|
||||
assert!(!ed.mask, "a type layer, not a mask");
|
||||
assert_eq!(mask_style(&app), ("Tool Font".into(), "Regular".into(), 48.0), "the Type tool's own defaults");
|
||||
}
|
||||
|
||||
/// The zero case: a text layer with no characters still shows its font, style and size in the bar
|
||||
/// (its one run), so the mask starts at them - the takeover only moves create parameters, it
|
||||
/// cannot knock anything out.
|
||||
#[test]
|
||||
fn an_empty_active_text_layer_gives_its_style_too() {
|
||||
let mut app = new_app();
|
||||
app.run("type.create", json!({"text": "", "x": 60, "y": 120, "font": "Inter", "fontStyle": "Bold", "size": 80})).unwrap();
|
||||
app.ui.tool_options.type_font = "Tool Font".into();
|
||||
app.ui.tool_options.type_style = "Regular".into();
|
||||
app.ui.tool_options.type_size = 48.0;
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
assert_eq!(mask_style(&app), ("Inter".into(), "Bold".into(), 80.0), "the empty layer's run, as the bar shows it");
|
||||
}
|
||||
|
||||
/// Not measured: which settings besides the size are taken over. Only the bar's font, style and
|
||||
/// size move to the mask - the active layer's leading, tracking, baseline shift and underline do
|
||||
/// not. Red before the change like the takeover itself: its last line names the three keys that
|
||||
/// move over.
|
||||
#[test]
|
||||
fn a_mask_takes_no_other_character_settings_from_the_layer() {
|
||||
let mut app = new_app();
|
||||
app.run("type.create", json!({"text": "TXT", "x": 60, "y": 120, "font": "Inter", "fontStyle": "Bold", "size": 80, "leading": 100, "tracking": 200, "baselineShift": 5, "underline": true}))
|
||||
.unwrap();
|
||||
app.ui.tool_options.type_font = "Tool Font".into();
|
||||
app.ui.tool_options.type_style = "Regular".into();
|
||||
app.ui.tool_options.type_size = 48.0;
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
let id = LayerId(app.ui.text_edit.as_ref().expect("an open mask session").layer);
|
||||
let c = char_style(&app, id);
|
||||
assert_eq!((c.leading_pt, c.tracking, c.baseline_shift_pt, c.underline), (None, 0.0, 0.0, false), "only font, style and size move over");
|
||||
assert_eq!((c.font_family.as_str(), c.font_style.as_str(), c.size_pt), ("Inter", "Bold", 80.0), "those three do");
|
||||
}
|
||||
|
||||
/// A layer that names no family or style (their placeholder for "the default"): the mask takes its
|
||||
/// size but keeps the tool's own font and style, so no empty name reaches `type.create`.
|
||||
#[test]
|
||||
fn a_layer_that_names_no_family_or_style_gives_only_its_size() {
|
||||
let mut app = new_app();
|
||||
app.run("type.create", json!({"text": "TXT", "x": 60, "y": 120, "font": "", "fontStyle": "", "size": 80})).unwrap();
|
||||
app.ui.tool_options.type_font = "Tool Font".into();
|
||||
app.ui.tool_options.type_style = "Regular".into();
|
||||
app.ui.tool_options.type_size = 48.0;
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
assert_eq!(mask_style(&app), ("Tool Font".into(), "Regular".into(), 80.0), "the size is taken, the empty names are not");
|
||||
}
|
||||
|
||||
/// A document as a corrupt file can leave it: the active layer's runs carry `bad` as their size, a
|
||||
/// value no `type` command writes (the commands keep the size within 0.1-1296 pt).
|
||||
fn corrupt_layer_size(app: &mut PhotocraftApp, id: LayerId, bad: f32) {
|
||||
let st = app.session.active_mut().unwrap();
|
||||
let mut doc = (*st.doc).clone();
|
||||
if let Some(photocraft_doc::LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) {
|
||||
t.size_pt = bad;
|
||||
for r in &mut t.runs {
|
||||
r.style.size_pt = bad;
|
||||
}
|
||||
}
|
||||
*st.doc_mut() = std::sync::Arc::new(doc);
|
||||
st.revision += 1;
|
||||
}
|
||||
|
||||
/// The corrupt-document case: a layer size that is not a finite number. It stays out of the create
|
||||
/// parameters, so the mask still starts - at the tool's own size, with the layer's font and style
|
||||
/// taken as measured. Red without the gate on the finite product: the size becomes JSON `null`,
|
||||
/// `type.create` refuses it, and the click does nothing at all.
|
||||
#[test]
|
||||
fn a_non_finite_layer_size_keeps_the_tool_size() {
|
||||
for bad in [f32::NAN, f32::INFINITY] {
|
||||
let (mut app, id) = txt_active(80.0);
|
||||
corrupt_layer_size(&mut app, id, bad);
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
assert_eq!(mask_style(&app), ("Inter".into(), "Bold".into(), 48.0), "the tool's size, not a null the engine rejects ({bad})");
|
||||
}
|
||||
}
|
||||
|
||||
/// A shown size can also leave the range `type.create` accepts while staying finite: an 800 pt
|
||||
/// layer under a 4x/0.7x transform shows sqrt(2.8) * 800 = 1338 pt, above the engine's 1296 pt
|
||||
/// maximum, and a corrupt document can carry a 0 pt run, below its 0.1 pt minimum. Inheriting a
|
||||
/// refused size fails the whole create, so the click would make no mask at all. The size stays
|
||||
/// out of the parameters there too, and the mask still starts - at the tool's own size, the
|
||||
/// layer's font and style taken. Red before the range gate: no mask session opens.
|
||||
#[test]
|
||||
fn a_shown_layer_size_outside_the_create_range_keeps_the_tool_size() {
|
||||
// A plain document reaches the too-large case: 800 pt is a size the commands write, only the
|
||||
// transform pushes the shown product past the maximum. The transformed glyph band then sits
|
||||
// entirely right of x = 189 and above y = 120, so the same click this file's other cases use
|
||||
// does not land on the layer's glyphs (which would edit the layer, #12075) but starts a
|
||||
// fresh mask.
|
||||
let (mut app, id) = txt_active(800.0);
|
||||
app.run("type.edit", json!({"layer": id.0, "transform": [4.0, 0.0, 0.0, 0.7, 60.0, 120.0]})).unwrap();
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
assert_eq!(mask_style(&app), ("Inter".into(), "Bold".into(), 48.0), "the tool's size, not the 1338 pt the create refuses");
|
||||
// And the corrupt-document case below the accepted minimum.
|
||||
let (mut app, id) = txt_active(80.0);
|
||||
corrupt_layer_size(&mut app, id, 0.0);
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
assert_eq!(mask_style(&app), ("Inter".into(), "Bold".into(), 48.0), "the tool's size, not the 0 pt the create refuses");
|
||||
}
|
||||
|
||||
/// Not measured: whether the tool options themselves change afterwards. Today they do not, and
|
||||
/// they still do not. Guard test: passes before and after the change.
|
||||
#[test]
|
||||
fn taking_the_active_layers_style_leaves_the_tool_options_as_they_are() {
|
||||
let (mut app, _) = txt_active(80.0);
|
||||
mask(&mut app, (60.0, 300.0), "MASK");
|
||||
commit(&mut app);
|
||||
let o = &app.ui.tool_options;
|
||||
assert_eq!((o.type_font.as_str(), o.type_style.as_str(), o.type_size), ("Tool Font", "Regular", 48.0), "the tool options are untouched");
|
||||
}
|
||||
@@ -13,7 +13,7 @@ use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolHostResponse, T
|
||||
use craft::ui::primitives::{Draw, PaintShape, StrokeColor, StrokeWidth};
|
||||
use craft::ui::style::DataColor;
|
||||
|
||||
use super::defaults::default_style_params;
|
||||
use super::defaults::{default_style_params, mask_style_from_active_layer};
|
||||
use super::editing::begin_edit;
|
||||
use super::layout::{hit_layer, offset_at};
|
||||
|
||||
@@ -227,6 +227,18 @@ fn create_text(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) {
|
||||
let placeholder = app.ui.tool != crate::state::Tool::VerticalTypeMask && app.session.prefs().type_.fill_new_type_layers_with_placeholder;
|
||||
let text = if placeholder { PLACEHOLDER } else { "" };
|
||||
let mut p = default_style_params(app);
|
||||
// #12077: the measured case - a click, not a paragraph box, with the Horizontal Type Mask over
|
||||
// a horizontal text layer - starts the mask in that layer's font, style and size, as the
|
||||
// options bar shows them for the layer. The vertical mask and a box drag are not measured in
|
||||
// the issue, so they keep today's tool options.
|
||||
if mask
|
||||
&& !is_box
|
||||
&& app.ui.tool == crate::state::Tool::HorizontalTypeMask
|
||||
&& let Some(style) = mask_style_from_active_layer(app)
|
||||
&& let (Some(params), Some(style)) = (p.as_object_mut(), style.as_object())
|
||||
{
|
||||
params.extend(style.clone());
|
||||
}
|
||||
p["text"] = json!(text);
|
||||
p["orientation"] = json!(if app.ui.tool.is_vertical_type() { "vertical" } else { "horizontal" });
|
||||
if is_box {
|
||||
@@ -362,3 +374,7 @@ mod mask_placeholder_tests;
|
||||
#[cfg(test)]
|
||||
#[path = "mask_click_text_layer_tests.rs"]
|
||||
mod mask_click_text_layer_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mask_active_layer_style_tests.rs"]
|
||||
mod mask_active_layer_style_tests;
|
||||
@@ -31,6 +31,28 @@ fn shape_drag(app: &mut PhotocraftApp, tool: Tool, from: [f64; 2], to: [f64; 2])
|
||||
tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, none);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_drag_with_a_path_operation_records_one_line_tool_step() {
|
||||
let mut app = app();
|
||||
app.ui.tool_options.shape_mode = VectorMode::Shape;
|
||||
shape_drag(&mut app, Tool::Line, [20.0, 20.0], [120.0, 100.0]);
|
||||
let initial = app.run("shape.info", json!({})).unwrap();
|
||||
let steps = app.session.active().unwrap().history.past_len();
|
||||
|
||||
for op in ["combine", "subtract", "intersect"] {
|
||||
app.ui.tool_options.shape_path_op = op.into();
|
||||
shape_drag(&mut app, Tool::Line, [30.0, 30.0], [120.0, 85.0]);
|
||||
let result = app.run("shape.info", json!({})).unwrap();
|
||||
assert_eq!(result["layer"], initial["layer"], "{op}");
|
||||
assert_eq!(result["path"]["subpaths"][1]["op"], op);
|
||||
let history = &app.session.active().unwrap().history;
|
||||
assert_eq!(history.past_len(), steps + 1, "{op}");
|
||||
assert_eq!(history.undo_label(), Some("Line Tool"), "{op}");
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(app.run("shape.info", json!({})).unwrap(), initial, "{op}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain click at each point, with the current tool.
|
||||
fn clicks(app: &mut PhotocraftApp, points: &[[f64; 2]]) {
|
||||
for at in points {
|
||||
|
||||
Reference in new issue
Block a user