mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge remote-tracking branch 'upstream/main' into agent-tasks-extended
This commit is contained in:
commit
e2fa116950
104 files changed
+3381
-461
No files matched your search
@@ -240,7 +240,7 @@ fn convert(a: &Args, _out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
let opts = export_opts(a)?;
|
||||
let o = files::open(Path::new(input)).map_err(|e| e.to_string())?;
|
||||
warn_all(err, &o.warnings);
|
||||
warn_all(err, &missing_font_warnings(photocraft_engine::type_extra_cmds::missing_fonts(&o.document)));
|
||||
warn_all(err, &photocraft_engine::type_extra_cmds::missing_font_warnings(&o.document));
|
||||
let ws = files::save(&o.document, Path::new(output), a.get("--format"), &opts, None).map_err(|e| e.to_string())?;
|
||||
warn_all(err, &ws);
|
||||
Ok(())
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::time::Instant;
|
||||
|
||||
use photocraft_automation::budgets::write_reply;
|
||||
use photocraft_automation::security::{
|
||||
ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream, read_bounded_line,
|
||||
ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream, read_bounded_line, repeat_auth_reply,
|
||||
};
|
||||
use photocraft_ui_egui::ControlRequest;
|
||||
use photocraft_ui_egui::control::{REPLY_DEADLINE, timeout_error};
|
||||
@@ -79,6 +79,12 @@ fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(reply) = repeat_auth_reply(&line) {
|
||||
if write_reply(&mut out, &reply).is_err() || out.flush().is_err() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let reply = match serde_json::from_str::<Value>(&line) {
|
||||
Ok(msg) => {
|
||||
let id = msg.get("id").cloned().unwrap_or(Value::Null);
|
||||
@@ -202,4 +208,44 @@ mod tests {
|
||||
handler.join().unwrap();
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_auth_reports_already_authenticated_without_dispatching() {
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
serve(stream, TOKEN, tx, egui::Context::default());
|
||||
});
|
||||
let handler = std::thread::spawn(move || {
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
assert_eq!(req.method, "test.after", "a repeat auth must not reach the UI dispatcher");
|
||||
req.reply.send(json!({"ok": true, "result": "still serving"})).unwrap();
|
||||
});
|
||||
let mut stream = TcpStream::connect(addr).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
for id in ["auth", "again"] {
|
||||
writeln!(stream, "{}", json!({"id": id, "method": "auth", "params": {"token": TOKEN}})).unwrap();
|
||||
line.clear();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
}
|
||||
let again: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(again["id"], "again");
|
||||
assert_eq!(again["ok"], false);
|
||||
assert_eq!(again["error"], "already authenticated");
|
||||
writeln!(stream, "{}", json!({"id": 9, "method": "test.after"})).unwrap();
|
||||
line.clear();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
let after: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(after["id"], 9);
|
||||
assert_eq!(after["result"], "still serving");
|
||||
drop(reader);
|
||||
drop(stream);
|
||||
handler.join().unwrap();
|
||||
server.join().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -20,9 +20,9 @@ mod recovery_tests;
|
||||
/// Photoshop brushes (.abr), gradients (.grd), swatches (.aco, .ase) and keyboard shortcut sets
|
||||
/// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts.
|
||||
const OPEN_EXTS: &[&str] = &[
|
||||
"pcraft", "pdn", "ora", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm",
|
||||
"ppm", "pam", "pfm", "fits", "fit", "fts", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd",
|
||||
"svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub",
|
||||
"pcraft", "pdn", "ora", "kra", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm",
|
||||
"pgm", "ppm", "pam", "pfm", "pcx", "fits", "fit", "fts", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf",
|
||||
"abr", "grd", "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub",
|
||||
];
|
||||
const SVG_EXTS: &[&str] = &["svg", "svgz"];
|
||||
|
||||
@@ -43,6 +43,7 @@ fn open_filters() -> Vec<(&'static str, Vec<String>)> {
|
||||
("All Formats", open_filter_extensions(OPEN_EXTS)),
|
||||
("PhotoCraft", open_filter_extensions(&["pcraft"])),
|
||||
("OpenRaster", open_filter_extensions(&["ora"])),
|
||||
("Krita", open_filter_extensions(&["kra"])),
|
||||
("SVG", open_filter_extensions(SVG_EXTS)),
|
||||
]
|
||||
}
|
||||
|
||||
+4
-127
@@ -4,7 +4,8 @@
|
||||
//! All work on straight (non-premultiplied) RGBA buffers in 0..=1, row-major `w × h`, so callers
|
||||
//! convert any colour model / bit depth to RGBA first (as `Image › Adjustments` does for the
|
||||
//! per-pixel adjustments). Formulas are documented approximations of Photoshop's behaviour,
|
||||
//! derived from its manual and observation, not from its implementation.
|
||||
//! derived from its manual and observation, not from its implementation; Shadows/Highlights is
|
||||
//! measured on Photoshop (see [`shadows_highlights`]).
|
||||
|
||||
use photocraft_color::convert::{lab_to_srgb, srgb_to_lab};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -17,18 +18,6 @@ fn luma(c: [f32; 3]) -> f32 {
|
||||
0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]
|
||||
}
|
||||
|
||||
fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
|
||||
let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
/// Blurred luminance (Gaussian, `radius` px ≈ 2σ like Photoshop's radius fields).
|
||||
fn blurred_luma(px: &[[f32; 4]], w: usize, h: usize, radius: f32) -> Vec<f32> {
|
||||
let mut l: Vec<f32> = px.iter().map(|p| luma([p[0], p[1], p[2]])).collect();
|
||||
gauss_blur_n(&mut l, w, h, 1, radius.max(0.0) / 2.0);
|
||||
l
|
||||
}
|
||||
|
||||
/// Image › Adjustments › Shadows/Highlights parameters (Photoshop's dialog, percentages as 0..=100).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ShadowsHighlights {
|
||||
@@ -64,95 +53,8 @@ impl Default for ShadowsHighlights {
|
||||
}
|
||||
}
|
||||
|
||||
/// Local tone mapping: a blurred-luminance mask selects shadows (dark neighbourhoods, up to the
|
||||
/// tonal width) and highlights; shadows are lifted and highlights pulled down by a gain that
|
||||
/// preserves hue, then saturation is corrected where the gain moved tones, midtone contrast is
|
||||
/// applied, and the result is stretched by the clip percentages.
|
||||
pub fn shadows_highlights(px: &mut [[f32; 4]], w: usize, h: usize, p: &ShadowsHighlights) {
|
||||
if px.is_empty() {
|
||||
return;
|
||||
}
|
||||
let ls = blurred_luma(px, w, h, p.shadow_radius);
|
||||
let lh = if (p.highlight_radius - p.shadow_radius).abs() < 1e-3 { ls.clone() } else { blurred_luma(px, w, h, p.highlight_radius) };
|
||||
let (sa, ha) = (p.shadow_amount / 100.0, p.highlight_amount / 100.0);
|
||||
let (st, ht) = ((p.shadow_tone / 100.0).max(0.01), (p.highlight_tone / 100.0).max(0.01));
|
||||
let color = p.color / 100.0;
|
||||
let mid = p.midtone / 100.0;
|
||||
par_rows(px, w, 1, |y, pxrow| {
|
||||
for (x, q) in pxrow.iter_mut().enumerate() {
|
||||
let i = y * w + x;
|
||||
if q[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let c = [q[0], q[1], q[2]];
|
||||
// Mask weights: 1 in deep shadows (resp. bright highlights), fading out at the tonal width.
|
||||
let ms = 1.0 - smoothstep(0.0, st, ls[i]);
|
||||
let mh = smoothstep(1.0 - ht, 1.0, lh[i]);
|
||||
let mut out = c;
|
||||
if sa > 0.0 && ms > 0.0 {
|
||||
// Lift: a gamma-like curve on the pixel, stronger for darker neighbourhoods.
|
||||
let g = 1.0 / (1.0 + 2.0 * sa * ms);
|
||||
out = out.map(|v| v.max(0.0).powf(g));
|
||||
}
|
||||
if ha > 0.0 && mh > 0.0 {
|
||||
let g = 1.0 / (1.0 + 2.0 * ha * mh);
|
||||
out = out.map(|v| 1.0 - (1.0 - v.min(1.0)).powf(g));
|
||||
}
|
||||
if mid != 0.0 {
|
||||
let k = 1.0 + mid * (1.0 - ms - mh).clamp(0.0, 1.0);
|
||||
out = out.map(|v| (v - 0.5) * k + 0.5);
|
||||
}
|
||||
let changed = (ms * sa + mh * ha).min(1.0);
|
||||
if color != 0.0 && changed > 0.0 {
|
||||
let l1 = luma(out);
|
||||
let s = 1.0 + color * changed;
|
||||
out = out.map(|v| l1 + (v - l1) * s);
|
||||
}
|
||||
q[0] = out[0].clamp(0.0, 1.0);
|
||||
q[1] = out[1].clamp(0.0, 1.0);
|
||||
q[2] = out[2].clamp(0.0, 1.0);
|
||||
}
|
||||
});
|
||||
clip_stretch(px, p.black_clip, p.white_clip);
|
||||
}
|
||||
|
||||
/// Stretches levels so `black`% of pixels clip to 0 and `white`% to 1 (luminance histogram).
|
||||
fn clip_stretch(px: &mut [[f32; 4]], black: f32, white: f32) {
|
||||
if black <= 0.0 && white <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let mut hist = [0u32; 1024];
|
||||
let mut n = 0u32;
|
||||
for q in px.iter().filter(|q| q[3] > 0.0) {
|
||||
hist[((luma([q[0], q[1], q[2]]).clamp(0.0, 1.0)) * 1023.0).round() as usize] += 1;
|
||||
n += 1;
|
||||
}
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let find = |pct: f32, rev: bool| -> f32 {
|
||||
let target = (pct.clamp(0.0, 50.0) / 100.0 * n as f32) as u32;
|
||||
let mut acc = 0;
|
||||
for k in 0..1024 {
|
||||
let i = if rev { 1023 - k } else { k };
|
||||
acc += hist[i];
|
||||
if acc > target {
|
||||
return i as f32 / 1023.0;
|
||||
}
|
||||
}
|
||||
if rev { 0.0 } else { 1.0 }
|
||||
};
|
||||
let lo = find(black, false);
|
||||
let hi = find(white, true);
|
||||
if hi - lo < 1e-3 {
|
||||
return;
|
||||
}
|
||||
for q in px.iter_mut().filter(|q| q[3] > 0.0) {
|
||||
for v in &mut q[..3] {
|
||||
*v = ((*v - lo) / (hi - lo)).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
mod shadows_highlights;
|
||||
pub use shadows_highlights::shadows_highlights;
|
||||
|
||||
/// Image › Adjustments › Replace Color: Color Range-style selection (fuzziness in 0..=200 levels)
|
||||
/// around `color`, then a hue (±180°), saturation and lightness (±100) shift weighted by it.
|
||||
@@ -378,31 +280,6 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadows_lift_dark_pixels_more_than_bright() {
|
||||
let mut px = ramp(32, 8);
|
||||
let orig = px.clone();
|
||||
shadows_highlights(&mut px, 32, 8, &ShadowsHighlights { black_clip: 0.0, white_clip: 0.0, ..Default::default() });
|
||||
let gain = |i: usize| luma([px[i][0], px[i][1], px[i][2]]) - luma([orig[i][0], orig[i][1], orig[i][2]]);
|
||||
assert!(gain(3) > 0.02, "{}", gain(3));
|
||||
assert!(gain(3) > gain(30), "{} {}", gain(3), gain(30));
|
||||
// Zero amounts and no clipping: identity.
|
||||
let mut px2 = orig.clone();
|
||||
let id = ShadowsHighlights { shadow_amount: 0.0, highlight_amount: 0.0, color: 0.0, black_clip: 0.0, white_clip: 0.0, ..Default::default() };
|
||||
shadows_highlights(&mut px2, 32, 8, &id);
|
||||
assert_eq!(px2, orig);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlights_darken_bright_pixels() {
|
||||
let mut px = ramp(32, 8);
|
||||
let orig = px.clone();
|
||||
let p = ShadowsHighlights { shadow_amount: 0.0, highlight_amount: 80.0, black_clip: 0.0, white_clip: 0.0, ..Default::default() };
|
||||
shadows_highlights(&mut px, 32, 8, &p);
|
||||
assert!(px[30][0] < orig[30][0]);
|
||||
assert!((px[1][0] - orig[1][0]).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_color_only_touches_matching_pixels() {
|
||||
let mut px = vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]];
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
//! Image › Adjustments › Shadows/Highlights, as Photoshop 25.4 does it.
|
||||
//!
|
||||
//! Measured on Photoshop as a black box (synthetic 16-bit images through the adjustment, results
|
||||
//! read back exactly); no Photoshop code was read. The pieces:
|
||||
//!
|
||||
//! - **Neighbourhood brightness.** Per pixel, the mean of its brightest channel and its Rec. 601
|
||||
//! luma. Its neighbourhood value is an edge-aware average: a Gaussian of σ = 1.14 · Radius whose
|
||||
//! weights fall linearly with the difference from the pixel's own (lightly blurred) brightness,
|
||||
//! so pixels across a strong edge count less and halos stay small. It is quantised to 8 bits.
|
||||
//! - **Tonal mask.** Tone sets which neighbourhoods are treated: shadows take the complement of a
|
||||
//! Beta distribution function of the neighbourhood brightness, from Beta(1.95, 23) at Tone 0 to
|
||||
//! 1 − L at Tone 95 and over; highlights take the same of 1 − L.
|
||||
//! - **Curve.** Amount sets a curve that screens the image with itself: 1 − (1 − v)^q, blended
|
||||
//! between q = 1, 2, 4 and 8 by a strength s = 3 at 100, 2 at 50 and 1 near 15. Shadows lift each
|
||||
//! channel by mask × (curve − v); highlights darken with the mirrored curve.
|
||||
//! - **Colour.** Only the luma of that result is kept: the pixel's own colour differences are
|
||||
//! added back, scaled by the Color slider (by exp(h · ΔY / max Y) for positive values, by
|
||||
//! 1 + h · ΔY / max Y for negative ones) and shortened where they would leave the gamut.
|
||||
//! - **Midtone** is a global S-curve on the luma, k · (Y − ½) · (4Y(1 − Y))^p.
|
||||
|
||||
use crate::fxutil::gauss_blur_n;
|
||||
use crate::photo_util::par_rows;
|
||||
|
||||
use super::ShadowsHighlights;
|
||||
|
||||
const W: [f32; 3] = [0.299, 0.587, 0.114];
|
||||
|
||||
fn luma(c: [f32; 3]) -> f32 {
|
||||
W[0] * c[0] + W[1] * c[1] + W[2] * c[2]
|
||||
}
|
||||
|
||||
/// Neighbourhood σ per pixel of Radius.
|
||||
const SPATIAL: f32 = 1.1424;
|
||||
/// σ of the blur of the pixel's own brightness the edge weights compare with.
|
||||
const GUIDE: f32 = 1.3559;
|
||||
/// Brightness difference at which a neighbour's weight reaches zero.
|
||||
const RANGE: f32 = 1.0152;
|
||||
/// Brightness levels of the piecewise-linear edge-aware average.
|
||||
const LEVELS: usize = 17;
|
||||
|
||||
/// Edge-aware neighbourhood brightness of `lum` (`w × h`) for Photoshop's Radius.
|
||||
fn neighbourhood(lum: &[f32], w: usize, h: usize, radius: f32) -> Vec<f32> {
|
||||
let mut guide = lum.to_vec();
|
||||
gauss_blur_n(&mut guide, w, h, 1, GUIDE);
|
||||
let sigma = SPATIAL * radius;
|
||||
if sigma < 0.3 {
|
||||
return guide;
|
||||
}
|
||||
// The average at each of a few brightness levels, interpolated at the pixel's own level
|
||||
// (Durand and Dorsey, "Fast bilateral filtering", 2002). The averages are smooth, so they are
|
||||
// taken on a grid `d` times coarser, with σ ≥ 4 cells there.
|
||||
let d = ((sigma / 4.0).floor() as usize).max(1);
|
||||
let (rw, rh) = (w.div_ceil(d), h.div_ceil(d));
|
||||
let cells = rw * rh;
|
||||
let step = 1.0 / (LEVELS - 1) as f32;
|
||||
let mut avg = vec![0.0f32; LEVELS * cells];
|
||||
let mut buf = vec![0.0f32; 2 * cells];
|
||||
for (k, out) in avg.chunks_exact_mut(cells).enumerate() {
|
||||
let g = k as f32 * step;
|
||||
buf.fill(0.0);
|
||||
for (i, &l) in lum.iter().enumerate() {
|
||||
let wgt = (1.0 - (l - g).abs() / RANGE).max(0.0);
|
||||
let c = 2 * ((i / w) / d * rw + (i % w) / d);
|
||||
buf[c] += wgt * l;
|
||||
buf[c + 1] += wgt;
|
||||
}
|
||||
gauss_blur_n(&mut buf, rw, rh, 2, sigma / d as f32);
|
||||
for (o, b) in out.iter_mut().zip(buf.as_chunks::<2>().0) {
|
||||
*o = if b[1] > 1e-6 { b[0] / b[1] } else { g };
|
||||
}
|
||||
}
|
||||
let mut out = vec![0.0f32; lum.len()];
|
||||
par_rows(&mut out, w, 1, |y, row| {
|
||||
let fy = ((y as f32 + 0.5) / d as f32 - 0.5).clamp(0.0, (rh - 1) as f32);
|
||||
let (y0, ty) = (fy.floor() as usize, fy.fract());
|
||||
let y1 = (y0 + 1).min(rh - 1);
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
let fx = ((x as f32 + 0.5) / d as f32 - 0.5).clamp(0.0, (rw - 1) as f32);
|
||||
let (x0, tx) = (fx.floor() as usize, fx.fract());
|
||||
let x1 = (x0 + 1).min(rw - 1);
|
||||
let at = |k: usize| {
|
||||
let a = &avg[k * cells..(k + 1) * cells];
|
||||
let top = a[y0 * rw + x0] + (a[y0 * rw + x1] - a[y0 * rw + x0]) * tx;
|
||||
let bot = a[y1 * rw + x0] + (a[y1 * rw + x1] - a[y1 * rw + x0]) * tx;
|
||||
top + (bot - top) * ty
|
||||
};
|
||||
let t = (guide[y * w + x].clamp(0.0, 1.0) / step).min((LEVELS - 1) as f32 - 1e-4);
|
||||
let k = t.floor() as usize;
|
||||
let f = t - k as f32;
|
||||
*o = at(k) * (1.0 - f) + at(k + 1) * f;
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Beta(α, β) parameters of the tonal mask for Tone 0, 5, …, 95 (fitted to Photoshop's masks
|
||||
/// within 2/255).
|
||||
const MASK_BETA: [(f32, f32); 20] = [
|
||||
(1.9468, 22.9366),
|
||||
(1.7770, 18.3471),
|
||||
(1.6403, 14.7559),
|
||||
(1.5270, 11.9346),
|
||||
(1.4269, 9.6467),
|
||||
(1.3470, 7.8430),
|
||||
(1.2807, 6.4038),
|
||||
(1.2240, 5.2384),
|
||||
(1.1772, 4.2967),
|
||||
(1.1373, 3.5350),
|
||||
(1.1021, 2.9109),
|
||||
(1.0755, 2.4186),
|
||||
(1.0508, 2.0189),
|
||||
(1.0307, 1.7034),
|
||||
(1.0140, 1.4583),
|
||||
(1.0015, 1.2758),
|
||||
(1.0, 1.1403),
|
||||
(1.0, 1.0510),
|
||||
(1.0, 1.0002),
|
||||
(1.0, 1.0),
|
||||
];
|
||||
|
||||
/// The tonal mask for `tone` (0..=100) at the 256 neighbourhood levels: 1 − I_L(α, β).
|
||||
fn tonal_mask(tone: f32) -> [f32; 256] {
|
||||
let t = (tone.clamp(0.0, 95.0)) / 5.0;
|
||||
let i = (t.floor() as usize).min(MASK_BETA.len() - 2);
|
||||
let f = t - i as f32;
|
||||
let (a0, b0) = MASK_BETA[i];
|
||||
let (a1, b1) = MASK_BETA[i + 1];
|
||||
let (a, b) = ((a0 + (a1 - a0) * f) as f64, (b0 + (b1 - b0) * f) as f64);
|
||||
// Midpoint sums of the Beta density, 16 per level.
|
||||
const SUB: usize = 16;
|
||||
let n = 255 * SUB;
|
||||
let dens = |x: f64| ((a - 1.0) * x.ln() + (b - 1.0) * (1.0 - x).ln()).exp();
|
||||
let mut cum = vec![0.0f64; 256];
|
||||
let mut acc = 0.0;
|
||||
for j in 0..n {
|
||||
acc += dens((j as f64 + 0.5) / n as f64);
|
||||
if (j + 1) % SUB == 0 {
|
||||
cum[(j + 1) / SUB] = acc;
|
||||
}
|
||||
}
|
||||
let total = acc.max(f64::MIN_POSITIVE);
|
||||
std::array::from_fn(|k| (1.0 - cum[k] / total) as f32)
|
||||
}
|
||||
|
||||
/// Curve strength for Amount `a` (0..=100): 0 at 0, 1 near 15, 2 at 50, 3 at 100.
|
||||
fn strength(a: f32) -> f32 {
|
||||
let u = (a.clamp(0.0, 100.0) / 100.0).powf(0.6216);
|
||||
if u <= 0.3 { u / 0.3 } else { (1.0 + 20.0 * u) / 7.0 }
|
||||
}
|
||||
|
||||
/// The full-strength curve of strength `s`: 1 − (1 − v)^q between q = 2^⌊s⌋ and 2^(⌊s⌋+1).
|
||||
fn lift(s: f32, v: f32) -> f32 {
|
||||
let n = (s.floor() as i32).clamp(0, 2);
|
||||
let t = (s - n as f32).clamp(0.0, 1.0);
|
||||
let c = (1.0 - v).clamp(0.0, 1.0);
|
||||
let lo = c.powi(1 << n);
|
||||
let hi = lo * lo;
|
||||
1.0 - ((1.0 - t) * lo + t * hi)
|
||||
}
|
||||
|
||||
/// Linear interpolation in a table of `(x, y)` sorted by `x`.
|
||||
fn interp(table: &[(f32, f32)], x: f32) -> f32 {
|
||||
let Some(&(x0, y0)) = table.first() else { return 0.0 };
|
||||
if x <= x0 {
|
||||
return y0;
|
||||
}
|
||||
for p in table.windows(2) {
|
||||
let ((xa, ya), (xb, yb)) = (p[0], p[1]);
|
||||
if x <= xb {
|
||||
return ya + (yb - ya) * (x - xa) / (xb - xa);
|
||||
}
|
||||
}
|
||||
table.last().map_or(0.0, |p| p.1)
|
||||
}
|
||||
|
||||
/// Color: the h of the colour-difference gain for positive values (exp(h · F))…
|
||||
const COLOR_UP: [(f32, f32); 12] = [
|
||||
(0.0, 0.0),
|
||||
(1.0, 0.1566),
|
||||
(2.0, 0.2271),
|
||||
(5.0, 0.3776),
|
||||
(10.0, 0.5653),
|
||||
(20.0, 0.8669),
|
||||
(30.0, 1.1299),
|
||||
(40.0, 1.3748),
|
||||
(50.0, 1.6093),
|
||||
(60.0, 1.8375),
|
||||
(75.0, 2.1721),
|
||||
(100.0, 2.7193),
|
||||
];
|
||||
/// … and for negative values (1 + h · F), by −Color.
|
||||
const COLOR_DOWN: [(f32, f32); 9] =
|
||||
[(0.0, 0.0), (1.0, -0.0145), (5.0, -0.0709), (10.0, -0.1373), (20.0, -0.2570), (30.0, -0.3612), (50.0, -0.5312), (75.0, -0.6866), (100.0, -0.7968)];
|
||||
|
||||
/// Midtone: (value, k, p) of k · (Y − ½) · (4Y(1 − Y))^p.
|
||||
const MIDTONE: [(f32, f32, f32); 11] = [
|
||||
(-100.0, -0.6955, 2.267),
|
||||
(-75.0, -0.5873, 2.362),
|
||||
(-50.0, -0.4429, 2.492),
|
||||
(-25.0, -0.2514, 2.667),
|
||||
(-10.0, -0.1088, 2.803),
|
||||
(0.0, 0.0, 2.9),
|
||||
(10.0, 0.1206, 3.016),
|
||||
(25.0, 0.3262, 3.216),
|
||||
(50.0, 0.7423, 3.625),
|
||||
(75.0, 1.2635, 4.160),
|
||||
(100.0, 1.9032, 4.850),
|
||||
];
|
||||
|
||||
fn midtone(m: f32, y: f32) -> f32 {
|
||||
if m == 0.0 {
|
||||
return y;
|
||||
}
|
||||
let ks: Vec<(f32, f32)> = MIDTONE.iter().map(|r| (r.0, r.1)).collect();
|
||||
let ps: Vec<(f32, f32)> = MIDTONE.iter().map(|r| (r.0, r.2)).collect();
|
||||
let (k, p) = (interp(&ks, m), interp(&ps, m));
|
||||
(y + k * (y - 0.5) * (4.0 * y * (1.0 - y)).max(0.0).powf(p)).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
fn level(v: f32) -> usize {
|
||||
(v.clamp(0.0, 1.0) * 255.0).round() as usize
|
||||
}
|
||||
|
||||
/// Image › Adjustments › Shadows/Highlights on straight RGBA `w × h`.
|
||||
pub fn shadows_highlights(px: &mut [[f32; 4]], w: usize, h: usize, p: &ShadowsHighlights) {
|
||||
if px.is_empty() || px.len() != w * h {
|
||||
return;
|
||||
}
|
||||
let (sa, ha) = (p.shadow_amount, p.highlight_amount);
|
||||
let lum: Vec<f32> = px.iter().map(|q| (q[0].max(q[1]).max(q[2]) + luma([q[0], q[1], q[2]])) / 2.0).collect();
|
||||
let ls = (sa > 0.0).then(|| neighbourhood(&lum, w, h, p.shadow_radius));
|
||||
let lh = (ha > 0.0).then(|| match &ls {
|
||||
Some(l) if (p.highlight_radius - p.shadow_radius).abs() < 1e-3 => l.clone(),
|
||||
_ => neighbourhood(&lum, w, h, p.highlight_radius),
|
||||
});
|
||||
let (ms, mh) = (tonal_mask(p.shadow_tone), tonal_mask(p.highlight_tone));
|
||||
let (ss, hs) = (strength(sa), strength(ha));
|
||||
// The new luma of every pixel.
|
||||
let mut y2 = vec![0.0f32; px.len()];
|
||||
par_rows(&mut y2, w, 1, |y, row| {
|
||||
for (x, out) in row.iter_mut().enumerate() {
|
||||
let i = y * w + x;
|
||||
let q = px[i];
|
||||
let mut adj = [q[0], q[1], q[2]];
|
||||
if let Some(l) = &ls {
|
||||
let m = ms[level(l[i])];
|
||||
for v in &mut adj {
|
||||
*v += m * (lift(ss, *v) - *v);
|
||||
}
|
||||
}
|
||||
if let Some(l) = &lh {
|
||||
let m = mh[255 - level(l[i])];
|
||||
for (v, &o) in adj.iter_mut().zip(&q[..3]) {
|
||||
*v -= m * (lift(hs, 1.0 - o) - (1.0 - o));
|
||||
}
|
||||
}
|
||||
*out = midtone(p.midtone, luma(adj).clamp(0.0, 1.0));
|
||||
}
|
||||
});
|
||||
clip_levels(&mut y2, px, p.black_clip, p.white_clip);
|
||||
let gain = |f: f32| {
|
||||
if p.color >= 0.0 { (interp(&COLOR_UP, p.color) * f).exp() } else { 1.0 + interp(&COLOR_DOWN, -p.color) * f }
|
||||
};
|
||||
par_rows(px, w, 1, |y, row| {
|
||||
for (x, q) in row.iter_mut().enumerate() {
|
||||
if q[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let y1 = luma([q[0], q[1], q[2]]);
|
||||
let yn = y2[y * w + x];
|
||||
let f = (yn - y1).abs() / yn.max(y1).max(1e-6);
|
||||
let g = gain(f);
|
||||
let d = [(q[0] - y1) * g, (q[1] - y1) * g, (q[2] - y1) * g];
|
||||
// Shorten the colour difference where it would leave 0..=1.
|
||||
let mut k = 1.0f32;
|
||||
for v in d {
|
||||
if v > 1e-9 {
|
||||
k = k.min((1.0 - yn) / v);
|
||||
} else if v < -1e-9 {
|
||||
k = k.min(yn / -v);
|
||||
}
|
||||
}
|
||||
let k = k.clamp(0.0, 1.0);
|
||||
for c in 0..3 {
|
||||
q[c] = (yn + k * d[c]).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Black and White Clip: stretches the new luma so `black`% of pixels reach 0 and `white`% reach 1.
|
||||
fn clip_levels(y2: &mut [f32], px: &[[f32; 4]], black: f32, white: f32) {
|
||||
if black <= 0.0 && white <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let mut hist = vec![0u32; 4096];
|
||||
let mut n = 0u32;
|
||||
for (&y, q) in y2.iter().zip(px) {
|
||||
if q[3] > 0.0 {
|
||||
hist[(y.clamp(0.0, 1.0) * 4095.0).round() as usize] += 1;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let find = |pct: f32, rev: bool| -> f32 {
|
||||
let target = (pct.clamp(0.0, 50.0) / 100.0 * n as f32) as u32;
|
||||
let mut acc = 0;
|
||||
for k in 0..4096 {
|
||||
let i = if rev { 4095 - k } else { k };
|
||||
acc += hist[i];
|
||||
if acc > target {
|
||||
return i as f32 / 4095.0;
|
||||
}
|
||||
}
|
||||
if rev { 0.0 } else { 1.0 }
|
||||
};
|
||||
let (lo, hi) = (if black > 0.0 { find(black, false) } else { 0.0 }, if white > 0.0 { find(white, true) } else { 1.0 });
|
||||
if hi - lo < 1e-3 {
|
||||
return;
|
||||
}
|
||||
for y in y2.iter_mut() {
|
||||
*y = ((*y - lo) / (hi - lo)).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A flat `w × h` grey or colour image with one different pixel in the middle; returns that
|
||||
/// pixel after Shadows/Highlights.
|
||||
fn probe(bg: [f32; 3], px: [f32; 3], p: &ShadowsHighlights) -> [f32; 3] {
|
||||
let (w, h) = (121, 121);
|
||||
let mut img = vec![[bg[0], bg[1], bg[2], 1.0]; w * h];
|
||||
img[60 * w + 60] = [px[0], px[1], px[2], 1.0];
|
||||
shadows_highlights(&mut img, w, h, p);
|
||||
let q = img[60 * w + 60];
|
||||
[q[0], q[1], q[2]]
|
||||
}
|
||||
|
||||
fn levels(v: [i32; 3]) -> [f32; 3] {
|
||||
v.map(|c| c as f32 / 32768.0)
|
||||
}
|
||||
|
||||
fn off(a: [f32; 3], b: [f32; 3]) -> f32 {
|
||||
a.iter().zip(b).map(|(x, y)| (x - y).abs() * 255.0).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
/// Photoshop 25.4's results (16-bit levels of 32768) for grey pixels lifted by the default
|
||||
/// Shadows (35 %, Tone 50 %, Radius 30 px; Color 0), in black surroundings and in grey 0.5.
|
||||
#[test]
|
||||
fn grey_matches_photoshop() {
|
||||
let p = ShadowsHighlights { color: 0.0, black_clip: 0.0, white_clip: 0.0, ..Default::default() };
|
||||
for (bg, want) in [(0.0, [11389, 19422, 28451, 31931]), (0.5, [5211, 9909, 18229, 25700])] {
|
||||
for (v, w) in [0.125f32, 0.25, 0.5, 0.749969].into_iter().zip(want) {
|
||||
let got = probe([bg; 3], [v; 3], &p);
|
||||
assert!(off(got, levels([w; 3])) < 2.0, "bg {bg} v {v}: {} vs {}", got[0] * 32768.0, w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Colour pixels keep their colour differences, scaled by Color (+20 here; Amount 35 %,
|
||||
/// Radius 10 px), in black, 0.15 and 0.3 grey surroundings: Photoshop's results.
|
||||
#[test]
|
||||
fn colour_matches_photoshop() {
|
||||
let p = ShadowsHighlights { shadow_radius: 10.0, black_clip: 0.0, white_clip: 0.0, ..Default::default() };
|
||||
for (bg, px, want) in [
|
||||
(0.0, [3277, 1638, 0], [8235, 5202, 2170]),
|
||||
(0.0, [8192, 6554, 4915], [19350, 16514, 13676]),
|
||||
(4915.0 / 32768.0, [4915, 3277, 1638], [10124, 7424, 4723]),
|
||||
(9830.0 / 32768.0, [11469, 9830, 8192], [16540, 14376, 12214]),
|
||||
] {
|
||||
let got = probe([bg; 3], levels(px), &p);
|
||||
assert!(off(got, levels(want)) < 2.0, "{px:?} on {bg}: {:?} vs {want:?}", got.map(|c| (c * 32768.0).round()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Across a strong edge the neighbourhood barely leaks (Amount 100 %, Tone 100 %, Radius
|
||||
/// 10 px; 0.1 | 0.9): Photoshop's results 8, 2 and 1 pixels either side.
|
||||
#[test]
|
||||
fn edge_matches_photoshop() {
|
||||
let (w, h) = (200, 24);
|
||||
let (a, b) = (3277.0 / 32768.0, 29491.0 / 32768.0);
|
||||
let mut img: Vec<[f32; 4]> = (0..w * h).map(|i| if i % w < 100 { [a, a, a, 1.0] } else { [b, b, b, 1.0] }).collect();
|
||||
let p = ShadowsHighlights {
|
||||
shadow_amount: 100.0,
|
||||
shadow_tone: 100.0,
|
||||
shadow_radius: 10.0,
|
||||
color: 0.0,
|
||||
black_clip: 0.0,
|
||||
white_clip: 0.0,
|
||||
..Default::default()
|
||||
};
|
||||
shadows_highlights(&mut img, w, h, &p);
|
||||
let row = &img[12 * w..13 * w];
|
||||
for (x, want) in [(92, 16370), (98, 14439), (99, 12146), (100, 30891), (101, 30403), (102, 30146), (108, 29979)] {
|
||||
let got = row[x][0] * 32768.0;
|
||||
assert!((got - want as f32).abs() / 32768.0 * 255.0 < 6.0, "x {x}: {got} vs {want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strength_and_curve_follow_photoshop() {
|
||||
assert!((strength(50.0) - 2.0).abs() < 2e-3 && (strength(100.0) - 3.0).abs() < 1e-4);
|
||||
assert!((strength(15.0) - 1.02).abs() < 0.01 && (strength(1.0) - 0.19).abs() < 0.01);
|
||||
// Amount 50 is the image screened with itself twice: 1 − (1 − v)^4.
|
||||
for v in [0.1f32, 0.3, 0.6] {
|
||||
assert!((lift(2.0, v) - (1.0 - (1.0 - v).powi(4))).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tonal_mask_spans_photoshop_tones() {
|
||||
let m95 = tonal_mask(95.0);
|
||||
assert!((m95[128] - (1.0 - 128.0 / 255.0)).abs() < 1e-3, "{}", m95[128]);
|
||||
assert_eq!(tonal_mask(100.0), m95);
|
||||
// Tone 0 still reaches about 7 % into the levels (Photoshop: half at level 18).
|
||||
let m0 = tonal_mask(0.0);
|
||||
assert!(m0[0] > 0.999 && (m0[18] - 0.5).abs() < 0.03 && m0[60] < 0.02, "{} {}", m0[18], m0[60]);
|
||||
}
|
||||
}
|
||||
@@ -96,13 +96,15 @@ impl Headless {
|
||||
st.source_read_only = o.source_read_only;
|
||||
}
|
||||
let d = &self.session.documents()[index];
|
||||
let mut warnings = o.warnings;
|
||||
warnings.extend(photocraft_engine::type_extra_cmds::missing_font_warnings(&d.doc));
|
||||
Ok(json!({
|
||||
"index": index,
|
||||
"name": d.doc.name,
|
||||
"width": d.doc.size.width,
|
||||
"height": d.doc.size.height,
|
||||
"layers": d.doc.layer_count(),
|
||||
"warnings": o.warnings,
|
||||
"warnings": warnings,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -240,7 +242,7 @@ impl Headless {
|
||||
}
|
||||
};
|
||||
let target_text = target.to_str().ok_or_else(|| AutomationError::BadRequest("automation paths must be valid UTF-8".into()))?;
|
||||
let warnings = match &self.filesystem {
|
||||
let mut warnings = match &self.filesystem {
|
||||
Filesystem::Denied => return Err(AutomationError::BadRequest("automation filesystem access is not granted: write authority is absent".into())),
|
||||
Filesystem::TrustedLocal => {
|
||||
let writer = self.writers.entry(doc.id.0).or_default();
|
||||
@@ -252,6 +254,7 @@ impl Headless {
|
||||
warnings
|
||||
}
|
||||
};
|
||||
warnings.extend(photocraft_engine::type_extra_cmds::missing_font_warnings(&doc));
|
||||
// A layered document save (PSD, PSB, OpenRaster or .pcraft) is a full write, not a flattened copy:
|
||||
// record the current revision as saved so the session stops reporting `dirty`, and make
|
||||
// the file the document's path. A flat export (PNG, JPEG, …) is a copy and leaves both
|
||||
@@ -317,21 +320,7 @@ impl Headless {
|
||||
}
|
||||
|
||||
pub fn command_list(&self) -> Value {
|
||||
Value::Array(
|
||||
command_specs()
|
||||
.iter()
|
||||
.map(|c| {
|
||||
json!({
|
||||
"id": c.id,
|
||||
"label": c.label,
|
||||
"menu": c.menu,
|
||||
"shortcut": c.shortcut,
|
||||
"params": c.params,
|
||||
"enabled": self.session.is_enabled(c.id),
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
Value::Array(command_specs().iter().map(|c| photocraft_engine::commands::list_entry(&self.session, c, self.session.disabled_reason(c.id))).collect())
|
||||
}
|
||||
|
||||
pub fn command_run(&mut self, id: &str, params: Value) -> Result<Value, AutomationError> {
|
||||
|
||||
@@ -30,7 +30,7 @@ use serde_json::{Value, json};
|
||||
use crate::budgets::{BatchReplyBudget, write_reply};
|
||||
use crate::security::{
|
||||
ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream, discard_rest_of_line,
|
||||
read_bounded_line,
|
||||
read_bounded_line, repeat_auth_reply,
|
||||
};
|
||||
use crate::{AutomationError, Headless};
|
||||
|
||||
@@ -288,7 +288,7 @@ fn serve_tcp_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token:
|
||||
LineRead::Line => {}
|
||||
}
|
||||
let reply = if authenticated {
|
||||
respond(h, &line)
|
||||
repeat_auth_reply(&line).unwrap_or_else(|| respond(h, &line))
|
||||
} else {
|
||||
let (reply, ok) = authentication_reply(&line, token);
|
||||
authenticated = ok;
|
||||
@@ -780,6 +780,36 @@ mod tests {
|
||||
assert!(v["result"].as_array().unwrap().iter().any(|m| m == "batch"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_repeat_auth_reports_already_authenticated_and_keeps_serving() {
|
||||
use std::io::{BufReader, Write as _};
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
let h = Arc::new(Mutex::new(Headless::new()));
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap());
|
||||
});
|
||||
let addr = rx.recv().unwrap();
|
||||
let mut s = std::net::TcpStream::connect(addr).unwrap();
|
||||
let mut reader = BufReader::new(s.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
for id in ["auth", "again"] {
|
||||
writeln!(s, r#"{{"id":"{id}","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap();
|
||||
line.clear();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
}
|
||||
let again: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(again["id"], "again");
|
||||
assert_eq!(again["ok"], false);
|
||||
assert_eq!(again["error"], "already authenticated");
|
||||
writeln!(s, r#"{{"id":"m","method":"methods"}}"#).unwrap();
|
||||
line.clear();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(v["id"], "m");
|
||||
assert_eq!(v["ok"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_rejects_requests_before_authentication() {
|
||||
use std::io::{BufReader, Write as _};
|
||||
|
||||
@@ -118,6 +118,18 @@ pub fn authentication_reply(line: &str, expected_token: &str) -> (Value, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer a repeat `auth` frame on an already authenticated connection. Returns `None` for any
|
||||
/// other frame, which the caller dispatches as usual.
|
||||
/// Without this, a second `auth` fell through to the method dispatcher as an unknown method.
|
||||
pub fn repeat_auth_reply(line: &str) -> Option<Value> {
|
||||
let req: Value = serde_json::from_str(line).ok()?;
|
||||
if req.get("method").and_then(Value::as_str) != Some(AUTH_METHOD) {
|
||||
return None;
|
||||
}
|
||||
let id = req.get("id").cloned().unwrap_or(Value::Null);
|
||||
Some(json!({"id": id, "ok": false, "error": "already authenticated"}))
|
||||
}
|
||||
|
||||
fn read_token_file(path: &Path) -> Result<String, AutomationError> {
|
||||
let token = std::fs::read_to_string(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
|
||||
let token = token.trim().to_owned();
|
||||
@@ -294,6 +306,17 @@ mod tests {
|
||||
assert_eq!(reply["result"]["authenticated"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_auth_on_an_authenticated_connection_says_so() {
|
||||
let line = json!({"id": 3, "method": AUTH_METHOD, "params": {"token": "anything"}}).to_string();
|
||||
let reply = repeat_auth_reply(&line).unwrap();
|
||||
assert_eq!(reply["id"], 3);
|
||||
assert_eq!(reply["ok"], false);
|
||||
assert_eq!(reply["error"], "already authenticated");
|
||||
assert!(repeat_auth_reply(r#"{"id":4,"method":"methods"}"#).is_none());
|
||||
assert!(repeat_auth_reply("{not json").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_file_round_trips_between_server_and_client() {
|
||||
let path = std::env::temp_dir().join(format!("photocraft-control-token-{}-{}.txt", std::process::id(), generate_token().unwrap()));
|
||||
|
||||
@@ -792,7 +792,9 @@ impl PhotocraftMcp {
|
||||
}
|
||||
}
|
||||
|
||||
#[tool(description = "List engine commands: id, label, menu path, shortcut, parameter doc, enabled now.")]
|
||||
#[tool(description = "List engine commands: id, label, menu path, shortcut, parameter doc, enabled now. \
|
||||
`disabledReason` says why a command is off (null when enabled); `needsDocument` is true when it is off because no \
|
||||
document is open: create or open one first (doc_new, doc_open).")]
|
||||
async fn command_list(&self, Parameters(p): Parameters<ListParams>) -> Result<CallToolResult, McpError> {
|
||||
let all = if let Some(r) = self.headless_op(|h| Ok(h.command_list())).await {
|
||||
r
|
||||
|
||||
@@ -170,6 +170,12 @@ async fn command_list_filters() {
|
||||
let enabled = json_of(&call(&client, "command_list", json!({"enabled_only": true})).await);
|
||||
assert!(enabled.as_array().unwrap().iter().any(|c| c["id"] == "file.new"));
|
||||
assert!(!enabled.as_array().unwrap().iter().any(|c| c["id"] == "layer.new.layer"), "needs a document");
|
||||
// The full list says why a document command is off with no document open (#3664).
|
||||
let layer = all.as_array().unwrap().iter().find(|c| c["id"] == "layer.new.layer").unwrap();
|
||||
assert_eq!((layer["enabled"].clone(), layer["needsDocument"].clone()), (json!(false), json!(true)), "{layer}");
|
||||
assert!(layer["disabledReason"].as_str().is_some_and(|r| r.starts_with("no document")), "{layer}");
|
||||
let new = all.as_array().unwrap().iter().find(|c| c["id"] == "file.new").unwrap();
|
||||
assert_eq!((new["needsDocument"].clone(), new["disabledReason"].clone()), (json!(false), Value::Null), "{new}");
|
||||
client.cancel().await.unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! #3391: `doc.save`, `doc.open`, and type commands emit warnings when text uses a missing font.
|
||||
|
||||
use photocraft_automation::Headless;
|
||||
use serde_json::json;
|
||||
|
||||
fn tmp_dir() -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"pc-font-warn-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_font_warnings_emitted_in_headless_and_type_commands() {
|
||||
let dir = tmp_dir();
|
||||
let psd_path = dir.join("card.psd");
|
||||
let png_path = dir.join("card.png");
|
||||
|
||||
let mut h = Headless::trusted_local();
|
||||
h.handle("doc.new", json!({"width": 600, "height": 300, "background": "white"})).unwrap();
|
||||
|
||||
// 1. type.create with missing font
|
||||
let created = h
|
||||
.handle("engine.execute", json!({"command": "type.create", "params": {"x": 30, "y": 100, "text": "Headline", "font": "NoSuchFamily123", "size": 40}}))
|
||||
.unwrap();
|
||||
assert_eq!(created["warnings"], json!(["font 'NoSuchFamily123' is not installed; text may render using a fallback face"]));
|
||||
|
||||
// 2. doc.save card.psd
|
||||
let saved_psd = h.handle("doc.save", json!({"path": psd_path.to_str().unwrap()})).unwrap();
|
||||
let warnings = saved_psd["warnings"].as_array().expect("warnings array in doc.save");
|
||||
assert!(
|
||||
warnings.iter().any(|w| w == "font 'NoSuchFamily123' is not installed; text may render using a fallback face"),
|
||||
"doc.save PSD warning: {saved_psd}"
|
||||
);
|
||||
|
||||
// 3. doc.save card.png
|
||||
let saved_png = h.handle("doc.save", json!({"path": png_path.to_str().unwrap()})).unwrap();
|
||||
let warnings = saved_png["warnings"].as_array().expect("warnings array in doc.save");
|
||||
assert!(
|
||||
warnings.iter().any(|w| w == "font 'NoSuchFamily123' is not installed; text may render using a fallback face"),
|
||||
"doc.save PNG warning: {saved_png}"
|
||||
);
|
||||
|
||||
// 4. doc.close then doc.open
|
||||
h.handle("doc.close", json!({})).unwrap();
|
||||
let opened = h.handle("doc.open", json!({"path": psd_path.to_str().unwrap()})).unwrap();
|
||||
let warnings = opened["warnings"].as_array().expect("warnings array in doc.open");
|
||||
assert!(
|
||||
warnings.iter().any(|w| w.as_str().unwrap_or("").contains("is not installed; text may render using a fallback face")),
|
||||
"doc.open warning: {opened}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ pub(crate) mod fits;
|
||||
pub(crate) mod gif_frames;
|
||||
pub(crate) mod heif;
|
||||
pub(crate) mod jpeg;
|
||||
pub(crate) mod pcx;
|
||||
pub(crate) mod png;
|
||||
pub(crate) mod pnm;
|
||||
pub(crate) mod tiff;
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! ZSoft PCX (Paintbrush) reader: strictly bounded scanline RLE, 16/256-colour
|
||||
//! palettes and 8-bit three-plane RGB. Read-only: modern saves should use PNG.
|
||||
|
||||
use crate::SampleType;
|
||||
use crate::error::CodecError;
|
||||
use crate::format::Format;
|
||||
use crate::image::{ChannelLayout, Image};
|
||||
use crate::options::Limits;
|
||||
|
||||
const HEADER: usize = 128;
|
||||
|
||||
fn bad(reason: impl std::fmt::Display) -> CodecError {
|
||||
CodecError::malformed(Format::Pcx, reason)
|
||||
}
|
||||
fn le16(b: &[u8], i: usize) -> u16 {
|
||||
u16::from_le_bytes([b[i], b[i + 1]])
|
||||
}
|
||||
|
||||
/// PCX lacks a strong magic number. Require plausible complete header fields before
|
||||
/// identifying it, rather than classifying every file starting with 0x0a as PCX.
|
||||
pub(crate) fn looks_like_pcx(b: &[u8]) -> bool {
|
||||
if b.len() < HEADER || b[0] != 0x0a || !matches!(b[1], 0 | 2 | 3 | 5) || b[2] != 1 {
|
||||
return false;
|
||||
}
|
||||
let bits = b[3];
|
||||
let planes = b[65];
|
||||
let stride = u32::from(le16(b, 66));
|
||||
let (x0, y0, x1, y1) = (le16(b, 4), le16(b, 6), le16(b, 8), le16(b, 10));
|
||||
if x1 < x0 || y1 < y0 || !matches!(bits, 1 | 2 | 4 | 8) || !(1..=4).contains(&planes) {
|
||||
return false;
|
||||
}
|
||||
let width = u32::from(x1 - x0) + 1;
|
||||
let min_stride = (width * u32::from(bits)).div_ceil(8);
|
||||
stride >= min_stride && stride > 0 && (bits != 8 || matches!(planes, 1 | 3)) && (bits == 8 || u32::from(bits) * u32::from(planes) <= 4)
|
||||
}
|
||||
|
||||
/// Read one compressed plane's row. RLE packets never cross a scanline.
|
||||
fn read_row(b: &[u8], pos: &mut usize, out: &mut [u8]) -> Result<(), CodecError> {
|
||||
let mut n = 0;
|
||||
while n < out.len() {
|
||||
let code = *b.get(*pos).ok_or_else(|| bad("truncated pixel RLE"))?;
|
||||
*pos += 1;
|
||||
let (count, value) = if code >= 0xc0 {
|
||||
let count = usize::from(code & 0x3f);
|
||||
let value = *b.get(*pos).ok_or_else(|| bad("truncated RLE packet"))?;
|
||||
*pos += 1;
|
||||
(count, value)
|
||||
} else {
|
||||
(1, code)
|
||||
};
|
||||
if count == 0 || count > out.len() - n {
|
||||
return Err(bad("RLE packet crosses a scanline or has zero length"));
|
||||
}
|
||||
out[n..n + count].fill(value);
|
||||
n += count;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result<Image, CodecError> {
|
||||
if !looks_like_pcx(b) {
|
||||
return Err(bad("invalid PCX header or unsupported pixel layout"));
|
||||
}
|
||||
let (w, h) = (u32::from(le16(b, 8) - le16(b, 4)) + 1, u32::from(le16(b, 10) - le16(b, 6)) + 1);
|
||||
limits.check(w, h, ChannelLayout::Rgb, SampleType::U8)?;
|
||||
let (bits, planes, stride) = (usize::from(b[3]), usize::from(b[65]), usize::from(le16(b, 66)));
|
||||
let row_len = stride.checked_mul(planes).ok_or_else(|| bad("row size overflow"))?;
|
||||
let total = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(3)).ok_or_else(|| bad("pixel size overflow"))?;
|
||||
// The last 769 bytes are the optional VGA palette for 8-bit indexed images.
|
||||
let vga = bits == 8 && planes == 1 && b.len() >= HEADER + 769 && b[b.len() - 769] == 0x0c;
|
||||
if bits == 8 && planes == 1 && !vga && le16(b, 68) != 2 {
|
||||
return Err(bad("8-bit indexed PCX has no 256-colour palette"));
|
||||
}
|
||||
let image_end = if vga { b.len() - 769 } else { b.len() };
|
||||
let mut row = vec![0u8; row_len];
|
||||
let mut pixels = vec![0u8; total];
|
||||
let mut p = HEADER;
|
||||
let width = w as usize;
|
||||
for y in 0..h as usize {
|
||||
for plane in row.chunks_mut(stride) {
|
||||
read_row(&b[..image_end], &mut p, plane)?;
|
||||
}
|
||||
for x in 0..width {
|
||||
let rgb = if bits == 8 && planes == 3 {
|
||||
[row[x], row[stride + x], row[2 * stride + x]]
|
||||
} else {
|
||||
let index = if bits == 8 {
|
||||
usize::from(row[x])
|
||||
} else {
|
||||
let bit = x * bits;
|
||||
let shift = 8 - bits - (bit % 8);
|
||||
let mask = (1usize << bits) - 1;
|
||||
(0..planes).fold(0usize, |v, plane| {
|
||||
let sample = (usize::from(row[plane * stride + bit / 8]) >> shift) & mask;
|
||||
v | sample << (plane * bits)
|
||||
})
|
||||
};
|
||||
if vga {
|
||||
let o = image_end + 1 + index * 3;
|
||||
[b[o], b[o + 1], b[o + 2]]
|
||||
} else if bits == 8 {
|
||||
let g = index as u8;
|
||||
[g, g, g] // palette-info 2: gray scale
|
||||
} else {
|
||||
let o = 16 + index * 3;
|
||||
[b[o], b[o + 1], b[o + 2]]
|
||||
}
|
||||
};
|
||||
pixels[(y * width + x) * 3..(y * width + x + 1) * 3].copy_from_slice(&rgb);
|
||||
}
|
||||
}
|
||||
let mut image = Image::from_u8(w, h, ChannelLayout::Rgb, pixels)?;
|
||||
let (xdpi, ydpi) = (le16(b, 12), le16(b, 14));
|
||||
if xdpi > 0 && ydpi > 0 {
|
||||
image.meta.dpi = Some((f32::from(xdpi), f32::from(ydpi)));
|
||||
}
|
||||
Ok(image)
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use crate::Format;
|
||||
use crate::error::CodecError;
|
||||
use crate::fidelity::Plan;
|
||||
use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType};
|
||||
use crate::options::{EncodeOptions, Limits, PngCompression};
|
||||
use crate::options::{EncodeOptions, Limits, PngCompression, alloc_zeroed};
|
||||
|
||||
const F: Format = Format::Png;
|
||||
pub(crate) const XMP_KEYWORD: &str = "XML:com.adobe.xmp";
|
||||
@@ -29,6 +29,10 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
|
||||
let (w, h) = info.size();
|
||||
// Worst case output: 4 channels x 16 bit.
|
||||
limits.check_bytes(w, h, 8)?;
|
||||
// zlib never beats 1032:1; refuse a file too small for the declared image before the
|
||||
// output buffer exists. Measured on the stored samples (before palette/bit expansion).
|
||||
let stored = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(info.bits_per_pixel() as u64).div_ceil(8);
|
||||
Limits::check_plausible(stored, bytes.len(), 1100)?;
|
||||
}
|
||||
let mut reader = decoder.read_info().map_err(map_png_err)?;
|
||||
// APNG: the IDAT image is the first frame, or an extra default image when no fcTL precedes it.
|
||||
@@ -47,7 +51,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
|
||||
d => return Err(err(format!("unexpected output bit depth {d:?}"))),
|
||||
};
|
||||
let size = reader.output_buffer_size().ok_or_else(|| err("image too large"))?;
|
||||
let mut buf = vec![0u8; size];
|
||||
let mut buf = alloc_zeroed::<u8>(size)?;
|
||||
let out = reader.next_frame(&mut buf).map_err(map_png_err)?;
|
||||
buf.truncate(out.buffer_size());
|
||||
// Collect ancillary chunks after IDAT. Tolerate malformed tails once pixels
|
||||
|
||||
@@ -145,6 +145,14 @@ impl<'a> File<'a> {
|
||||
Some(if self.le { u64::from_le_bytes(s) } else { u64::from_be_bytes(s) })
|
||||
}
|
||||
|
||||
/// The declared entry count of the directory at `at`, before its table is parsed.
|
||||
pub fn entry_count(&self, at: u64) -> Option<u64> {
|
||||
if at < self.header_len() {
|
||||
return None;
|
||||
}
|
||||
if self.big { self.u64_at(at) } else { self.u16_at(at).map(u64::from) }
|
||||
}
|
||||
|
||||
/// The directory at `at`: its whole table, up to and including the next-IFD pointer, must
|
||||
/// be inside the file and after the header.
|
||||
pub fn ifd(&self, at: u64) -> Option<Ifd> {
|
||||
@@ -355,6 +363,10 @@ struct Walk<'a, 'f> {
|
||||
seen: HashSet<u64>,
|
||||
pages: Vec<TiffPage>,
|
||||
complete: bool,
|
||||
/// Directory entries that may still be parsed. Real directory tables are disjoint, so their
|
||||
/// total size is bounded by the file; overlapping tables (a hostile file) would otherwise
|
||||
/// make every one of thousands of directories cost a full 65,535-entry parse.
|
||||
entry_budget: u64,
|
||||
}
|
||||
|
||||
impl Walk<'_, '_> {
|
||||
@@ -366,6 +378,15 @@ impl Walk<'_, '_> {
|
||||
self.complete = false;
|
||||
return;
|
||||
}
|
||||
let Some(n) = self.f.entry_count(at) else {
|
||||
self.complete = false;
|
||||
return;
|
||||
};
|
||||
if n > self.entry_budget {
|
||||
self.complete = false;
|
||||
return;
|
||||
}
|
||||
self.entry_budget -= n;
|
||||
let Some(ifd) = self.f.ifd(at) else {
|
||||
self.complete = false;
|
||||
return;
|
||||
@@ -391,10 +412,37 @@ pub fn tiff_info(bytes: &[u8]) -> Result<TiffInfo, CodecError> {
|
||||
}
|
||||
|
||||
pub(crate) fn info_of(f: &File<'_>) -> Result<TiffInfo, CodecError> {
|
||||
let mut w = Walk { f, seen: HashSet::new(), pages: Vec::new(), complete: true };
|
||||
let mut w = Walk { f, seen: HashSet::new(), pages: Vec::new(), complete: true, entry_budget: (f.b.len() as u64) / 12 + 64 };
|
||||
w.chain(f.first_ifd, None, 0);
|
||||
if w.pages.is_empty() {
|
||||
return Err(CodecError::malformed(Format::Tiff, "the first image directory is missing or cut off"));
|
||||
}
|
||||
Ok(TiffInfo { big_tiff: f.big, little_endian: f.le, pages: w.pages, complete: w.complete })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 10,000 directories 4 bytes apart, each declaring 65,535 overlapping entries: the walk must
|
||||
/// stop after the file-size entry budget instead of parsing ~6.5e8 entries.
|
||||
#[test]
|
||||
fn overlapping_directory_tables_exhaust_the_entry_budget() {
|
||||
let first = 8usize;
|
||||
let table = 2 + 65_535 * 12 + 4;
|
||||
let mut b = vec![0u8; first + table + 4 * 10_000];
|
||||
b[..8].copy_from_slice(&[b'I', b'I', 42, 0, first as u8, 0, 0, 0]);
|
||||
for i in 0..10_000usize {
|
||||
let at = first + 4 * i;
|
||||
b[at..at + 2].copy_from_slice(&u16::MAX.to_le_bytes());
|
||||
let next_cell = at + 2 + 65_535 * 12;
|
||||
let next = (first + 4 * (i + 1)) as u32;
|
||||
if let Some(cell) = b.get_mut(next_cell..next_cell + 4) {
|
||||
cell.copy_from_slice(&next.to_le_bytes());
|
||||
}
|
||||
}
|
||||
let info = tiff_info(&b).expect("the first directory is readable");
|
||||
assert!(!info.complete);
|
||||
assert!(info.pages.len() < 200, "{} directories parsed", info.pages.len());
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use crate::Format;
|
||||
use crate::error::CodecError;
|
||||
use crate::fidelity::Plan;
|
||||
use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType};
|
||||
use crate::options::{EncodeOptions, Limits};
|
||||
use crate::options::{EncodeOptions, Limits, alloc_zeroed};
|
||||
|
||||
const F: Format = Format::WebP;
|
||||
|
||||
@@ -23,8 +23,11 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
|
||||
let (w, h) = dec.dimensions();
|
||||
let layout = if dec.has_alpha() { ChannelLayout::Rgba } else { ChannelLayout::Rgb };
|
||||
limits.check(w, h, layout, SampleType::U8)?;
|
||||
// VP8L back-references and VP8 skipped macroblocks compress flat areas extremely well, so the
|
||||
// ratio is generous; it still stops a header-only file from asking for a gigabyte.
|
||||
Limits::check_plausible(u64::from(w) * u64::from(h) * layout.channels() as u64, bytes.len(), 1 << 16)?;
|
||||
let size = dec.output_buffer_size().ok_or_else(|| err("image too large"))?;
|
||||
let mut buf = vec![0u8; size];
|
||||
let mut buf = alloc_zeroed::<u8>(size)?;
|
||||
dec.read_image(&mut buf).map_err(err)?;
|
||||
let icc = dec.icc_profile().ok().flatten();
|
||||
let exif = dec.exif_metadata().ok().flatten();
|
||||
|
||||
@@ -15,6 +15,8 @@ pub enum Format {
|
||||
Ico,
|
||||
/// Netpbm family: PBM/PGM/PPM (P1–P6), PAM (P7) and PFM (`PF`/`Pf`).
|
||||
Pnm,
|
||||
/// ZSoft Paintbrush: 1/2/4-bit planar palettes, 8-bit indexed and 24-bit RGB.
|
||||
Pcx,
|
||||
Qoi,
|
||||
OpenExr,
|
||||
/// Radiance RGBE.
|
||||
@@ -56,6 +58,10 @@ pub struct FormatCaps {
|
||||
/// Formats that are enabled but intentionally not symmetric, with the reason.
|
||||
/// The test-suite asserts that every other enabled format is read+write.
|
||||
pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[
|
||||
(
|
||||
Format::Pcx,
|
||||
"PCX is supported for opening legacy paint and clipart assets. New files should use PNG; writing obsolete indexed and planar variants is intentionally not provided.",
|
||||
),
|
||||
(
|
||||
Format::Avif,
|
||||
"AVIF encode uses ravif (pure Rust) but decoding requires dav1d (C); read stays unsupported \
|
||||
@@ -78,7 +84,7 @@ const ALL_LAYOUTS: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::C
|
||||
|
||||
impl Format {
|
||||
/// Every format known to the crate (enabled or not).
|
||||
pub const ALL: [Format; 15] = [
|
||||
pub const ALL: [Format; 16] = [
|
||||
Format::Png,
|
||||
Format::Jpeg,
|
||||
Format::Tiff,
|
||||
@@ -88,6 +94,7 @@ impl Format {
|
||||
Format::Tga,
|
||||
Format::Ico,
|
||||
Format::Pnm,
|
||||
Format::Pcx,
|
||||
Format::Qoi,
|
||||
Format::OpenExr,
|
||||
Format::Hdr,
|
||||
@@ -117,6 +124,7 @@ impl Format {
|
||||
Format::Tga => "TGA",
|
||||
Format::Ico => "ICO",
|
||||
Format::Pnm => "Netpbm",
|
||||
Format::Pcx => "PCX",
|
||||
Format::Qoi => "QOI",
|
||||
Format::OpenExr => "OpenEXR",
|
||||
Format::Hdr => "Radiance HDR",
|
||||
@@ -139,6 +147,7 @@ impl Format {
|
||||
Format::Tga => &["tga", "icb", "vda", "vst"],
|
||||
Format::Ico => &["ico"],
|
||||
Format::Pnm => &["pnm", "pbm", "pgm", "ppm", "pam", "pfm"],
|
||||
Format::Pcx => &["pcx"],
|
||||
Format::Qoi => &["qoi"],
|
||||
Format::OpenExr => &["exr"],
|
||||
Format::Hdr => &["hdr"],
|
||||
@@ -159,6 +168,7 @@ impl Format {
|
||||
Format::Tga => "image/x-tga",
|
||||
Format::Ico => "image/x-icon",
|
||||
Format::Pnm => "image/x-portable-anymap",
|
||||
Format::Pcx => "image/x-pcx",
|
||||
Format::Qoi => "image/qoi",
|
||||
Format::OpenExr => "image/x-exr",
|
||||
Format::Hdr => "image/vnd.radiance",
|
||||
@@ -207,6 +217,7 @@ pub fn caps(format: Format) -> FormatCaps {
|
||||
Format::Tga => FormatCaps { layouts: RGB_GRAY, ..base },
|
||||
Format::Ico => FormatCaps { layouts: &[L::Rgba], ..base },
|
||||
Format::Pnm => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, ..base },
|
||||
Format::Pcx => FormatCaps { read: true, write: false, layouts: &[L::Rgb], alpha: false, ..base },
|
||||
Format::Qoi => base,
|
||||
Format::OpenExr => FormatCaps { depths: &[S::F16, S::F32], layouts: RGB_GRAY, ..base },
|
||||
Format::Hdr => FormatCaps { depths: &[S::F32], layouts: &[L::Rgb], alpha: false, lossy: true, ..base },
|
||||
@@ -266,6 +277,9 @@ pub fn detect(bytes: &[u8]) -> Option<Format> {
|
||||
if b.starts_with(b"SIMPLE =") {
|
||||
return Some(Format::Fits);
|
||||
}
|
||||
if crate::codecs::pcx::looks_like_pcx(b) {
|
||||
return Some(Format::Pcx);
|
||||
}
|
||||
if looks_like_tga(b) {
|
||||
return Some(Format::Tga);
|
||||
}
|
||||
|
||||
@@ -512,6 +512,8 @@ impl Image {
|
||||
out.extend_from_slice(&one);
|
||||
}
|
||||
out
|
||||
} else if let Some(fast) = self.convert_int_direct(layout, sample) {
|
||||
fast
|
||||
} else if layout == self.layout {
|
||||
quantize(&self.to_normalized(), sample)
|
||||
} else {
|
||||
@@ -531,6 +533,55 @@ impl Image {
|
||||
}
|
||||
}
|
||||
|
||||
/// Integer fast path of [`Image::convert`] for U8/U16 sources and targets whose result is
|
||||
/// a pure channel copy: same colour model (alpha added as opaque, or dropped) or gray to
|
||||
/// RGB. Bit-identical to the generic f32 route (see the equivalence tests) but without
|
||||
/// the two intermediate f32 buffers. Returns `None` for everything else.
|
||||
fn convert_int_direct(&self, layout: ChannelLayout, sample: SampleType) -> Option<Vec<u8>> {
|
||||
let int = |s: SampleType| matches!(s, SampleType::U8 | SampleType::U16);
|
||||
if !int(self.sample) || !int(sample) {
|
||||
return None;
|
||||
}
|
||||
let gray_to_rgb = self.layout.is_gray() && layout.is_rgb();
|
||||
if !gray_to_rgb && !layout.same_model(self.layout) {
|
||||
return None;
|
||||
}
|
||||
let one: &[u8] = match sample {
|
||||
SampleType::U8 => &[u8::MAX],
|
||||
_ => &u16::MAX.to_ne_bytes(),
|
||||
};
|
||||
let (fc, tc) = (self.layout.channels(), layout.channels());
|
||||
let (sb, db) = (self.sample.bytes(), sample.bytes());
|
||||
let (src_color, dst_color) = (self.layout.color_channels(), layout.color_channels());
|
||||
let n = self.data.len() / (fc * sb);
|
||||
let mut out = Vec::with_capacity(n.checked_mul(tc)?.checked_mul(db)?);
|
||||
macro_rules! run {
|
||||
($conv:expr) => {{
|
||||
let conv = $conv;
|
||||
for px in self.data.chunks_exact(fc * sb) {
|
||||
for j in 0..dst_color {
|
||||
let c = if src_color == 1 { 0 } else { j };
|
||||
conv(&px[c * sb..(c + 1) * sb], &mut out);
|
||||
}
|
||||
if layout.has_alpha() {
|
||||
if self.layout.has_alpha() {
|
||||
conv(&px[src_color * sb..(src_color + 1) * sb], &mut out);
|
||||
} else {
|
||||
out.extend_from_slice(one);
|
||||
}
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
match (self.sample, sample) {
|
||||
(SampleType::U8, SampleType::U8) => run!(|s: &[u8], o: &mut Vec<u8>| o.push(s[0])),
|
||||
(SampleType::U16, SampleType::U16) => run!(|s: &[u8], o: &mut Vec<u8>| o.extend_from_slice(s)),
|
||||
(SampleType::U8, SampleType::U16) => run!(|s: &[u8], o: &mut Vec<u8>| o.extend_from_slice(&(u16::from(s[0]) * 257).to_ne_bytes())),
|
||||
_ => run!(|s: &[u8], o: &mut Vec<u8>| o.push(((u32::from(u16::from_ne_bytes([s[0], s[1]])) + 128) / 257) as u8)),
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// [`Image::convert`], borrowing `self` when it already has that layout and sample type
|
||||
/// (encoders use it so a full-size image isn't copied for nothing).
|
||||
pub fn converted(&self, layout: ChannelLayout, sample: SampleType) -> std::borrow::Cow<'_, Image> {
|
||||
@@ -661,6 +712,66 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The generic f32 route `convert` used before the integer fast paths (the reference).
|
||||
fn convert_via_f32(img: &Image, layout: ChannelLayout, sample: SampleType) -> Vec<u8> {
|
||||
quantize(&convert_layout(&img.to_normalized(), img.layout, layout), sample)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn int_fast_path_matches_f32_route_for_every_value() {
|
||||
// Every U8 and every U16 value through every depth pair (alpha goes through the same per-sample conversion; covered by the layout test).
|
||||
let all8: Vec<u8> = (0..=255).collect();
|
||||
let all16: Vec<u16> = (0..=65535).collect();
|
||||
for (src, to) in
|
||||
[(SampleType::U8, SampleType::U8), (SampleType::U8, SampleType::U16), (SampleType::U16, SampleType::U8), (SampleType::U16, SampleType::U16)]
|
||||
{
|
||||
let img = if src == SampleType::U8 {
|
||||
Image::from_u8(256, 1, ChannelLayout::Gray, all8.clone()).unwrap()
|
||||
} else {
|
||||
Image::from_u16(65536, 1, ChannelLayout::Gray, &all16).unwrap()
|
||||
};
|
||||
for layout in [ChannelLayout::Gray, ChannelLayout::Rgb] {
|
||||
assert_eq!(img.convert(layout, to).data(), &convert_via_f32(&img, layout, to)[..], "{src:?}->{to:?} {layout:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn int_fast_path_matches_f32_route_for_every_layout() {
|
||||
let mut seed = 0x9e3779b97f4a7c15u64;
|
||||
let mut next = || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
};
|
||||
for from_s in [SampleType::U8, SampleType::U16] {
|
||||
for from_l in ChannelLayout::ALL {
|
||||
let n = 64 * from_l.channels();
|
||||
let mut vals = Vec::new();
|
||||
for i in 0..n {
|
||||
// Edge values (0, 1, max-1, max, mid) mixed with random ones.
|
||||
let r = next();
|
||||
let v = match i % 7 {
|
||||
0 => 0.0,
|
||||
1 => 1.0,
|
||||
2 => 1.0 / 255.0,
|
||||
3 => 254.0 / 255.0,
|
||||
_ => (r % 65536) as f32 / 65535.0,
|
||||
};
|
||||
vals.push(v);
|
||||
}
|
||||
let img = Image::from_normalized(64, 1, from_l, from_s, &vals).unwrap();
|
||||
for to_l in ChannelLayout::ALL {
|
||||
for to_s in SampleType::ALL {
|
||||
let got = img.convert(to_l, to_s);
|
||||
assert_eq!(got.data(), &convert_via_f32(&img, to_l, to_s)[..], "{from_l:?}/{from_s:?} -> {to_l:?}/{to_s:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn u8_u16_roundtrip_exact() {
|
||||
let v: Vec<u8> = (0..=255).collect();
|
||||
|
||||
@@ -43,7 +43,7 @@ pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_
|
||||
pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding};
|
||||
pub use half::f16;
|
||||
|
||||
use crate::codecs::{exr, fits, heif, jpeg, png, pnm, tiff, via_image, webp};
|
||||
use crate::codecs::{exr, fits, heif, jpeg, pcx, png, pnm, tiff, via_image, webp};
|
||||
|
||||
/// Detect the format and decode with default [`Limits`].
|
||||
pub fn decode(bytes: &[u8]) -> Result<Image, CodecError> {
|
||||
@@ -74,6 +74,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res
|
||||
Format::Tiff => tiff::decode(bytes, l),
|
||||
Format::WebP => webp::decode(bytes, l),
|
||||
Format::Pnm => pnm::decode(bytes, l),
|
||||
Format::Pcx => pcx::decode(bytes, l),
|
||||
Format::Fits => fits::decode(bytes, l),
|
||||
Format::OpenExr => exr::decode(bytes, l),
|
||||
Format::Heif => heif::decode(bytes, l, opts.keep_orientation),
|
||||
@@ -216,6 +217,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result<Vec
|
||||
Format::Tiff => tiff::encode(image, plan, opts),
|
||||
Format::WebP => webp::encode(image, plan, opts),
|
||||
Format::Pnm => pnm::encode(image, plan, opts),
|
||||
Format::Pcx => Err(CodecError::unsupported(format, "PCX is import-only; save as PNG instead")),
|
||||
Format::Fits => fits::encode(image, plan, opts),
|
||||
Format::OpenExr => exr::encode(image, plan, opts),
|
||||
Format::Heif => Err(CodecError::unsupported(format, "encoding is not available in this build")),
|
||||
|
||||
@@ -21,8 +21,10 @@ pub struct Limits {
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
// 2^30 pixels (e.g. 32768²) and, on 64-bit targets, 8 GiB: enough for the large
|
||||
// documents Photoshop users open (a 20000² RGBA 16-bit image is 3.2 GB).
|
||||
let max_alloc = if cfg!(target_pointer_width = "64") { 8 << 30 } else { 2 << 30 };
|
||||
// documents Photoshop users open (a 20000² RGBA 16-bit image is 3.2 GB). On 32-bit
|
||||
// targets (wasm32 has a 4 GiB address space shared with the document, history and
|
||||
// the decoder's own buffers) 1 GiB is the most one buffer can safely ask for.
|
||||
let max_alloc = if cfg!(target_pointer_width = "64") { 8 << 30 } else { 1 << 30 };
|
||||
Limits { max_width: 1 << 18, max_height: 1 << 18, max_pixels: 1 << 30, max_alloc }
|
||||
}
|
||||
}
|
||||
@@ -60,6 +62,19 @@ impl Limits {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decompression-bomb guard for formats that compress: refuse a file too small to hold
|
||||
/// `declared_bytes` of (stored, pre-expansion) image data, given that the compression
|
||||
/// never beats `max_ratio`:1. Called before the output buffer is allocated, so a
|
||||
/// header-only hostile file cannot make the decoder reserve gigabytes. A fixed 1 MiB of
|
||||
/// slack keeps tiny images and headers with large metadata unaffected.
|
||||
pub(crate) fn check_plausible(declared_bytes: u64, file_len: usize, max_ratio: u64) -> Result<(), CodecError> {
|
||||
let capacity = (file_len as u64).saturating_mul(max_ratio).saturating_add(1 << 20);
|
||||
if declared_bytes > capacity {
|
||||
return Err(CodecError::LimitExceeded(format!("a {file_len} byte file cannot hold {declared_bytes} bytes of image data")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn alloc_usize(&self) -> usize {
|
||||
usize::try_from(self.max_alloc).unwrap_or(usize::MAX)
|
||||
}
|
||||
@@ -149,3 +164,13 @@ impl Default for EncodeOptions {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A zero-filled buffer of `len` elements, allocated fallibly: an allocation failure becomes
|
||||
/// [`CodecError::LimitExceeded`] instead of aborting the process (which `catch_unwind` cannot
|
||||
/// stop).
|
||||
pub(crate) fn alloc_zeroed<T: Copy + Default>(len: usize) -> Result<Vec<T>, CodecError> {
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(len).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {len} elements for the image")))?;
|
||||
v.resize(len, T::default());
|
||||
Ok(v)
|
||||
}
|
||||
@@ -93,6 +93,30 @@ fn png_bomb_header_rejected_before_alloc() {
|
||||
assert!(is_limit(decode(&b)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_header_at_the_default_limit_needs_a_plausible_file_size() {
|
||||
// 32768 x 32768 x RGBA16 is exactly the default max_alloc: it passes the dimension limits,
|
||||
// but a ~100 byte file cannot hold it (zlib tops out near 1032:1), so it is refused before
|
||||
// the 8 GiB output buffer is allocated.
|
||||
let mut ihdr = Vec::new();
|
||||
ihdr.extend_from_slice(&32768u32.to_be_bytes());
|
||||
ihdr.extend_from_slice(&32768u32.to_be_bytes());
|
||||
ihdr.extend_from_slice(&[16, 6, 0, 0, 0]);
|
||||
let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
b.extend(png_chunk(b"IHDR", &ihdr));
|
||||
b.extend(png_chunk(b"IDAT", &[0x78, 0x9C, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01]));
|
||||
b.extend(png_chunk(b"IEND", &[]));
|
||||
assert!(is_limit(decode(&b)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_highly_compressible_image_still_decodes() {
|
||||
let img = Image::from_u8(3000, 3000, ChannelLayout::Rgba, vec![255u8; 3000 * 3000 * 4]).unwrap();
|
||||
let b = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert!(b.len() < 100_000, "{}", b.len());
|
||||
assert_eq!(decode(&b).unwrap().width(), 3000);
|
||||
}
|
||||
|
||||
const PNG_TEXT_BUDGET: usize = 64 << 10;
|
||||
|
||||
fn png_text_decode(bytes: &[u8], max_alloc: usize) -> Result<Image, CodecError> {
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
use photocraft_codecs::{ChannelLayout, CodecError, Format, SampleType, caps, decode, decode_as, detect, encode, from_extension};
|
||||
|
||||
fn header(bits: u8, planes: u8, width: u16, height: u16, stride: u16) -> Vec<u8> {
|
||||
let mut b = vec![0u8; 128];
|
||||
b[0] = 0x0a; // ZSoft
|
||||
b[1] = 5; // PC Paintbrush 3.0+
|
||||
b[2] = 1; // RLE
|
||||
b[3] = bits;
|
||||
b[8..10].copy_from_slice(&(width - 1).to_le_bytes());
|
||||
b[10..12].copy_from_slice(&(height - 1).to_le_bytes());
|
||||
b[12..14].copy_from_slice(&300u16.to_le_bytes());
|
||||
b[14..16].copy_from_slice(&150u16.to_le_bytes());
|
||||
b[65] = planes;
|
||||
b[66..68].copy_from_slice(&stride.to_le_bytes());
|
||||
b[68..70].copy_from_slice(&1u16.to_le_bytes());
|
||||
b
|
||||
}
|
||||
|
||||
fn rle_row(out: &mut Vec<u8>, row: &[u8]) {
|
||||
for &value in row {
|
||||
if value >= 0xc0 {
|
||||
out.extend_from_slice(&[0xc1, value]);
|
||||
} else {
|
||||
out.push(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pcx_is_readable_but_not_writable() {
|
||||
assert_eq!(from_extension("archive.PCX"), Some(Format::Pcx));
|
||||
assert!(caps(Format::Pcx).read && !caps(Format::Pcx).write);
|
||||
let img = photocraft_codecs::Image::from_u8(1, 1, ChannelLayout::Rgb, vec![0, 0, 0]).unwrap();
|
||||
assert!(matches!(encode(&img, Format::Pcx, &Default::default()), Err(CodecError::Unsupported { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_three_plane_rgb_and_keeps_dpi() {
|
||||
let mut b = header(8, 3, 2, 1, 2);
|
||||
for row in [&[255, 0][..], &[0, 255][..], &[0, 0][..]] {
|
||||
rle_row(&mut b, row);
|
||||
}
|
||||
assert_eq!(detect(&b), Some(Format::Pcx));
|
||||
let im = decode(&b).unwrap();
|
||||
assert_eq!(im.layout(), ChannelLayout::Rgb);
|
||||
assert_eq!(im.sample_type(), SampleType::U8);
|
||||
assert_eq!(im.dimensions(), (2, 1));
|
||||
assert_eq!(im.data(), &[255, 0, 0, 0, 255, 0]);
|
||||
assert_eq!(im.meta.dpi, Some((300.0, 150.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_256_colour_vga_palette() {
|
||||
let mut b = header(8, 1, 2, 1, 2);
|
||||
rle_row(&mut b, &[1, 2]);
|
||||
b.push(0x0c);
|
||||
let mut palette = vec![0; 256 * 3];
|
||||
palette[3..6].copy_from_slice(&[255, 0, 0]);
|
||||
palette[6..9].copy_from_slice(&[0, 255, 0]);
|
||||
b.extend(palette);
|
||||
assert_eq!(decode(&b).unwrap().data(), &[255, 0, 0, 0, 255, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_4bit_and_monochrome_palettes() {
|
||||
let mut four = header(4, 1, 2, 1, 2);
|
||||
four[16 + 3..16 + 6].copy_from_slice(&[255, 0, 0]);
|
||||
four[16 + 6..16 + 9].copy_from_slice(&[0, 0, 255]);
|
||||
rle_row(&mut four, &[0x12, 0]);
|
||||
assert_eq!(decode(&four).unwrap().data(), &[255, 0, 0, 0, 0, 255]);
|
||||
|
||||
let mut one = header(1, 1, 2, 1, 2);
|
||||
one[16 + 3..16 + 6].copy_from_slice(&[255, 0, 0]);
|
||||
rle_row(&mut one, &[0x80, 0]);
|
||||
assert_eq!(decode(&one).unwrap().data(), &[255, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncated_and_overshooting_rle_without_panicking() {
|
||||
let mut b = header(8, 3, 2, 1, 2);
|
||||
assert!(decode_as(Format::Pcx, &b).is_err(), "header alone is truncated");
|
||||
b.extend([0xc5, 0xff]); // a five-pixel run cannot cross a two-byte row
|
||||
assert!(decode_as(Format::Pcx, &b).is_err());
|
||||
let mut b = header(8, 3, 2, 1, 2);
|
||||
b.extend([0xc1]); // missing run value
|
||||
assert!(decode_as(Format::Pcx, &b).is_err());
|
||||
let mut b = header(8, 3, 2, 1, 2);
|
||||
b[66..68].copy_from_slice(&0u16.to_le_bytes());
|
||||
assert_eq!(detect(&b), None, "invalid stride is not a PCX signature");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_headers_that_exceed_allocation_budget() {
|
||||
let mut b = header(8, 3, 3000, 3000, 3000);
|
||||
// The default decoder rejects the allocation before reading any scanline.
|
||||
let opts = photocraft_codecs::DecodeOptions { limits: photocraft_codecs::Limits { max_alloc: 1024, ..Default::default() }, ..Default::default() };
|
||||
assert!(matches!(photocraft_codecs::decode_as_with(Format::Pcx, &b, &opts), Err(CodecError::LimitExceeded(_))));
|
||||
b[2] = 0;
|
||||
assert_eq!(detect(&b), None, "unsupported uncompressed encoding");
|
||||
}
|
||||
@@ -163,7 +163,8 @@ pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth
|
||||
}
|
||||
None => (0.0, 0.0, 0.0),
|
||||
};
|
||||
hue_saturation(c, *hue + dh, (*saturation / 100.0 + ds).clamp(-1.0, 1.0), (*lightness / 100.0 + dl).clamp(-1.0, 1.0), *colorize)
|
||||
let out = hue_saturation(c, *hue + dh, (*saturation / 100.0 + ds).clamp(-1.0, 1.0), (*lightness / 100.0).clamp(-1.0, 1.0), *colorize);
|
||||
range_lightness(out, dl)
|
||||
})
|
||||
}
|
||||
Adjustment::Vibrance { vibrance, saturation } => {
|
||||
@@ -188,7 +189,9 @@ pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth
|
||||
Adjustment::BlackWhite { weights, tint } => map_rgb(buf, |c| {
|
||||
let g = black_white_gray(c, weights);
|
||||
match tint {
|
||||
Some(t) => std::array::from_fn(|i| (g * t[i] * 2.0).clamp(0.0, 1.0) * 0.5 + g * 0.5),
|
||||
// Photoshop tints like the Color blend mode: the tint's hue and saturation at the
|
||||
// grey's luminosity (SetLum + ClipColor), measured in Photoshop 27.11.
|
||||
Some(t) => photocraft_color::blend::set_lum(*t, g).map(|v| v.clamp(0.0, 1.0)),
|
||||
None => [g; 3],
|
||||
}
|
||||
}),
|
||||
@@ -426,21 +429,32 @@ pub fn hue_range_tables(ranges: &[HueRange; 6]) -> [Vec<f32>; 3] {
|
||||
/// Colorize sets the hue and saturation instead of shifting them; at 0% it leaves only the
|
||||
/// lightness, as in Photoshop (#2326). Ticking Colorize in the dialog starts saturation at 25%.
|
||||
pub fn hue_saturation(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool) -> [f32; 3] {
|
||||
let (mut hh, mut ss, ll) = rgb_to_hsl(c);
|
||||
let lighten = |v: f32| if l > 0.0 { v + (1.0 - v) * l } else { v * (1.0 + l) };
|
||||
if colorize {
|
||||
hh = hue.rem_euclid(360.0) / 360.0;
|
||||
ss = s.abs().min(1.0);
|
||||
} else {
|
||||
hh = (hh + hue / 360.0).rem_euclid(1.0);
|
||||
ss = (ss * (1.0 + s)).clamp(0.0, 1.0);
|
||||
// Colorize builds the colour at the lightened (or darkened) lightness, so black with
|
||||
// Lightness +30 becomes a 30 % lightness colour, not grey (measured in Photoshop 27.11).
|
||||
let (_, _, ll) = rgb_to_hsl(c);
|
||||
return hsl_to_rgb(hue.rem_euclid(360.0) / 360.0, s.abs().min(1.0), lighten(ll));
|
||||
}
|
||||
let mut rgb = hsl_to_rgb(hh, ss, ll);
|
||||
if l > 0.0 {
|
||||
rgb = rgb.map(|v| v + (1.0 - v) * l);
|
||||
} else if l < 0.0 {
|
||||
rgb = rgb.map(|v| v * (1.0 + l));
|
||||
}
|
||||
rgb
|
||||
// Photoshop applies Lightness first, then rotates the hue and scales the saturation of the
|
||||
// result: Hue +40, Saturation +25, Lightness -10 turns (240, 160, 30) into (173, 243, 0), not
|
||||
// (168, 230, 14) (Photoshop 27.11 corpus file adjustments/rgb8/hue-saturation).
|
||||
let (hh, ss, ll) = rgb_to_hsl(c.map(lighten));
|
||||
let hh = (hh + hue / 360.0).rem_euclid(1.0);
|
||||
// Raising saturation divides by 1 - s, lowering it multiplies by 1 + s: +50 % doubles it
|
||||
// (measured in Photoshop 27.11); +100 % saturates any colour that has some.
|
||||
let ss = if s > 0.0 { ss / (1.0 - s).max(1.0 / 512.0) } else { ss * (1.0 + s) }.clamp(0.0, 1.0);
|
||||
hsl_to_rgb(hh, ss, ll)
|
||||
}
|
||||
|
||||
/// A colour range's Lightness, applied after the master edits. It moves each channel towards the
|
||||
/// pixel's brightest channel when raised and towards its darkest when lowered, not towards white
|
||||
/// or black: Blues +50 turns (0, 29, 115) into (57, 71, 115), Blues -50 turns (102, 128, 204) into
|
||||
/// (102, 115, 153) (measured in Photoshop 27.11).
|
||||
pub fn range_lightness(c: [f32; 3], l: f32) -> [f32; 3] {
|
||||
let l = l.clamp(-1.0, 1.0);
|
||||
let target = if l > 0.0 { c[0].max(c[1]).max(c[2]) } else { c[0].min(c[1]).min(c[2]) };
|
||||
c.map(|v| v + (target - v) * l.abs())
|
||||
}
|
||||
|
||||
/// Black & White grey value. Each colour is the sum of a grey part (its smallest channel), a
|
||||
@@ -1283,6 +1297,51 @@ mod tone_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Photoshop 27.11, measured: Hue/Saturation raising saturation, and Colorize with Lightness.
|
||||
#[test]
|
||||
fn hue_saturation_matches_photoshop() {
|
||||
// (input, hue, saturation, lightness, colorize, Photoshop's output)
|
||||
type Case = ([u8; 3], f32, f32, f32, bool, [u8; 3]);
|
||||
let measured: [Case; 8] = [
|
||||
([204, 102, 102], 0.0, 50.0, 0.0, false, [254, 51, 51]),
|
||||
([204, 159, 102], 0.0, 50.0, 0.0, false, [254, 164, 51]),
|
||||
([204, 102, 102], 0.0, -50.0, 0.0, false, [178, 127, 127]),
|
||||
([0, 0, 0], 120.0, 100.0, 30.0, true, [0, 152, 0]),
|
||||
([28, 28, 28], 120.0, 100.0, 30.0, true, [0, 192, 0]),
|
||||
([160, 160, 160], 30.0, 25.0, -40.0, true, [120, 96, 73]),
|
||||
([252, 252, 252], 30.0, 25.0, -40.0, true, [177, 151, 126]),
|
||||
([255, 143, 0], 30.0, 25.0, -40.0, true, [95, 76, 58]),
|
||||
];
|
||||
for (input, hue, saturation, lightness, colorize, want) in measured {
|
||||
let a = Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges: HueRange::defaults() };
|
||||
let c = input.map(|v| v as f32 / 255.0);
|
||||
let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c[0], c[1], c[2], 1.0]] };
|
||||
apply(&a, &mut b);
|
||||
for (i, w) in want.iter().enumerate() {
|
||||
let got = b.px[0][i] * 255.0;
|
||||
assert!((got - *w as f32).abs() <= 2.0, "{input:?} h{hue} s{saturation} l{lightness} colorize {colorize}, channel {i}: {got} vs {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Photoshop 27.11, measured: a range's Lightness (Blues ±50) moves towards the brightest or darkest channel.
|
||||
#[test]
|
||||
fn range_lightness_matches_photoshop() {
|
||||
let measured = [
|
||||
([0u8, 29, 115], 0.5, [57u8, 71, 115]),
|
||||
([0, 64, 255], 0.5, [125, 157, 255]),
|
||||
([102, 128, 204], 0.5, [152, 165, 204]),
|
||||
([102, 128, 204], -0.5, [102, 115, 154]),
|
||||
([0, 18, 115], -0.5, [0, 9, 58]),
|
||||
];
|
||||
for (input, l, want) in measured {
|
||||
let got = range_lightness(input.map(|v| v as f32 / 255.0), l);
|
||||
for i in 0..3 {
|
||||
assert!((got[i] * 255.0 - want[i] as f32).abs() <= 2.5, "{input:?} channel {i}: {} vs {}", got[i] * 255.0, want[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_white_weights() {
|
||||
let d = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0];
|
||||
@@ -1294,6 +1353,31 @@ mod tone_tests {
|
||||
assert!(black_white_gray([1.0, 0.0, 0.0], &w) > black_white_gray([1.0, 0.0, 0.0], &d));
|
||||
}
|
||||
|
||||
/// Photoshop 27.11, measured: Black & White (default weights) with Tint over greys. The tint
|
||||
/// is blended like the Color blend mode: its hue and saturation at the grey's luminosity.
|
||||
#[test]
|
||||
fn black_white_tint_matches_photoshop() {
|
||||
let weights = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0];
|
||||
let measured: [([u8; 3], u8, [u8; 3]); 6] = [
|
||||
([255, 0, 0], 24, [81, 1, 1]),
|
||||
([255, 0, 0], 120, [255, 64, 64]),
|
||||
([255, 0, 0], 240, [255, 235, 235]),
|
||||
([0xe1, 0xd3, 0xb3], 120, [133, 119, 87]),
|
||||
([0xe1, 0xd3, 0xb3], 24, [33, 24, 1]),
|
||||
([0x40, 0x20, 0x10], 120, [144, 112, 96]),
|
||||
];
|
||||
for (tint, grey, want) in measured {
|
||||
let tint = Some(tint.map(|v| v as f32 / 255.0));
|
||||
let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[grey as f32 / 255.0; 4]] };
|
||||
b.px[0][3] = 1.0;
|
||||
apply(&Adjustment::BlackWhite { weights, tint }, &mut b);
|
||||
for (i, w) in want.iter().enumerate() {
|
||||
let got = b.px[0][i] * 255.0;
|
||||
assert!((got - *w as f32).abs() <= 2.5, "tint {tint:?} grey {grey} channel {i}: {got} vs {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_map_dither_stays_close() {
|
||||
let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])];
|
||||
|
||||
@@ -84,10 +84,10 @@ pub fn shapeless(layer: &Layer) -> bool {
|
||||
!layer.advanced.transparency_shapes && (layer.advanced.knockout != Knockout::None || effects::has_effects(layer))
|
||||
}
|
||||
|
||||
/// The Background layer of a stack: the bottom layer, a locked, opaque-by-convention pixel layer
|
||||
/// named "Background" (how PSD import and File › New create it).
|
||||
/// Whether `l`, the bottom layer of a stack, is the Background: identified by its locks and kind,
|
||||
/// never by its (localized) name ([`photocraft_doc::Document::background`]).
|
||||
pub fn is_background(l: &Layer) -> bool {
|
||||
l.name == "Background" && l.locks.transparency && !l.clipped && matches!(l.content, LayerContent::Raster(_))
|
||||
l.has_background_traits()
|
||||
}
|
||||
|
||||
/// What a deep knockout reveals over `rect`: the document's initial backdrop with its Background
|
||||
|
||||
@@ -437,3 +437,26 @@ fn a_knockout_background_does_not_recurse() {
|
||||
let got = render(&d, Rect::from_xywh(0, 0, 1, 1)).px[0];
|
||||
assert!(got[3] <= 1.0);
|
||||
}
|
||||
|
||||
/// The Background is found by its structure, not its English name: a file from a German or
|
||||
/// Japanese Photoshop calls it "Hintergrund" or "背景", and a deep knockout still reveals it. A
|
||||
/// bottom layer merely called "Background", without the Background's locks, is not one.
|
||||
#[test]
|
||||
fn deep_knockout_reveals_a_localized_background() {
|
||||
for depth in DEPTHS {
|
||||
for name in ["Hintergrund", "背景", "Arrière-plan"] {
|
||||
let mut d = doc(depth, true);
|
||||
d.layers[0].name = name.into();
|
||||
let green = solid(&d, "green", full(&d), GREEN);
|
||||
d.layers.push(green);
|
||||
d.layers.push(knocker(&d, Knockout::Deep));
|
||||
check(&d, 2, 2, WHITE, name);
|
||||
}
|
||||
let mut d = doc(depth, true);
|
||||
d.layers[0].locks = Default::default();
|
||||
let green = solid(&d, "green", full(&d), GREEN);
|
||||
d.layers.push(green);
|
||||
d.layers.push(knocker(&d, Knockout::Deep));
|
||||
check(&d, 2, 2, [0.0; 4], "an unlocked layer named Background");
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,7 @@ pub fn margin(layer: &Layer) -> i32 {
|
||||
Effect::DropShadow(s) | Effect::InnerShadow(s) => s.distance + s.size,
|
||||
Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.size,
|
||||
Effect::Stroke(s) => s.size,
|
||||
Effect::Satin(s) => s.distance + s.size,
|
||||
Effect::Satin(s) => satin_distance(s) + s.size,
|
||||
Effect::BevelEmboss(b) => b.size + b.soften,
|
||||
_ => 0.0,
|
||||
};
|
||||
@@ -1689,8 +1689,14 @@ impl FxMaps {
|
||||
}
|
||||
}
|
||||
|
||||
/// The distance the two satin copies are offset by. Photoshop draws Distance 0 as 1 px (an
|
||||
/// edge band of 2/size, measured in Photoshop 27.11), not as two copies cancelling out.
|
||||
pub fn satin_distance(s: &photocraft_doc::effects::Satin) -> f32 {
|
||||
s.distance.max(1.0)
|
||||
}
|
||||
|
||||
fn satin_map(shape: &Map, s: &photocraft_doc::effects::Satin) -> Map {
|
||||
let (dx, dy) = offset(s.angle, s.distance);
|
||||
let (dx, dy) = offset(s.angle, satin_distance(s));
|
||||
let mut a = shape.shifted(dx, dy, 0.0);
|
||||
let mut b = shape.shifted(-dx, -dy, 0.0);
|
||||
// Two box passes of the satin size (fitted: 0.2 % mean error on psd-tools layer_effects).
|
||||
@@ -3008,6 +3014,28 @@ mod tests {
|
||||
m
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn satin_at_distance_zero_matches_photoshop() {
|
||||
// Photoshop 27.11, Satin black 100 %, angle 90°, Linear contour, distance 0, size 5 over a
|
||||
// #808080 square: the rows from the top edge read 82, 102, 123, 128.
|
||||
let s = photocraft_doc::effects::Satin {
|
||||
common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0),
|
||||
color: photocraft_color::Color::BLACK,
|
||||
angle: 90.0,
|
||||
distance: 0.0,
|
||||
size: 5.0,
|
||||
contour: Contour::Linear,
|
||||
anti_alias: false,
|
||||
invert: false,
|
||||
};
|
||||
let m = satin_map(&square_shape(60), &s);
|
||||
for (row, gray) in [(5, 82.0), (7, 102.0), (9, 123.0), (11, 128.0), (30, 128.0)] {
|
||||
let want = 1.0 - gray / 128.0;
|
||||
let got = m.v[row * 60 + 30];
|
||||
assert!((got - want).abs() < 0.02, "row {row}: {got} vs {want}");
|
||||
}
|
||||
}
|
||||
|
||||
fn shadow(noise: f32, origin: (i32, i32)) -> Map {
|
||||
let s = Shadow {
|
||||
common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0),
|
||||
|
||||
@@ -1674,6 +1674,18 @@ fn blend_into_fill(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity
|
||||
|
||||
/// [`blend_into`] mixing coverage in a `gamma` space (type layers).
|
||||
fn blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) {
|
||||
// The blend space is constant in this loop. Some TLS implementations synchronise even a
|
||||
// boolean read, so select the common Normal kernel once instead of once per pixel.
|
||||
if mode == BlendMode::Normal && gamma == 1.0 && !psblend::LAB_MIX.with(|l| l.get()) {
|
||||
for (i, b) in backdrop.px.iter_mut().enumerate() {
|
||||
let s = src.px[i];
|
||||
if s[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
*b = psblend::composite_normal_rgb(*b, s, opacity);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let rect = backdrop.rect;
|
||||
let w = rect.width() as i32;
|
||||
for (i, b) in backdrop.px.iter_mut().enumerate() {
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
//! Ink density `v` (the channel value, 1 = solid) of an ink with display colour `c` and solidity
|
||||
//! `s` turns the colour underneath `p` into `(1 − s·v)·p·(1 − v + v·c) + s·v·c`: transparent inks
|
||||
//! (solidity 0) multiply like overprinted process inks, opaque ones cover what is below, which is
|
||||
//! how Photoshop previews spot channels.
|
||||
//! how Photoshop previews spot channels. An alpha-type channel of a Multichannel document
|
||||
//! (selected / masked areas) still prints, as a transparent black ink, like Photoshop shows it.
|
||||
|
||||
use photocraft_doc::Document;
|
||||
use photocraft_geom::Rect;
|
||||
@@ -15,7 +16,7 @@ pub fn inks(doc: &Document, rect: Rect) -> Buffer {
|
||||
let mut buf = Buffer::filled(rect, [1.0, 1.0, 1.0, 1.0]);
|
||||
let mut vals = Vec::new();
|
||||
for ch in &doc.channels {
|
||||
let Some((ink, solidity)) = ch.spot else { continue };
|
||||
let (ink, solidity) = ch.spot.unwrap_or((photocraft_color::Color::BLACK, 0.0));
|
||||
if ch.surface.content_bounds().intersect(&rect).is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -65,7 +66,15 @@ mod tests {
|
||||
assert_eq!(r.px[1], [0.0, 1.0, 1.0, 1.0]);
|
||||
assert_eq!(r.px[2], [0.0, 0.0, 1.0, 1.0]);
|
||||
assert_eq!(r.px[3], [1.0, 0.0, 1.0, 1.0]);
|
||||
// Alpha channels and other modes are not inks.
|
||||
// An alpha-type channel prints as a black ink.
|
||||
let mut k = Surface::new(fmt);
|
||||
k.write_region(Rect::new(0, 0, 4, 1), &[0.5, 0.0, 0.0, 0.0]);
|
||||
doc.channels.push(AlphaChannel::new("Alpha", k));
|
||||
let r = crate::flatten(&doc);
|
||||
// 0.5 is stored as 128/255 in an 8-bit channel: within one 8-bit step.
|
||||
assert!((r.px[0][0] - 0.5).abs() <= 1.0 / 255.0 && (r.px[0][1] - 0.5).abs() <= 1.0 / 255.0, "{:?}", r.px[0]);
|
||||
assert_eq!(r.px[1], [0.0, 1.0, 1.0, 1.0]);
|
||||
// Other modes have no inks.
|
||||
doc.mode = ColorMode::Rgb;
|
||||
assert_eq!(crate::flatten(&doc).px[1][3], 0.0);
|
||||
}
|
||||
|
||||
+165
-2
@@ -83,15 +83,52 @@ pub fn proxy_document(doc: &Document, k: u32) -> Document {
|
||||
}
|
||||
|
||||
/// Whether a proxy composite is a faithful reduction of `doc`: layer effects (whose sizes are in
|
||||
/// document pixels) and vector masks (paths in document coordinates) would not scale with it.
|
||||
/// document pixels) and nonempty vector masks (paths in document coordinates) would not scale
|
||||
/// with it. Empty vector masks have constant coverage, including inversion and density.
|
||||
/// Nonempty paths can still anchor fill layouts even when their mask density is zero.
|
||||
pub fn proxy_faithful(doc: &Document) -> bool {
|
||||
doc.walk().iter().all(|(_, _, l)| !crate::effects::has_effects(l) && l.vector_mask.as_ref().is_none_or(|v| !v.enabled))
|
||||
doc.walk().iter().all(|(_, _, l)| !crate::effects::has_effects(l) && l.vector_mask.as_ref().is_none_or(|v| !v.enabled || v.path.is_empty()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_doc::vector::{Knot, Path, Subpath, VectorMask};
|
||||
use photocraft_doc::{Effect, Fill, GradientStyle, LayerMask};
|
||||
|
||||
fn two_colors(size: Size, depth: SampleType) -> Document {
|
||||
let mut doc = Document::new("mask", size, ColorMode::Rgb, depth);
|
||||
let format = doc.pixel_format();
|
||||
for (name, color) in [("blue", [0.0, 0.0, 1.0, 1.0]), ("red", [1.0, 0.0, 0.0, 1.0])] {
|
||||
doc.layers.push(Layer::new(name, LayerContent::Raster(Surface::with_default(format, &color))));
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
fn assert_same_pixels(actual: &crate::Buffer, expected: &crate::Buffer) {
|
||||
assert_same_pixels_within(actual, expected, 1e-6);
|
||||
}
|
||||
|
||||
fn assert_same_pixels_within(actual: &crate::Buffer, expected: &crate::Buffer, tolerance: f32) {
|
||||
assert_eq!(actual.rect, expected.rect);
|
||||
assert_eq!(actual.px.len(), expected.px.len());
|
||||
for (a, b) in actual.px.iter().zip(&expected.px) {
|
||||
assert!(a.iter().zip(b).all(|(a, b)| (a - b).abs() <= tolerance), "{a:?} != {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn u16_coverage(value: f32) -> f32 {
|
||||
// Feathered masks use the existing U16 combined-mask surface, including its default.
|
||||
(value.clamp(0.0, 1.0) * 65535.0 + 0.5).floor() / 65535.0
|
||||
}
|
||||
|
||||
fn opacity_reference(doc: &Document, coverage: f32) -> Document {
|
||||
let mut reference = doc.clone();
|
||||
reference.layers[1].vector_mask = None;
|
||||
reference.layers[1].opacity *= coverage;
|
||||
reference
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn downsample_picks_every_kth_pixel() {
|
||||
@@ -134,4 +171,130 @@ mod tests {
|
||||
assert_eq!((s.pixel(7, 15)[0], s.pixel(8, 0)[0]), (1.0, 0.0));
|
||||
assert!(proxy_document(&Document::new("n", Size::new(8, 8), ColorMode::Rgb, SampleType::U8), 4).selection.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_accepts_empty_paths_but_keeps_geometry_and_effect_guards() {
|
||||
let mut doc = two_colors(Size::new(32, 16), SampleType::F32);
|
||||
doc.layers[1].vector_mask = Some(VectorMask::new(Path::new(vec![Subpath::default()])));
|
||||
assert!(proxy_faithful(&doc));
|
||||
// A lone knot has no fillable segments, but still carries document coordinates.
|
||||
doc.layers[1].vector_mask.as_mut().unwrap().path.subpaths[0].knots.push(Knot::corner(12.0, 8.0));
|
||||
assert!(!proxy_faithful(&doc));
|
||||
doc.layers[1].vector_mask.as_mut().unwrap().enabled = false;
|
||||
assert!(proxy_faithful(&doc));
|
||||
doc.layers[1].vector_mask = Some(VectorMask::new(Path::default()));
|
||||
doc.layers[1].effects.items.push(Effect::default_drop_shadow());
|
||||
doc.layers[1].effects.enabled = true;
|
||||
assert!(!proxy_faithful(&doc));
|
||||
doc.layers[1].effects.items[0].set_enabled(false);
|
||||
assert!(proxy_faithful(&doc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_vector_masks_keep_constant_coverage_at_every_depth() {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let mut doc = two_colors(Size::new(32, 16), depth);
|
||||
for path in [Path::default(), Path::new(vec![Subpath::default()])] {
|
||||
for inverted in [false, true] {
|
||||
for density in [0.0, 0.25, 1.0] {
|
||||
for feather in [0.0, 4.0] {
|
||||
let mut mask = VectorMask::new(path.clone());
|
||||
mask.path.inverted = inverted;
|
||||
mask.density = density;
|
||||
mask.feather = feather;
|
||||
doc.layers[1].vector_mask = Some(mask);
|
||||
assert!(proxy_faithful(&doc));
|
||||
let coverage = if inverted { 1.0 - density } else { 1.0 };
|
||||
let coverage = if feather > 0.0 { u16_coverage(coverage) } else { coverage };
|
||||
let expected = [coverage, 0.0, 1.0 - coverage, 1.0];
|
||||
let full = crate::render(&doc, doc.bounds());
|
||||
for pixel in &full.px {
|
||||
assert!(pixel.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-6), "{depth:?} {inverted} {density} {feather}: {pixel:?}");
|
||||
}
|
||||
let proxy = proxy_document(&doc, 4);
|
||||
assert_eq!(proxy.layers[1].vector_mask, doc.layers[1].vector_mask);
|
||||
let reference = proxy_document(&opacity_reference(&doc, coverage), 4);
|
||||
assert_same_pixels(&crate::render(&proxy, proxy.bounds()), &crate::render(&reference, reference.bounds()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_vector_mask_multiplies_a_feathered_pixel_mask_on_the_proxy() {
|
||||
let mut doc = two_colors(Size::new(32, 16), SampleType::F32);
|
||||
let mut surface = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false), &[0.25]);
|
||||
surface.fill_rect(Rect::new(0, 0, 16, 16), &[0.75]);
|
||||
doc.layers[1].mask = Some(LayerMask { surface, density: 0.5, feather: 2.0, ..LayerMask::reveal_all() });
|
||||
let mut mask = VectorMask::new(Path { inverted: true, ..Path::default() });
|
||||
mask.density = 0.75;
|
||||
mask.feather = 8.0;
|
||||
doc.layers[1].vector_mask = Some(mask);
|
||||
assert!(proxy_faithful(&doc));
|
||||
let reference = opacity_reference(&doc, 0.25);
|
||||
for k in [1, 2, 4] {
|
||||
let (actual, expected) = (proxy_document(&doc, k), proxy_document(&reference, k));
|
||||
// Q(0.25 * pixel) versus 0.25 * Q(pixel): U16 rounding differs by at most
|
||||
// 0.625 / 65535. Allow one U16 level plus a small float arithmetic allowance.
|
||||
assert_same_pixels_within(&crate::render(&actual, actual.bounds()), &crate::render(&expected, expected.bounds()), 1.0 / 65535.0 + 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_vector_masks_keep_the_pixel_mask_gradient_frame() {
|
||||
let mut doc = two_colors(Size::new(32, 16), SampleType::F32);
|
||||
doc.layers[1].content = LayerContent::Fill(Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false));
|
||||
let mut pixel = LayerMask::hide_all();
|
||||
pixel.surface.fill_rect(Rect::new(8, 4, 24, 12), &[1.0]);
|
||||
doc.layers[1].mask = Some(pixel);
|
||||
for inverted in [false, true] {
|
||||
let mut mask = VectorMask::new(Path { inverted, ..Path::default() });
|
||||
mask.density = 0.5;
|
||||
mask.feather = 3.0;
|
||||
doc.layers[1].vector_mask = Some(mask);
|
||||
assert!(proxy_faithful(&doc));
|
||||
assert_eq!(crate::fill_frame(&doc.layers[1], doc.bounds()), Rect::new(8, 4, 24, 12));
|
||||
let actual = proxy_document(&doc, 4);
|
||||
assert_eq!(crate::fill_frame(&actual.layers[1], actual.bounds()), Rect::new(2, 1, 6, 3));
|
||||
let reference = proxy_document(&opacity_reference(&doc, u16_coverage(if inverted { 0.5 } else { 1.0 })), 4);
|
||||
assert_same_pixels(&crate::render(&actual, actual.bounds()), &crate::render(&reference, reference.bounds()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_density_geometry_still_blocks_the_proxy_and_anchors_a_gradient() {
|
||||
let mut doc = Document::new("gradient", Size::new(64, 32), ColorMode::Rgb, SampleType::F32);
|
||||
let fill = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false);
|
||||
let mut layer = Layer::new("gradient", LayerContent::Fill(fill));
|
||||
let path = Path::new(vec![Subpath::polygon(&[(16.0, 8.0), (48.0, 8.0), (48.0, 24.0), (16.0, 24.0)])]);
|
||||
let mut mask = VectorMask::new(path);
|
||||
mask.density = 0.0;
|
||||
layer.vector_mask = Some(mask);
|
||||
doc.layers.push(layer);
|
||||
assert!(!proxy_faithful(&doc));
|
||||
assert_eq!(crate::fill_frame(&doc.layers[0], doc.bounds()), Rect::new(16, 8, 48, 24));
|
||||
// Density zero reveals all pixels, but the unscaled path would still move the fill.
|
||||
let forced_proxy = proxy_document(&doc, 4);
|
||||
let exact = crate::render_reduced(&doc, 16, 8);
|
||||
let wrong = crate::render(&forced_proxy, forced_proxy.bounds());
|
||||
assert!(exact.px.iter().zip(&wrong.px).any(|(a, b)| (a[0] - b[0]).abs() > 0.1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_thumbnail_keeps_inverted_empty_mask_coverage() {
|
||||
// Default-only surfaces exercise the large-document branch without allocating 17 MP.
|
||||
let mut doc = two_colors(Size::new(4200, 4200), SampleType::F32);
|
||||
let mut mask = VectorMask::new(Path { inverted: true, ..Path::default() });
|
||||
mask.density = 0.75;
|
||||
mask.feather = 8.0;
|
||||
doc.layers[1].vector_mask = Some(mask);
|
||||
assert!(doc.size.area() > crate::PROXY_THUMBNAIL_PIXELS);
|
||||
assert!(proxy_faithful(&doc));
|
||||
let actual = crate::thumbnail_buffer(&doc, 4);
|
||||
assert_eq!(actual.rect, Rect::new(0, 0, 4, 4));
|
||||
let coverage = u16_coverage(0.25);
|
||||
assert_eq!(actual.px, vec![[coverage, 0.0, 1.0 - coverage, 1.0]; 16]);
|
||||
}
|
||||
}
|
||||
@@ -210,13 +210,7 @@ pub fn composite(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opacity:
|
||||
return [r[0], r[1], r[2], ao];
|
||||
}
|
||||
if mode == BlendMode::Normal {
|
||||
// Fast path: B(Cb, Cs) = Cs.
|
||||
if ao <= 0.0 {
|
||||
return [0.0; 4];
|
||||
}
|
||||
let kb = ab * (1.0 - as_);
|
||||
let inv = 1.0 / ao;
|
||||
return [(kb * backdrop[0] + as_ * source[0]) * inv, (kb * backdrop[1] + as_ * source[1]) * inv, (kb * backdrop[2] + as_ * source[2]) * inv, ao];
|
||||
return normal_rgb(backdrop, source, as_, ao);
|
||||
}
|
||||
let cb = [backdrop[0], backdrop[1], backdrop[2]];
|
||||
let cs = [source[0], source[1], source[2]];
|
||||
@@ -232,6 +226,29 @@ pub fn composite(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opacity:
|
||||
out
|
||||
}
|
||||
|
||||
/// Normal mixing outside Lab, for callers that select the blend space once per buffer.
|
||||
#[inline]
|
||||
pub(crate) fn composite_normal_rgb(backdrop: [f32; 4], source: [f32; 4], opacity: f32) -> [f32; 4] {
|
||||
let ab = backdrop[3];
|
||||
let as_ = source[3] * opacity;
|
||||
if as_ <= 0.0 {
|
||||
return backdrop;
|
||||
}
|
||||
let ao = as_ + ab * (1.0 - as_);
|
||||
normal_rgb(backdrop, source, as_, ao)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn normal_rgb(backdrop: [f32; 4], source: [f32; 4], as_: f32, ao: f32) -> [f32; 4] {
|
||||
// B(Cb, Cs) = Cs. Keep the scalar composite's operation order and straight alpha.
|
||||
if ao <= 0.0 {
|
||||
return [0.0; 4];
|
||||
}
|
||||
let kb = backdrop[3] * (1.0 - as_);
|
||||
let inv = 1.0 / ao;
|
||||
[(kb * backdrop[0] + as_ * source[0]) * inv, (kb * backdrop[1] + as_ * source[1]) * inv, (kb * backdrop[2] + as_ * source[2]) * inv, ao]
|
||||
}
|
||||
|
||||
/// Photoshop's "Blend Text Colors Using Gamma" (Color Settings › Advanced, on at 1.45 by
|
||||
/// default): type layers mix their colour with the backdrop in linear light raised to 1 / 1.45
|
||||
/// ([`text_encode`]), so anti-aliased glyph edges come out lighter over dark backdrops than a
|
||||
|
||||
@@ -40,6 +40,147 @@ fn normal_layer_over_background() {
|
||||
assert!(close4(px(&d, 5, 1), [1.0; 4]));
|
||||
}
|
||||
|
||||
// The pre-optimisation Normal formula, independent of the production helper. Its operation
|
||||
// order matters: an algebraically equivalent premultiplied mix can round differently.
|
||||
fn original_normal_rgb(backdrop: [f32; 4], source: [f32; 4], opacity: f32) -> [f32; 4] {
|
||||
let ab = backdrop[3];
|
||||
let as_ = source[3] * opacity;
|
||||
if as_ <= 0.0 {
|
||||
return backdrop;
|
||||
}
|
||||
let ao = as_ + ab * (1.0 - as_);
|
||||
if ao <= 0.0 {
|
||||
return [0.0; 4];
|
||||
}
|
||||
let kb = ab * (1.0 - as_);
|
||||
let inv = 1.0 / ao;
|
||||
[(kb * backdrop[0] + as_ * source[0]) * inv, (kb * backdrop[1] + as_ * source[1]) * inv, (kb * backdrop[2] + as_ * source[2]) * inv, ao]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_rgb_kernel_preserves_scalar_bits() {
|
||||
let subnormal = f32::from_bits(1);
|
||||
let backdrops = [[0.0, -0.0, 2.0, 0.0], [0.2, 0.4, 0.6, 0.5], [2.0, -0.25, 4.0, 1.0], [-1.0, 0.01, 1.0, -0.5], [1.0, -0.0, f32::MIN_POSITIVE, subnormal]];
|
||||
let sources = [
|
||||
[0.9, 0.1, 0.3, 1.0],
|
||||
[0.25, 2.0, -1.0, 0.5],
|
||||
[subnormal, 1e-20, 1.0, subnormal],
|
||||
[0.5, 0.2, 0.7, -0.0],
|
||||
[0.5, 0.2, 0.7, -0.5],
|
||||
[f32::NAN, 0.2, 0.7, 0.0],
|
||||
];
|
||||
for b in backdrops {
|
||||
for s in sources {
|
||||
for opacity in [-1.0, -0.0, 0.0, 0.5, 1.0, 2.0] {
|
||||
let want = original_normal_rgb(b, s, opacity);
|
||||
let got = psblend::composite_normal_rgb(b, s, opacity);
|
||||
assert_eq!(got.map(f32::to_bits), want.map(f32::to_bits), "{b:?} / {s:?} / {opacity}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn normal_rgb_test_buffers(fmt: PixelFormat) -> (Buffer, Buffer) {
|
||||
let rect = Rect::new(-3, -2, 5, 0);
|
||||
let mut bottom = Surface::new(fmt);
|
||||
let mut top = Surface::new(fmt);
|
||||
for y in rect.y0..rect.y1 {
|
||||
for x in rect.x0..rect.x1 {
|
||||
let i = ((y - rect.y0) * rect.width() as i32 + x - rect.x0) as usize;
|
||||
let t = i as f32 / 16.0;
|
||||
let b = [2.0 * t, 0.4, -0.25 + t, [0.0, 0.25, 0.75, 1.0][i % 4]];
|
||||
let s = [0.9 - t, 0.1 + t, 0.3, [0.0, -0.0, 0.5, 1.0][i % 4]];
|
||||
bottom.write_pixel(x, y, &photocraft_raster::from_rgba(&fmt, b));
|
||||
top.write_pixel(x, y, &photocraft_raster::from_rgba(&fmt, s));
|
||||
}
|
||||
}
|
||||
(surface_to_buffer(&bottom, rect), surface_to_buffer(&top, rect))
|
||||
}
|
||||
|
||||
// Keep the old buffer dispatch as an oracle for the specialised loop and all of its fallbacks.
|
||||
fn original_blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) {
|
||||
let rect = backdrop.rect;
|
||||
let w = rect.width() as i32;
|
||||
for (i, b) in backdrop.px.iter_mut().enumerate() {
|
||||
let mut s = src.px[i];
|
||||
if s[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let mut mode = mode;
|
||||
if mode == BlendMode::Dissolve {
|
||||
let x = rect.x0 + (i as i32 % w);
|
||||
let y = rect.y0 + (i as i32 / w);
|
||||
s[3] = if dissolve_noise(x, y) < s[3] * opacity { 1.0 } else { 0.0 };
|
||||
mode = BlendMode::Normal;
|
||||
*b = blend::composite(mode, *b, s, 1.0);
|
||||
continue;
|
||||
}
|
||||
*b = blend::composite_gamma(mode, *b, s, opacity, gamma);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_buffer_bits(got: &Buffer, want: &Buffer) {
|
||||
assert_eq!(got.rect, want.rect);
|
||||
assert_eq!(got.px.len(), want.px.len());
|
||||
for (i, (got, want)) in got.px.iter().zip(&want.px).enumerate() {
|
||||
assert_eq!(got.map(f32::to_bits), want.map(f32::to_bits), "pixel {i}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_rgb_buffer_dispatch_and_fallbacks_preserve_bits() {
|
||||
for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] {
|
||||
let (bottom, top) = normal_rgb_test_buffers(fmt);
|
||||
for lab in [false, true] {
|
||||
psblend::with_lab_mix(lab, || {
|
||||
psblend::with_hdr(fmt.sample == SampleType::F32, || {
|
||||
for mode in BlendMode::LAYER_MODES {
|
||||
for gamma in [1.0, psblend::TEXT_GAMMA] {
|
||||
for opacity in [0.0, 0.5, 1.0] {
|
||||
let mut got = bottom.clone();
|
||||
let mut want = bottom.clone();
|
||||
original_blend_into_g(&mut want, &top, mode, opacity, gamma);
|
||||
blend_into_g(&mut got, &top, mode, opacity, gamma);
|
||||
assert_buffer_bits(&got, &want);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_rgb_buffer_preserves_alpha_skip_and_nested_scopes() {
|
||||
let rect = Rect::new(-1, -1, 2, 0);
|
||||
let bottom = Buffer::filled(rect, [-0.0, 0.4, 2.0, 0.75]);
|
||||
let top = Buffer { rect, px: vec![[f32::NAN, 0.3, 0.1, -0.5], [0.2, 0.3, 0.1, -0.0], [0.2, 0.3, 0.1, f32::NAN]] };
|
||||
psblend::with_lab_mix(true, || {
|
||||
psblend::with_hdr(true, || {
|
||||
psblend::with_lab_mix(false, || {
|
||||
psblend::with_hdr(false, || {
|
||||
let mut got = bottom.clone();
|
||||
let mut want = bottom.clone();
|
||||
original_blend_into_g(&mut want, &top, BlendMode::Normal, -1.0, 1.0);
|
||||
blend_into_g(&mut got, &top, BlendMode::Normal, -1.0, 1.0);
|
||||
assert_buffer_bits(&got, &want);
|
||||
assert_eq!(got.px[0].map(f32::to_bits), bottom.px[0].map(f32::to_bits));
|
||||
assert_eq!(got.px[1].map(f32::to_bits), bottom.px[1].map(f32::to_bits));
|
||||
});
|
||||
assert!(psblend::HDR.with(|h| h.get()));
|
||||
});
|
||||
assert!(psblend::LAB_MIX.with(|l| l.get()));
|
||||
assert!(psblend::HDR.with(|h| h.get()));
|
||||
let mut got = bottom.clone();
|
||||
let mut want = bottom.clone();
|
||||
original_blend_into_g(&mut want, &top, BlendMode::Normal, 0.5, 1.0);
|
||||
blend_into_g(&mut got, &top, BlendMode::Normal, 0.5, 1.0);
|
||||
assert_buffer_bits(&got, &want);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opacity_and_fill_multiply() {
|
||||
let mut d = doc_white(4, 4);
|
||||
|
||||
@@ -636,6 +636,13 @@ pub struct Layer {
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
/// Whether the layer has the Background's own properties: an unclipped pixel layer with
|
||||
/// transparency and position locked. Only the bottom layer of a document with them is the
|
||||
/// Background: use [`Document::background`] / [`Document::is_background`] to identify it.
|
||||
pub fn has_background_traits(&self) -> bool {
|
||||
self.locks.transparency && self.locks.position && !self.clipped && matches!(self.content, LayerContent::Raster(_))
|
||||
}
|
||||
|
||||
pub fn new(name: impl Into<String>, content: LayerContent) -> Self {
|
||||
Layer {
|
||||
id: LayerId::fresh(),
|
||||
@@ -1040,6 +1047,25 @@ impl Document {
|
||||
self.path_of(id).map_or_else(Locks::default, |p| self.locks_at(&p))
|
||||
}
|
||||
|
||||
/// The Background layer, identified structurally as Photoshop does, never by its name (a file
|
||||
/// from a German or Japanese Photoshop names it "Hintergrund" or "背景"): the bottom layer of
|
||||
/// the stack, a pixel layer that is not clipped, with transparency and position locked (a PSD
|
||||
/// stores it without a transparency channel and transparency-protected; File › New and opaque
|
||||
/// flat files create it the same way).
|
||||
pub fn background(&self) -> Option<&Layer> {
|
||||
self.layers.first().filter(|l| Layer::has_background_traits(l))
|
||||
}
|
||||
|
||||
/// [`Self::background`], mutably.
|
||||
pub fn background_mut(&mut self) -> Option<&mut Layer> {
|
||||
self.layers.first_mut().filter(|l| Layer::has_background_traits(l))
|
||||
}
|
||||
|
||||
/// Whether `id` is the document's Background layer ([`Self::background`]).
|
||||
pub fn is_background(&self, id: LayerId) -> bool {
|
||||
self.background().is_some_and(|b| b.id == id)
|
||||
}
|
||||
|
||||
pub fn layer(&self, id: LayerId) -> Option<&Layer> {
|
||||
fn rec(layers: &[Layer], id: LayerId) -> Option<&Layer> {
|
||||
layers.iter().find_map(|l| if l.id == id { Some(l) } else { l.children().and_then(|ch| rec(ch, id)) })
|
||||
@@ -1205,6 +1231,30 @@ mod tests {
|
||||
assert_eq!(s.pixel(100, 0), vec![0.0; 4]);
|
||||
}
|
||||
|
||||
/// The Background is the locked bottom pixel layer, whatever it is called.
|
||||
#[test]
|
||||
fn background_is_structural_not_named() {
|
||||
let mut d = doc();
|
||||
let id = d.layers[0].id;
|
||||
assert!(d.is_background(id));
|
||||
for name in ["Hintergrund", "背景", "Arrière-plan"] {
|
||||
d.layers[0].name = name.into();
|
||||
assert_eq!(d.background().map(|l| l.id), Some(id), "{name}");
|
||||
}
|
||||
// A layer called "Background" without the locks, or above the bottom, is not it.
|
||||
let mut top = Layer::raster("Background", d.pixel_format());
|
||||
top.locks.transparency = true;
|
||||
top.locks.position = true;
|
||||
let top_id = top.id;
|
||||
d.layers.push(top);
|
||||
assert!(!d.is_background(top_id));
|
||||
d.layers[0].locks.position = false;
|
||||
assert!(d.background().is_none());
|
||||
d.layers[0].locks.position = true;
|
||||
d.layers[0].clipped = true;
|
||||
assert!(d.background_mut().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_group_depth_counts_nesting_without_recursing() {
|
||||
let mut d = doc();
|
||||
|
||||
@@ -428,6 +428,7 @@ fn hdr_toning(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let data: Vec<f32> = px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect();
|
||||
let mut bg = Layer::raster("Background", fmt);
|
||||
bg.locks.transparency = true;
|
||||
bg.locks.position = true;
|
||||
crate::pixels_mut(&mut bg)?.write_region(doc.bounds(), &data);
|
||||
*active = Some(bg.id);
|
||||
doc.layers = vec![bg];
|
||||
|
||||
@@ -670,7 +670,7 @@ fn straighten(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({"angle": 0.0}));
|
||||
}
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let active_bg = st.active_layer.and_then(|id| d.layer(id)).is_some_and(|l| l.name == "Background" && l.locks.position);
|
||||
let active_bg = st.active_layer.and_then(|id| d.layer(id)).is_some_and(|l| d.is_background(l.id));
|
||||
let crop = p.get("crop").and_then(Value::as_bool).unwrap_or(active_bg || st.active_layer.is_none());
|
||||
let (w0, h0) = (f64::from(d.size.width), f64::from(d.size.height));
|
||||
compound(s, "Straighten", |s| {
|
||||
|
||||
@@ -10,14 +10,13 @@ use photocraft_doc::{Document, Layer, LayerContent, LayerId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::commands::CommandSpec;
|
||||
use crate::extra_cmds::is_background;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const CMD: &str = "layer.new.backgroundFromLayer";
|
||||
|
||||
/// The document's Background layer, if it has one (always the bottom layer).
|
||||
pub(crate) fn background_id(doc: &Document) -> Option<LayerId> {
|
||||
doc.layers.first().filter(|l| is_background(l)).map(|l| l.id)
|
||||
doc.background().map(|l| l.id)
|
||||
}
|
||||
|
||||
/// Refuses an edit that moved the Background `bg` (taken before the edit) off the bottom of the
|
||||
@@ -155,7 +154,7 @@ mod tests {
|
||||
assert_eq!(s.execute(CMD, json!({})).unwrap()["layer"], a.0);
|
||||
assert_eq!(order(&s), [a, l0, b], "{depth}: drops to the bottom");
|
||||
let l = &doc(&s).layers[0];
|
||||
assert!(is_background(l) && l.name == "Background", "{depth}");
|
||||
assert!(doc(&s).is_background(l.id) && l.name == "Background", "{depth}");
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(a));
|
||||
// Its pixels stay; transparency takes the background colour (blue).
|
||||
let red = pixel(&s, 3, 3);
|
||||
@@ -170,10 +169,10 @@ mod tests {
|
||||
assert!(s.undo());
|
||||
assert_eq!(order(&s), [l0, a, b], "{depth}");
|
||||
let l = doc(&s).layer(a).unwrap();
|
||||
assert!(!is_background(l) && l.name == "A");
|
||||
assert!(!doc(&s).is_background(l.id) && l.name == "A");
|
||||
assert!(s.redo());
|
||||
assert_eq!(order(&s), [a, l0, b], "{depth}");
|
||||
assert!(is_background(&doc(&s).layers[0]));
|
||||
assert!(doc(&s).is_background(doc(&s).layers[0].id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,7 +190,7 @@ mod tests {
|
||||
assert_eq!(d.layers[1].id, l0);
|
||||
assert_eq!(d.layers[2].id, a);
|
||||
let bg = &d.layers[0];
|
||||
assert!(is_background(bg) && !bg.visible, "visibility is kept");
|
||||
assert!(d.is_background(bg.id) && !bg.visible, "visibility is kept");
|
||||
assert_eq!(bg.opacity, 1.0);
|
||||
}
|
||||
|
||||
@@ -211,7 +210,7 @@ mod tests {
|
||||
for p in [json!({"layer": "A"}), json!({"layer": -1}), json!({"layer": 1.5}), json!({"layer": 99999}), json!({"layer": [a.0]})] {
|
||||
assert!(s.execute(CMD, p.clone()).is_err(), "{p}");
|
||||
}
|
||||
assert!(!doc(&s).layers.iter().any(is_background));
|
||||
assert!(doc(&s).background().is_none());
|
||||
// A group or an adjustment layer can't become the Background.
|
||||
s.execute("layer.select", json!({"layer": a.0})).unwrap();
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
@@ -220,7 +219,7 @@ mod tests {
|
||||
s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap();
|
||||
assert!(!s.is_enabled(CMD));
|
||||
assert!(s.execute(CMD, json!({})).is_err());
|
||||
assert!(!doc(&s).layers.iter().any(is_background));
|
||||
assert!(doc(&s).background().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1804,6 +1804,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
journal: false,
|
||||
},
|
||||
spec!("channel.target.composite", "Target Composite Channel", [], Some("Cmd+2"), "{}", has_doc, |s, _| target_slot(s, 2)),
|
||||
// ⌘\ targets the active layer's mask, as clicking its thumbnail does.
|
||||
spec!("channel.target.layerMask", "Target Layer Mask", [], Some("Cmd+\\"), "{}", has_layer_mask, |s, _| target_cmd(
|
||||
s,
|
||||
&serde_json::json!({"channel": "mask"})
|
||||
)),
|
||||
// ⌘⌥2 loads the image's luminosity as a selection (⌘-click on the composite channel).
|
||||
spec!("select.loadLuminosity", "Load Luminosity", [], Some("Cmd+Alt+2"), "{}", has_doc, |s, _| load_selection(
|
||||
s,
|
||||
&serde_json::json!({"channel": "composite"})
|
||||
)),
|
||||
spec!("channel.target.slot3", "Target Channel 3", [], Some("Cmd+3"), "{}", slot_ok::<3>, |s, _| target_slot(s, 3)),
|
||||
spec!("channel.target.slot4", "Target Channel 4", [], Some("Cmd+4"), "{}", slot_ok::<4>, |s, _| target_slot(s, 4)),
|
||||
spec!("channel.target.slot5", "Target Channel 5", [], Some("Cmd+5"), "{}", slot_ok::<5>, |s, _| target_slot(s, 5)),
|
||||
@@ -1814,6 +1824,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Target Layer Mask: the active layer has a mask.
|
||||
fn has_layer_mask(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
let layer = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("no active layer")?;
|
||||
layer.mask.as_ref().map(|_| ()).ok_or_else(|| "the active layer has no layer mask".to_string())
|
||||
}
|
||||
|
||||
fn slot_ok<const N: usize>(s: &Session) -> std::result::Result<(), String> {
|
||||
let d = s.active().ok_or("no document open")?;
|
||||
let colors = color_count(&d.doc);
|
||||
|
||||
@@ -741,6 +741,33 @@ fn clear_with_an_alpha_channel_or_quick_mask_targeted_fills_it_not_the_layer() {
|
||||
assert_eq!(px(&s, 5, 5), layer, "the layer is untouched in Quick Mask mode");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_backslash_targets_the_layer_mask_and_command_2_the_composite() {
|
||||
let mut s = session();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
assert!(!s.is_enabled("channel.target.layerMask"), "no mask yet");
|
||||
assert!(s.execute("channel.target.layerMask", json!({})).is_err());
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
s.execute("channel.target.composite", json!({})).unwrap();
|
||||
assert_eq!(crate::commands::find("channel.target.layerMask").and_then(|c| c.shortcut), Some("Cmd+\\"));
|
||||
s.execute("channel.target.layerMask", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().channel_view.target, ChannelTarget::LayerMask);
|
||||
s.execute("channel.target.composite", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().channel_view.target, ChannelTarget::Composite);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_alt_2_loads_the_images_luminosity() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0, 0, 20, 20, "replace");
|
||||
s.execute("edit.fill", json!({"contents": "black"})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
assert_eq!(crate::commands::find("select.loadLuminosity").and_then(|c| c.shortcut), Some("Cmd+Alt+2"));
|
||||
s.execute("select.loadLuminosity", json!({})).unwrap();
|
||||
assert!(sel_at(&s, 5, 5) < 0.01, "black: unselected");
|
||||
assert!(sel_at(&s, 30, 5) > 0.99, "white: selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thumbnail_selection_shape_without_pixel_cache_uses_its_transparency() {
|
||||
for depth in [8, 16, 32] {
|
||||
|
||||
@@ -92,7 +92,7 @@ fn enabled(s: &Session) -> std::result::Result<(), String> {
|
||||
if locks.pixels || locks.all {
|
||||
return Err(format!("the layer \"{}\" is locked", l.name));
|
||||
}
|
||||
if locks.transparency && !crate::extra_cmds::is_background(l) {
|
||||
if locks.transparency && !d.doc.is_background(l.id) {
|
||||
return Err(format!("the transparency of layer \"{}\" is locked", l.name));
|
||||
}
|
||||
Ok(())
|
||||
@@ -217,7 +217,7 @@ mod tests {
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(name(&s), "Background");
|
||||
let d = s.active().unwrap();
|
||||
assert!(crate::extra_cmds::is_background(d.doc.layer(d.active_layer.unwrap()).unwrap()));
|
||||
assert!(d.doc.is_background(d.active_layer.unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -136,6 +136,19 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
®istry().specs
|
||||
}
|
||||
|
||||
/// One `command.list` / `engine.commands` row for `c`, given why it can't run now (`None` = it can).
|
||||
/// `disabledReason` is that message; `needsDocument` is true when the reason is that no document is
|
||||
/// open (#3664), so an agent can tell "open or create a document first" from a precondition that a
|
||||
/// document alone won't meet (a selection, an empty clipboard).
|
||||
pub fn list_entry(s: &Session, c: &CommandSpec, reason: Option<String>) -> Value {
|
||||
let needs_document =
|
||||
s.active().is_none() && reason.as_deref().is_some_and(|r| ["no document", "no active document", "no open document"].iter().any(|p| r.starts_with(p)));
|
||||
json!({
|
||||
"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params,
|
||||
"enabled": reason.is_none(), "disabledReason": reason, "needsDocument": needs_document,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn find(id: &str) -> Option<&'static CommandSpec> {
|
||||
let registry = registry();
|
||||
registry.by_id.get(id).and_then(|&index| registry.specs.get(index))
|
||||
@@ -1014,18 +1027,7 @@ fn build() -> Vec<CommandSpec> {
|
||||
shortcut: None,
|
||||
params: "{}",
|
||||
enabled: always,
|
||||
run: |s, _| {
|
||||
Ok(Value::Array(
|
||||
command_specs()
|
||||
.iter()
|
||||
.map(|c| {
|
||||
json!({
|
||||
"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params, "enabled": (c.enabled)(s).is_ok(),
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
},
|
||||
run: |s, _| Ok(Value::Array(command_specs().iter().map(|c| list_entry(s, c, (c.enabled)(s).err())).collect())),
|
||||
journal: false,
|
||||
},
|
||||
CommandSpec {
|
||||
@@ -1416,7 +1418,7 @@ pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) {
|
||||
pub(crate) fn layer_copy(doc: &Document, id: LayerId) -> Result<Layer> {
|
||||
let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
// A copy of the Background layer is an ordinary, unlocked layer (Photoshop).
|
||||
let from_background = src.name == "Background" && src.locks.transparency && doc.layers.first().is_some_and(|b| b.id == id);
|
||||
let from_background = doc.is_background(id);
|
||||
let mut dup = src.duplicate();
|
||||
dup.name = doc.copy_name(&dup.name);
|
||||
if from_background {
|
||||
|
||||
@@ -213,15 +213,6 @@ fn smart_layer(s: &Session) -> std::result::Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unlocks a Background layer for an operation that exposes transparency (as Photoshop does).
|
||||
fn float_background(l: &mut Layer) {
|
||||
if l.locks.position && l.name == "Background" {
|
||||
l.locks.position = false;
|
||||
l.locks.transparency = false;
|
||||
l.name = "Layer 0".into();
|
||||
}
|
||||
}
|
||||
|
||||
fn check_locks(l: &Layer, group: Locks, position: bool) -> Result<()> {
|
||||
let locks = l.locks.union(group);
|
||||
if locks.all || locks.pixels || (position && locks.position) {
|
||||
@@ -247,14 +238,15 @@ fn run_on_layer(s: &mut Session, cmd: &str, label: &str, p: &Value, moves: bool,
|
||||
let canvas = doc.bounds();
|
||||
let selection = doc.selection.clone();
|
||||
let group = crate::transform_cmds::group_locks(doc, id);
|
||||
// A Background gains transparency when the distortion moves pixels (as in Photoshop).
|
||||
if moves {
|
||||
crate::extra_cmds::background_to_layer(doc, id);
|
||||
}
|
||||
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
if let LayerContent::Smart(_) = l.content {
|
||||
let sf = SmartFilter { command: cmd.to_string(), params: params.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true };
|
||||
return crate::smart_cmds::add_smart_filter(doc, id, sf, selection.as_ref());
|
||||
}
|
||||
if moves {
|
||||
float_background(l);
|
||||
}
|
||||
check_locks(l, group, moves)?;
|
||||
let LayerContent::Raster(surf) = &mut l.content else {
|
||||
return Err(EngineError::Other(format!("{label} needs a pixel layer (rasterize it first)")));
|
||||
|
||||
@@ -82,7 +82,7 @@ fn whole_layers(d: &crate::DocState, ids: &[LayerId]) -> Option<Box<Document>> {
|
||||
let mut copies = scratch_doc(&d.doc);
|
||||
for id in ids {
|
||||
let mut l = d.doc.layer(*id)?.clone();
|
||||
if crate::extra_cmds::is_background(&l) {
|
||||
if d.doc.is_background(*id) {
|
||||
l.name = "Layer 0".into();
|
||||
l.locks = Default::default();
|
||||
}
|
||||
@@ -277,7 +277,8 @@ fn clear_selected(doc: &mut Document, id: LayerId, background: [f32; 4]) -> Resu
|
||||
/// Cut / Clear on a layer: makes the selected pixels transparent. The Background can't hold
|
||||
/// transparency, so there the area is filled with the background colour instead (Photoshop).
|
||||
pub(crate) fn clear_area(doc: &mut Document, id: LayerId, area: Rect, sel: Option<&Surface>, background: [f32; 4]) -> Result<()> {
|
||||
let bg = crate::extra_cmds::is_background(doc.layer(id).ok_or(EngineError::NoLayer(id))?);
|
||||
doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
let bg = doc.is_background(id);
|
||||
let surf = crate::commands::paint_surface(doc, id, &Value::Null)?;
|
||||
if bg {
|
||||
crate::pixels::try_fill_surface(surf, area, background, sel, true)?;
|
||||
@@ -461,7 +462,7 @@ fn merge_visible(s: &mut Session) -> Result<Value> {
|
||||
}
|
||||
let lowest = visible[0];
|
||||
let base = doc.layers[lowest].clone();
|
||||
let is_background = base.name == "Background" && base.locks.transparency;
|
||||
let is_background = lowest == 0 && doc.is_background(base.id);
|
||||
// Composite of visible layers only (hidden ones stay where they are).
|
||||
let mut solo = doc.clone();
|
||||
solo.layers.retain(|l| l.visible);
|
||||
@@ -1363,7 +1364,7 @@ mod tests {
|
||||
let mut s = fresh();
|
||||
s.execute(cmd, json!({})).unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(crate::extra_cmds::is_background(&d.layers[0]), "{cmd}: still the Background");
|
||||
assert!(d.is_background(d.layers[0].id), "{cmd}: still the Background");
|
||||
assert_eq!(px(&s, 0, 8, 8), vec![1.0, 0.0, 0.0, 1.0], "{cmd}: cut area is the background colour");
|
||||
assert_eq!(px(&s, 0, 30, 20), vec![1.0, 1.0, 1.0, 1.0], "{cmd}: outside untouched");
|
||||
}
|
||||
@@ -1609,9 +1610,9 @@ mod tests {
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.doc.layers.len(), 4);
|
||||
let pasted = &st.doc.layers[st.doc.layers.len() - 2];
|
||||
assert!(!crate::extra_cmds::is_background(pasted));
|
||||
assert!(!st.doc.is_background(pasted.id));
|
||||
assert_eq!(pasted.locks, Default::default());
|
||||
assert!(crate::extra_cmds::is_background(&st.doc.layers[0]), "the real Background is untouched");
|
||||
assert!(st.doc.is_background(st.doc.layers[0].id), "the real Background is untouched");
|
||||
}
|
||||
|
||||
/// #2428: a smart object copied in one document pastes into another as a smart object, in
|
||||
|
||||
@@ -59,19 +59,6 @@ fn active_pixel_layer(s: &Session, cmd: &str) -> Result<LayerId> {
|
||||
s.active().and_then(|d| d.active_layer).ok_or_else(|| bad(cmd, "no active layer"))
|
||||
}
|
||||
|
||||
fn is_background(l: &Layer) -> bool {
|
||||
l.name == "Background" && l.locks.transparency && l.locks.position && matches!(l.content, LayerContent::Raster(_))
|
||||
}
|
||||
|
||||
/// Photoshop converts the Background to a normal layer before erasing to transparency.
|
||||
fn unlock_background(l: &mut Layer) {
|
||||
if is_background(l) {
|
||||
l.name = "Layer 0".into();
|
||||
l.locks.transparency = false;
|
||||
l.locks.position = false;
|
||||
}
|
||||
}
|
||||
|
||||
fn pixels_locked(doc: &Document, l: &Layer) -> Option<EngineError> {
|
||||
let locks = doc.effective_locks(l.id);
|
||||
(locks.pixels || locks.all).then(|| EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name)))
|
||||
@@ -114,7 +101,9 @@ fn magic_eraser(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bg = s.tools.background;
|
||||
let dmg = s.edit("Magic Eraser", |doc, _| {
|
||||
let selection = doc.selection.clone();
|
||||
unlock_background(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?);
|
||||
// Photoshop converts the Background to a normal layer before erasing to transparency.
|
||||
doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
crate::extra_cmds::background_to_layer(doc, id);
|
||||
let lock = doc.effective_locks(id).transparency;
|
||||
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
let surf = l.surface_mut().ok_or_else(|| bad(CMD, "not a pixel layer"))?;
|
||||
@@ -149,15 +138,15 @@ fn background_eraser(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(e) = pixels_locked(&d.doc, l) {
|
||||
return Err(e);
|
||||
}
|
||||
if d.doc.effective_locks(id).transparency && !is_background(l) {
|
||||
if d.doc.effective_locks(id).transparency && !d.doc.is_background(id) {
|
||||
return Err(EngineError::Other(format!("Could not use the Background Eraser because the transparency of layer \"{}\" is locked", l.name)));
|
||||
}
|
||||
}
|
||||
let stroke = Stroke { brush, points: pts };
|
||||
let dmg = s.edit("Background Eraser", |doc, _| {
|
||||
let selection = doc.selection.clone();
|
||||
crate::extra_cmds::background_to_layer(doc, id);
|
||||
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
unlock_background(l);
|
||||
let surf = l.surface_mut().ok_or_else(|| bad(CMD, "not a pixel layer"))?;
|
||||
Ok(apply_background_eraser(surf, &stroke, &bs, selection.as_ref()))
|
||||
})?;
|
||||
|
||||
@@ -43,13 +43,9 @@ fn has_clip_and_selection(s: &Session) -> std::result::Result<(), String> {
|
||||
d.doc.selection.as_ref().map(|_| ()).ok_or_else(|| "Paste Into needs a selection".into())
|
||||
}
|
||||
|
||||
pub(crate) fn is_background(l: &Layer) -> bool {
|
||||
l.name == "Background" && l.locks.transparency && l.locks.position && matches!(l.content, LayerContent::Raster(_))
|
||||
}
|
||||
|
||||
fn has_background(s: &Session) -> std::result::Result<(), String> {
|
||||
let d = s.active().ok_or("no document open")?;
|
||||
d.doc.layers.first().filter(|l| is_background(l)).map(|_| ()).ok_or_else(|| "the document has no Background layer".into())
|
||||
d.doc.background().map(|_| ()).ok_or_else(|| "the document has no Background layer".into())
|
||||
}
|
||||
|
||||
/// The layers a layer-style command acts on: as [`crate::layer_multi_cmds::targets`], but with
|
||||
@@ -60,7 +56,7 @@ pub(crate) fn style_targets(s: &Session, p: &Value, fits: impl Fn(&Layer) -> boo
|
||||
return Ok(ids);
|
||||
}
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let ids: Vec<LayerId> = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| !is_background(l) && fits(l))).collect();
|
||||
let ids: Vec<LayerId> = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| !d.doc.is_background(l.id) && fits(l))).collect();
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("none of the selected layers can take this layer style change".into()));
|
||||
}
|
||||
@@ -441,7 +437,7 @@ pub fn reveal_all_bounds(doc: &Document) -> Rect {
|
||||
|
||||
fn layer_from_background(s: &mut Session) -> Result<Value> {
|
||||
let id = s.edit("Layer From Background", |doc, active| {
|
||||
let l = doc.layers.first_mut().filter(|l| is_background(l)).ok_or(EngineError::Other("the document has no Background layer".into()))?;
|
||||
let l = doc.background_mut().ok_or(EngineError::Other("the document has no Background layer".into()))?;
|
||||
unlock_background(l);
|
||||
*active = Some(l.id);
|
||||
Ok(l.id)
|
||||
@@ -458,7 +454,14 @@ pub(crate) fn unlock_background(l: &mut Layer) {
|
||||
/// Before `id` gets a layer mask: the Background can't have one, so it becomes a normal layer
|
||||
/// first ("Layer 0"), as when adding a mask to it in Photoshop. Other layers are left alone.
|
||||
pub(crate) fn background_to_layer_for_mask(doc: &mut photocraft_doc::Document, id: photocraft_doc::LayerId) {
|
||||
if let Some(l) = doc.layers.first_mut().filter(|l| l.id == id && is_background(l)) {
|
||||
background_to_layer(doc, id);
|
||||
}
|
||||
|
||||
/// If `id` is the Background ([`photocraft_doc::Document::background`], whatever its name), turns
|
||||
/// it into a normal layer ("Layer 0"), as Photoshop does before an edit the Background can't
|
||||
/// take (moving, transforming, exposing transparency, a style). Other layers are left alone.
|
||||
pub(crate) fn background_to_layer(doc: &mut photocraft_doc::Document, id: photocraft_doc::LayerId) {
|
||||
if let Some(l) = doc.background_mut().filter(|l| l.id == id) {
|
||||
unlock_background(l);
|
||||
}
|
||||
}
|
||||
@@ -563,6 +566,35 @@ fn set_visible(s: &mut Session, p: &Value, visible: bool) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Layer › Hide Layers (⌘,): hide the targeted layers, or show them when every one is already
|
||||
/// hidden, as Photoshop's item does (it reads Show Layers then), so ⌘, toggles.
|
||||
fn hide_or_show(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let targets = if crate::layer_multi_cmds::multi(s, p) { crate::layer_multi_cmds::selected(s) } else { vec![layer_param(s, p)?] };
|
||||
let all_hidden = targets.iter().all(|id| st.doc.layer(*id).is_some_and(|l| !l.visible));
|
||||
set_visible(s, p, all_hidden)
|
||||
}
|
||||
|
||||
/// `/`: Lock Transparent Pixels on or off for the targeted layers, as the Layers panel's first lock
|
||||
/// button does. With several layers targeted, any unlocked one means lock them all. The
|
||||
/// Background, which can't take this lock, is left out.
|
||||
fn toggle_lock_transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let targets: Vec<LayerId> = if crate::layer_multi_cmds::multi(s, p) { crate::layer_multi_cmds::selected(s) } else { vec![layer_param(s, p)?] };
|
||||
let targets: Vec<LayerId> = targets.into_iter().filter(|id| st.doc.layer(*id).is_some_and(|l| !st.doc.is_background(l.id))).collect();
|
||||
if targets.is_empty() {
|
||||
return Err(EngineError::Other("the Background layer can't lock transparent pixels".into()));
|
||||
}
|
||||
let lock = !targets.iter().all(|id| st.doc.layer(*id).is_some_and(|l| l.locks.transparency));
|
||||
s.edit(if lock { "Lock Transparent Pixels" } else { "Unlock Transparent Pixels" }, |doc, _| {
|
||||
for id in &targets {
|
||||
doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.locks.transparency = lock;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"locked": lock}))
|
||||
}
|
||||
|
||||
/// Is the layer at `path` shown alone: it and its enclosing groups visible, every layer outside
|
||||
/// it hidden (the layers inside a group keep their own visibility)?
|
||||
fn shown_alone(doc: &Document, path: &[usize]) -> bool {
|
||||
@@ -913,8 +945,25 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
},
|
||||
ungroup
|
||||
),
|
||||
spec!("layer.hideLayers", "Hide Layers", &["Layer"], Some("Cmd+,"), r##"{"layer":id?}"##, has_layer, |s, p| set_visible(s, p, false)),
|
||||
spec!(
|
||||
"layer.hideLayers",
|
||||
"Hide Layers",
|
||||
&["Layer"],
|
||||
Some("Cmd+,"),
|
||||
r##"{"layer":id?} (shows them instead when every targeted layer is already hidden, so ⌘, toggles)"##,
|
||||
has_layer,
|
||||
hide_or_show
|
||||
),
|
||||
spec!("layer.showLayers", "Show Layers", &[], None, r##"{"layer":id?}"##, has_layer, |s, p| set_visible(s, p, true)),
|
||||
spec!(
|
||||
"layer.toggleLockTransparency",
|
||||
"Lock Transparent Pixels",
|
||||
&[],
|
||||
Some("/"),
|
||||
r##"{"layer":id?} (toggles; several layers selected: locks them all unless every one is locked)"##,
|
||||
has_layer,
|
||||
toggle_lock_transparency
|
||||
),
|
||||
spec!(
|
||||
"layer.showOnly",
|
||||
"Show Only This Layer",
|
||||
@@ -1493,6 +1542,48 @@ mod tests {
|
||||
assert_eq!(doc(&s).layers[0].name, "Background");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_layers_toggles_once_every_target_is_hidden() {
|
||||
let mut s = session(8);
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
let b = active(&s).id;
|
||||
let visible = |s: &Session| doc(s).layer(b).unwrap().visible;
|
||||
// Select › All Layers leaves out the Background, as in Photoshop.
|
||||
let all = |s: &Session| crate::layer_multi_cmds::selected(s).iter().map(|id| doc(s).layer(*id).unwrap().visible).collect::<Vec<_>>();
|
||||
s.execute("layer.hideLayers", json!({})).unwrap();
|
||||
assert!(!visible(&s));
|
||||
s.execute("layer.hideLayers", json!({})).unwrap();
|
||||
assert!(visible(&s), "⌘, again shows it");
|
||||
// Several selected: any one still shown means hide them all; then they all come back.
|
||||
s.execute("layer.hideLayers", json!({"layer": b.0})).unwrap();
|
||||
s.execute("select.allLayers", json!({})).unwrap();
|
||||
assert!(all(&s).len() > 1);
|
||||
s.execute("layer.hideLayers", json!({})).unwrap();
|
||||
assert!(all(&s).iter().all(|v| !v));
|
||||
s.execute("layer.hideLayers", json!({})).unwrap();
|
||||
assert!(all(&s).iter().all(|v| *v));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slash_toggles_lock_transparent_pixels_but_not_on_the_background() {
|
||||
let mut s = session(8);
|
||||
let bg = doc(&s).layers[0].id;
|
||||
assert!(doc(&s).is_background(bg));
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
let top = active(&s).id;
|
||||
let locked = |s: &Session, id: LayerId| doc(s).layer(id).unwrap().locks.transparency;
|
||||
assert_eq!(s.execute("layer.toggleLockTransparency", json!({})).unwrap()["locked"], true);
|
||||
assert!(locked(&s, top));
|
||||
s.execute("layer.toggleLockTransparency", json!({})).unwrap();
|
||||
assert!(!locked(&s, top));
|
||||
s.undo();
|
||||
assert!(locked(&s, top), "one undoable step each");
|
||||
let bg_locks = doc(&s).layer(bg).unwrap().locks;
|
||||
assert!(s.execute("layer.toggleLockTransparency", json!({"layer": bg.0})).is_err());
|
||||
assert_eq!(doc(&s).layer(bg).unwrap().locks, bg_locks, "the Background is left alone");
|
||||
assert!(s.execute("layer.toggleLockTransparency", json!({"layer": 999_999})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_utilities() {
|
||||
let mut s = session(8);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Photoshop's fill keys (#249): ⌥⌫ fills the selection (or the whole layer) with the foreground
|
||||
//! colour, ⌘⌫ with the background colour, and with ⇧ added they preserve transparency. Photoshop
|
||||
//! colour, ⌘⌫ with the background colour, and with ⇧ added they preserve transparency. ⌘⌥⌫ fills
|
||||
//! from history: the History Brush's source state (the oldest state still held). Photoshop
|
||||
//! has no menu item for them; here they are ordinary commands with default shortcuts, so they
|
||||
//! appear in Edit › Keyboard Shortcuts (Tools) and can be rebound, recorded and driven by agents.
|
||||
//!
|
||||
@@ -12,7 +13,7 @@ use crate::commands::CommandSpec;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// The fill-key command ids (routed to the Channels panel target like `edit.fill`).
|
||||
pub const IDS: [&str; 4] = ["edit.fillForeground", "edit.fillBackground", "edit.fillForegroundPreserve", "edit.fillBackgroundPreserve"];
|
||||
pub const IDS: [&str; 5] = ["edit.fillForeground", "edit.fillBackground", "edit.fillForegroundPreserve", "edit.fillBackgroundPreserve", "edit.fillHistory"];
|
||||
|
||||
const PARAMS: &str = r##"{"layer":id?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?}"##;
|
||||
|
||||
@@ -39,6 +40,22 @@ fn fill(s: &mut Session, p: &Value, cmd: &str, background: bool, preserve: bool)
|
||||
(edit_fill.run)(s, &Value::Object(q))
|
||||
}
|
||||
|
||||
/// ⌘⌥⌫: `edit.fill` from history, the History Brush's source unless `state` names another.
|
||||
fn fill_history(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "edit.fillHistory";
|
||||
let mut q: Map<String, Value> = match p {
|
||||
Value::Object(m) => m.clone(),
|
||||
Value::Null => Map::new(),
|
||||
_ => return Err(EngineError::BadParams { cmd: CMD.into(), msg: "expected an object".into() }),
|
||||
};
|
||||
for k in ["color", "contents", "pattern"] {
|
||||
q.remove(k);
|
||||
}
|
||||
q.insert("contents".into(), json!("history"));
|
||||
let edit_fill = crate::commands::find("edit.fill").ok_or_else(|| EngineError::Other("Fill is unavailable".into()))?;
|
||||
(edit_fill.run)(s, &Value::Object(q))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec {
|
||||
@@ -81,6 +98,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
run: |s, p| fill(s, p, "edit.fillBackgroundPreserve", true, true),
|
||||
journal: true,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "edit.fillHistory",
|
||||
label: "Fill from History",
|
||||
menu: &[],
|
||||
shortcut: Some("Cmd+Alt+Backspace"),
|
||||
params: r##"{"state":n? (default: the History Brush's source, the oldest state still held),"layer":id?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?,"preserveTransparency":bool?}"##,
|
||||
enabled,
|
||||
run: fill_history,
|
||||
journal: true,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
@@ -133,6 +160,27 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_from_history_restores_the_history_brush_source_in_the_selection() {
|
||||
let mut s = session();
|
||||
assert_eq!(crate::commands::find("edit.fillHistory").and_then(|c| c.shortcut), Some("Cmd+Alt+Backspace"));
|
||||
s.execute("edit.fillForeground", json!({})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 6})).unwrap();
|
||||
s.execute("edit.fillHistory", json!({})).unwrap();
|
||||
// The oldest state (the new, transparent layer) comes back inside the selection only.
|
||||
assert_eq!(px(&s, 1, 1)[3], 0.0);
|
||||
assert_eq!(px(&s, 6, 1), [1.0, 0.0, 0.0, 1.0]);
|
||||
// A named state, and refused ones change nothing.
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
for bad in [json!({"state": 99}), json!({"state": "x"}), json!(7)] {
|
||||
assert!(s.execute("edit.fillHistory", bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.active().unwrap().history.past_len(), steps);
|
||||
s.execute("edit.fillHistory", json!({"state": 1})).unwrap();
|
||||
assert_eq!(px(&s, 1, 1), [1.0, 0.0, 0.0, 1.0], "state 1 is after the foreground fill");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_fills_only_the_selection() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -58,7 +58,7 @@ impl CutParts {
|
||||
// A mask has no alpha: it keeps its format, and the cut leaves background colour.
|
||||
let mut rest = if mask { surf.clone() } else { full.clone() };
|
||||
let mut piece = Surface::new(with_alpha);
|
||||
let fill = !copy && (mask || crate::extra_cmds::is_background(l));
|
||||
let fill = !copy && (mask || doc.is_background(layer));
|
||||
// A mask's untouched pixels (its default, e.g. white) move too, so take the whole canvas.
|
||||
let b = sel.content_bounds().intersect(&if mask { doc.bounds() } else { surf.content_bounds() });
|
||||
if !b.is_empty() {
|
||||
@@ -165,7 +165,7 @@ fn can_float(s: &Session) -> std::result::Result<(), String> {
|
||||
/// floating? The Background is position-locked, but its selected pixels move (Photoshop).
|
||||
pub fn locked_for_float(doc: &Document, l: &photocraft_doc::Layer) -> bool {
|
||||
let locks = doc.effective_locks(l.id);
|
||||
locks.all || (locks.position && !crate::extra_cmds::is_background(l))
|
||||
locks.all || (locks.position && !doc.is_background(l.id))
|
||||
}
|
||||
|
||||
fn float(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -137,7 +137,7 @@ fn new_frame(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let gid = match content {
|
||||
Some(id) => {
|
||||
let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
if !matches!(l.content, LayerContent::Raster(_)) || crate::extra_cmds::is_background(l) {
|
||||
if !matches!(l.content, LayerContent::Raster(_)) || doc.is_background(id) {
|
||||
return Err(bad("only a pixel layer (not the Background) can go in a frame".into()));
|
||||
}
|
||||
let gid = doc.insert_above(Some(id), Layer::group(name, vec![]));
|
||||
|
||||
@@ -199,8 +199,39 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> {
|
||||
s.active().map(|_| ()).ok_or_else(|| "no document open".into())
|
||||
}
|
||||
|
||||
/// `history.undo` / `history.redo` enable predicates, matching `edit.undo` / `edit.redo`.
|
||||
fn can_undo(s: &Session) -> std::result::Result<(), String> {
|
||||
s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to undo".into())
|
||||
}
|
||||
|
||||
fn can_redo(s: &Session) -> std::result::Result<(), String> {
|
||||
s.active().filter(|d| d.history.can_redo()).map(|_| ()).ok_or_else(|| "nothing to redo".into())
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
// `history.*` aliases of Edit › Undo / Redo, so a client reaching for the History namespace
|
||||
// finds them (`edit.undo` / `edit.redo` remain the menu items and own the shortcuts, #3675).
|
||||
CommandSpec {
|
||||
id: "history.undo",
|
||||
label: "Undo",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: "{} (the same action as `edit.undo`)",
|
||||
enabled: can_undo,
|
||||
run: |s, _| Ok(json!(s.undo())),
|
||||
journal: false,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "history.redo",
|
||||
label: "Redo",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: "{} (the same action as `edit.redo`)",
|
||||
enabled: can_redo,
|
||||
run: |s, _| Ok(json!(s.redo())),
|
||||
journal: false,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "history.deleteState",
|
||||
label: "Delete State",
|
||||
@@ -282,6 +313,16 @@ mod tests {
|
||||
s.active().unwrap().history.entries()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_undo_and_redo_alias_edit_undo_and_redo() {
|
||||
let mut s = session();
|
||||
let n = s.active().unwrap().history.past_len();
|
||||
s.execute("history.undo", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len(), n - 1, "history.undo steps back like edit.undo");
|
||||
s.execute("history.redo", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len(), n, "history.redo steps forward like edit.redo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_current_state_steps_back_and_drops_it() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -300,7 +300,7 @@ fn crop_doc(doc: &mut Document, cmd: &str, r: Rect, delete_pixels: bool, extensi
|
||||
// A Background cannot hold transparent pixels: like an opaque Canvas Size extension, the area
|
||||
// an extending Crop adds is filled with the extension (background) colour.
|
||||
if extends
|
||||
&& let Some(bg) = doc.layers.first_mut().filter(|l| crate::extra_cmds::is_background(l))
|
||||
&& let Some(bg) = doc.background_mut()
|
||||
&& let LayerContent::Raster(surf) = &mut bg.content
|
||||
{
|
||||
let old = old_canvas.translate(dx, dy);
|
||||
@@ -381,16 +381,13 @@ fn canvas_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A shrink or no-op resize must not silently convert the Background.
|
||||
if ext[3] == 0.0
|
||||
&& (nw > ow as u32 || nh > oh as u32)
|
||||
&& let Some(bg) = doc.layers.first_mut()
|
||||
&& crate::extra_cmds::is_background(bg)
|
||||
&& let Some(bg) = doc.background_mut()
|
||||
{
|
||||
crate::extra_cmds::unlock_background(bg);
|
||||
}
|
||||
// The locked Background layer is extended with the extension colour.
|
||||
if ext[3] > 0.0
|
||||
&& let Some(bg) = doc.layers.first_mut()
|
||||
&& bg.name == "Background"
|
||||
&& bg.locks.transparency
|
||||
&& let Some(bg) = doc.background_mut()
|
||||
&& let LayerContent::Raster(surf) = &mut bg.content
|
||||
{
|
||||
let fmt = surf.format();
|
||||
|
||||
@@ -163,7 +163,7 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let src_layer = sdoc.layer(*id).ok_or(EngineError::NoLayer(*id))?;
|
||||
let mut l = src_layer.duplicate();
|
||||
// A dragged Background arrives as an ordinary layer (the destination keeps its own).
|
||||
if crate::extra_cmds::is_background(src_layer) && sdoc.layers.first().is_some_and(|b| b.id == *id) {
|
||||
if sdoc.is_background(*id) {
|
||||
l.name = ddoc.next_layer_name("Layer");
|
||||
l.locks = Default::default();
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ pub(crate) fn mask_targets(s: &Session, p: &serde_json::Value) -> Result<Vec<Lay
|
||||
return Ok(ids);
|
||||
}
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let ids: Vec<LayerId> = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| l.mask.is_none() && !crate::extra_cmds::is_background(l))).collect();
|
||||
let ids: Vec<LayerId> = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| l.mask.is_none() && !d.doc.is_background(l.id))).collect();
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("none of the selected layers can take a layer mask".into()));
|
||||
}
|
||||
@@ -163,13 +163,9 @@ pub fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"selected": selected(s).iter().map(|l| l.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
pub(crate) fn is_locked_background(l: &Layer) -> bool {
|
||||
l.name == "Background" && l.locks.transparency && matches!(l.content, LayerContent::Raster(_))
|
||||
}
|
||||
|
||||
fn select_all_layers(s: &mut Session) -> Result<Value> {
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let ids: Vec<LayerId> = d.doc.walk().into_iter().filter(|(_, _, l)| !is_locked_background(l)).map(|(_, _, l)| l.id).collect();
|
||||
let ids: Vec<LayerId> = d.doc.walk().into_iter().filter(|(_, _, l)| !d.doc.is_background(l.id)).map(|(_, _, l)| l.id).collect();
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("there are no layers to select".into()));
|
||||
}
|
||||
|
||||
@@ -287,6 +287,7 @@ fn run_filter(s: &mut Session, cmd: &str, label: &str, stored: Value, float_bg:
|
||||
let canvas = doc.bounds();
|
||||
let selection = doc.selection.clone();
|
||||
let locks = doc.effective_locks(id);
|
||||
let background = doc.is_background(id);
|
||||
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
if let LayerContent::Smart(_) = l.content {
|
||||
let sf = SmartFilter { command: cmd.to_string(), params: stored.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true };
|
||||
@@ -296,7 +297,7 @@ fn run_filter(s: &mut Session, cmd: &str, label: &str, stored: Value, float_bg:
|
||||
return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));
|
||||
}
|
||||
// A Background layer gains transparency when the edge mode exposes it (as in Photoshop).
|
||||
if float_bg && l.locks.position && l.name == "Background" {
|
||||
if float_bg && background {
|
||||
l.locks.position = false;
|
||||
l.locks.transparency = false;
|
||||
l.name = "Layer 0".into();
|
||||
|
||||
@@ -91,8 +91,9 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let canvas = doc.bounds();
|
||||
let fmt = doc.pixel_format();
|
||||
let dpi = doc.resolution_dpi;
|
||||
let background_id = doc.background().map(|l| l.id);
|
||||
for l in doc.layers.iter_mut() {
|
||||
let background = l.name == "Background" && l.locks.position && matches!(l.content, LayerContent::Raster(_));
|
||||
let background = Some(l.id) == background_id;
|
||||
if background && let Some(surf) = l.surface_mut() {
|
||||
// The Background stays a Background: rotated pixels over the background colour.
|
||||
let src = surf.content_bounds();
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
use photocraft_algo::transform::{Homography, Interp, convex_quad, quad_size, quad_to_rect, warp_surface_clipped};
|
||||
use photocraft_color::PixelFormat;
|
||||
use photocraft_doc::{Document, Layer, LayerContent, Size};
|
||||
use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size};
|
||||
use photocraft_geom::{Affine, Rect};
|
||||
use photocraft_raster::Surface;
|
||||
use serde_json::{Value, json};
|
||||
@@ -154,12 +154,13 @@ fn warp_gray(s: &Surface, h: &Homography, interp: Interp, clip: Rect) -> Result<
|
||||
}
|
||||
|
||||
/// Maps every layer's pixels and masks through `h` into `clip`.
|
||||
fn warp_layers(layers: &mut [Layer], h: &Homography, interp: Interp, clip: Rect, bg: &[f32]) -> Result<()> {
|
||||
/// `background_id` is the id of the document's Background, if it has one.
|
||||
fn warp_layers(layers: &mut [Layer], h: &Homography, interp: Interp, clip: Rect, bg: &[f32], background_id: Option<LayerId>) -> Result<()> {
|
||||
for l in layers {
|
||||
crate::allocation::checkpoint("a perspective crop")?;
|
||||
let background = crate::extra_cmds::is_background(l);
|
||||
let background = background_id == Some(l.id);
|
||||
match &mut l.content {
|
||||
LayerContent::Group(g) => warp_layers(&mut g.children, h, interp, clip, bg)?,
|
||||
LayerContent::Group(g) => warp_layers(&mut g.children, h, interp, clip, bg, None)?,
|
||||
LayerContent::Raster(surf) => {
|
||||
let warped = warp_surface_clipped(surf, surf.content_bounds(), h, interp, clip)?;
|
||||
*surf = if background {
|
||||
@@ -188,7 +189,8 @@ fn apply(doc: &mut Document, q: &[[f64; 2]; 4], h: &Homography, size: (u32, u32)
|
||||
let (w, ht) = size;
|
||||
let clip = Rect::from_xywh(0, 0, w, ht);
|
||||
let bg = photocraft_raster::from_rgba(&doc.pixel_format(), bg);
|
||||
warp_layers(&mut doc.layers, h, interp, clip, &bg)?;
|
||||
let background_id = doc.background().map(|l| l.id);
|
||||
warp_layers(&mut doc.layers, h, interp, clip, &bg, background_id)?;
|
||||
for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
|
||||
ch.surface = warp_gray(&ch.surface, h, interp, clip)?;
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ pub fn layers_in_rect(doc: &Document, r: Rect, group: bool) -> Vec<LayerId> {
|
||||
let canvas = doc.bounds();
|
||||
for (path, _, l) in doc.walk().iter().rev() {
|
||||
if matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_))
|
||||
|| crate::layer_multi_cmds::is_locked_background(l)
|
||||
|| doc.is_background(l.id)
|
||||
|| doc.effective_locks(l.id).all
|
||||
|| !(1..=path.len()).all(|n| doc.layer_at(&path[..n]).is_some_and(|a| a.visible))
|
||||
{
|
||||
|
||||
@@ -994,6 +994,10 @@ pub struct Preferences {
|
||||
/// differ from their defaults, saved as the user changes them and restored at launch, as
|
||||
/// Photoshop remembers each tool's options between sessions. JSON owned by the shell.
|
||||
pub tool_options: Value,
|
||||
/// View › Extras, the View › Show items (Pixel Grid, Grid, Guides, …) and the View › Snap To
|
||||
/// targets that differ from their defaults, saved as the user toggles them and restored at
|
||||
/// launch, as Photoshop keeps them between sessions (#3762). JSON owned by the shell.
|
||||
pub view_extras: Value,
|
||||
/// File › Scripts › Script Events Manager: event → script bindings.
|
||||
pub script_events: crate::automate_cmds::ScriptEvents,
|
||||
}
|
||||
|
||||
@@ -191,13 +191,9 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mode = doc.mode;
|
||||
let effects: Vec<_> = effects.iter().cloned().map(|e| e.in_mode(mode)).collect();
|
||||
for id in &ids {
|
||||
let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
|
||||
// Styles can't sit on the Background: Photoshop turns it into a normal layer first.
|
||||
if l.name == "Background" && l.locks.transparency && l.locks.position && matches!(l.content, photocraft_doc::LayerContent::Raster(_)) {
|
||||
l.name = "Layer 0".into();
|
||||
l.locks.transparency = false;
|
||||
l.locks.position = false;
|
||||
}
|
||||
crate::extra_cmds::background_to_layer(doc, *id);
|
||||
let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
|
||||
if add {
|
||||
l.effects.items.extend(effects.iter().cloned());
|
||||
} else {
|
||||
|
||||
@@ -50,7 +50,7 @@ fn has_layer_for_slice(s: &Session) -> std::result::Result<(), String> {
|
||||
if matches!(l.content, LayerContent::Adjustment(_)) {
|
||||
return Err("adjustment layers have no bounds to slice".into());
|
||||
}
|
||||
if d.doc.layers.first().is_some_and(|b| b.id == id && b.name == "Background" && b.locks.transparency && b.locks.position) {
|
||||
if d.doc.is_background(id) {
|
||||
return Err("the Background layer can't have a layer-based slice".into());
|
||||
}
|
||||
if d.doc.slices.list.iter().any(|s| s.layer == Some(id)) {
|
||||
|
||||
@@ -666,7 +666,7 @@ fn any_layer(l: &Layer, f: &dyn Fn(&Layer) -> bool) -> bool {
|
||||
/// blend mode, clipping and label stay on the smart layer. The cache is the exact composite, so
|
||||
/// the document looks the same before and after.
|
||||
pub fn layer_to_smart(doc: &Document, l: &Layer) -> Result<Layer> {
|
||||
let background = l.name == "Background" && l.locks.position;
|
||||
let background = doc.is_background(l.id);
|
||||
let mut inner = l.clone();
|
||||
inner.visible = true;
|
||||
inner.opacity = 1.0;
|
||||
|
||||
@@ -32,9 +32,10 @@ fn contents(s: &Session, doc: &Document, sm: &SmartObject, intent: Intent, bpc:
|
||||
if src.depth != doc.depth {
|
||||
crate::image_cmds::convert_layers_depth(&mut src.layers, doc.depth);
|
||||
}
|
||||
let background_id = src.background().map(|l| l.id);
|
||||
let mut layers = std::mem::take(&mut src.layers);
|
||||
for l in &mut layers {
|
||||
if crate::extra_cmds::is_background(l) {
|
||||
if Some(l.id) == background_id {
|
||||
l.name = "Layer 0".into();
|
||||
l.locks = Default::default();
|
||||
}
|
||||
|
||||
@@ -767,6 +767,33 @@ fn command_list_reports_enablement() {
|
||||
assert_eq!(find("layer.new.layer")["enabled"], false);
|
||||
}
|
||||
|
||||
/// With no document open, a document command says so instead of only `enabled: false` (#3664).
|
||||
#[test]
|
||||
fn command_list_tells_no_document_from_other_preconditions() {
|
||||
let mut s = Session::new();
|
||||
let list = s.execute("command.list", json!({})).unwrap();
|
||||
let find = |list: &Value, id: &str| list.as_array().unwrap().iter().find(|c| c["id"] == id).unwrap().clone();
|
||||
for id in ["paint.stroke", "layer.new.layer", "filter.blur.gaussianBlur"] {
|
||||
let c = find(&list, id);
|
||||
assert_eq!((c["enabled"].clone(), c["needsDocument"].clone()), (json!(false), json!(true)), "{id}: {c}");
|
||||
assert!(c["disabledReason"].as_str().is_some_and(|r| r.starts_with("no document")), "{id}: {c}");
|
||||
}
|
||||
let new = find(&list, "file.new");
|
||||
assert_eq!((new["enabled"].clone(), new["needsDocument"].clone(), new["disabledReason"].clone()), (json!(true), json!(false), Value::Null));
|
||||
// A precondition that isn't the missing document keeps its own reason.
|
||||
let paste = find(&list, "file.newFromClipboard");
|
||||
assert_eq!((paste["enabled"].clone(), paste["needsDocument"].clone()), (json!(false), json!(false)));
|
||||
assert_eq!(paste["disabledReason"], "the clipboard is empty");
|
||||
// With a document, the same commands run; a missing selection is not a missing document.
|
||||
let mut s = session_with_doc();
|
||||
let list = s.execute("command.list", json!({})).unwrap();
|
||||
assert_eq!(find(&list, "paint.stroke")["needsDocument"], false);
|
||||
assert_eq!(find(&list, "paint.stroke")["disabledReason"], Value::Null);
|
||||
let deselect = find(&list, "select.deselect");
|
||||
assert_eq!((deselect["enabled"].clone(), deselect["needsDocument"].clone()), (json!(false), json!(false)));
|
||||
assert_eq!(deselect["disabledReason"], "no selection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translate_moves_pixels_and_respects_locks() {
|
||||
let mut s = session_with_doc();
|
||||
|
||||
@@ -201,10 +201,10 @@ pub(crate) fn group_locks(doc: &Document, id: LayerId) -> Locks {
|
||||
}
|
||||
|
||||
/// The locks a transform of `l` meets: its own and `group`'s (those it inherits). The Background's
|
||||
/// position lock doesn't count: Photoshop turns it into a normal layer first ([`transform_layer`]).
|
||||
fn transform_locks(l: &Layer, group: Locks) -> Locks {
|
||||
/// position lock doesn't count: Photoshop turns it into a normal layer first.
|
||||
fn transform_locks(l: &Layer, group: Locks, background: bool) -> Locks {
|
||||
let mut own = l.locks;
|
||||
if own.position && l.name == "Background" {
|
||||
if background {
|
||||
own.position = false;
|
||||
own.transparency = false;
|
||||
}
|
||||
@@ -217,29 +217,24 @@ fn transform_locks(l: &Layer, group: Locks) -> Locks {
|
||||
pub fn locked_for_transform(doc: &Document, id: LayerId) -> bool {
|
||||
let Some(l) = doc.layer(id) else { return false };
|
||||
// An explicit stack rather than recursion: documents can nest deeply.
|
||||
let mut stack = vec![(l, group_locks(doc, id))];
|
||||
while let Some((l, group)) = stack.pop() {
|
||||
let locks = transform_locks(l, group);
|
||||
let mut stack = vec![(l, group_locks(doc, id), doc.is_background(id))];
|
||||
while let Some((l, group, background)) = stack.pop() {
|
||||
let locks = transform_locks(l, group, background);
|
||||
if locks.position || locks.all {
|
||||
return true;
|
||||
}
|
||||
if let LayerContent::Group(g) = &l.content {
|
||||
stack.extend(g.children.iter().map(|c| (c, locks)));
|
||||
stack.extend(g.children.iter().map(|c| (c, locks, false)));
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// `group` holds the locks `l` inherits from the groups around it ([`group_locks`]).
|
||||
/// `group` holds the locks `l` inherits from the groups around it ([`group_locks`]). A Background
|
||||
/// is turned into a normal layer by the caller first ([`crate::extra_cmds::background_to_layer`]).
|
||||
pub(crate) fn transform_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &Homography, affine: Option<Affine>, interp: Interp) -> Result<()> {
|
||||
crate::allocation::checkpoint("transforming pixels")?;
|
||||
let locks = transform_locks(l, group);
|
||||
// Photoshop turns the Background into a normal layer before transforming it.
|
||||
if l.locks.position && l.name == "Background" {
|
||||
l.locks.position = false;
|
||||
l.locks.transparency = false;
|
||||
l.name = "Layer 0".into();
|
||||
}
|
||||
let locks = transform_locks(l, group, false);
|
||||
if locks.position || locks.all {
|
||||
return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));
|
||||
}
|
||||
@@ -493,6 +488,8 @@ fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id.ok_or_else(|| EngineError::Other("no active layer".into()))?;
|
||||
let is_group = doc.layer(id).is_some_and(Layer::is_group);
|
||||
let group = group_locks(doc, id);
|
||||
// Photoshop turns the Background into a normal layer before transforming it.
|
||||
crate::extra_cmds::background_to_layer(doc, id);
|
||||
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
transform_layer(if is_group { None } else { sel.as_ref() }, group, l, &h, affine, interp)?;
|
||||
if !h.is_identity() {
|
||||
|
||||
@@ -639,7 +639,8 @@ fn info(s: &Session, p: &Value) -> Result<Value> {
|
||||
.map(|ln| json!({ "start": char_at(text, ln.range.start), "end": char_at(text, ln.range.end), "baseline": ln.baseline, "x0": ln.x0, "x1": ln.x1, "ascent": ln.ascent, "descent": ln.descent }))
|
||||
.collect();
|
||||
let bounds = t.cache.as_ref().map(|c| c.content_bounds()).map(|r| json!([r.x0, r.y0, r.x1, r.y1]));
|
||||
Ok(json!({
|
||||
let warnings = crate::type_extra_cmds::missing_font_warnings_for_layer(t);
|
||||
let mut out = json!({
|
||||
"layer": id.0,
|
||||
"text": text,
|
||||
"shape": t.shape,
|
||||
@@ -652,7 +653,11 @@ fn info(s: &Session, p: &Value) -> Result<Value> {
|
||||
"lines": lines,
|
||||
"bounds": bounds,
|
||||
"pxPerPt": layout.px_per_pt,
|
||||
}))
|
||||
});
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A type layer (not yet rendered or added) from `type.create`'s params: text, point `x`/`y` or
|
||||
@@ -723,7 +728,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Ok(id)
|
||||
})?;
|
||||
let bounds = s.active().and_then(|d| d.doc.layer(id)).and_then(|l| l.surface()).map(|c| c.content_bounds());
|
||||
Ok(json!({ "layer": id.0, "bounds": bounds.map(|r| [r.x0, r.y0, r.x1, r.y1]) }))
|
||||
let mut out = json!({ "layer": id.0, "bounds": bounds.map(|r| [r.x0, r.y0, r.x1, r.y1]) });
|
||||
if let Some(LayerContent::Text(t)) = s.active().and_then(|d| d.doc.layer(id)).map(|l| &l.content) {
|
||||
let warnings = crate::type_extra_cmds::missing_font_warnings_for_layer(t);
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
},
|
||||
},
|
||||
CommandSpec {
|
||||
@@ -1582,4 +1594,22 @@ mod tests {
|
||||
assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_font_emits_warning_in_create_set_style_and_edit() {
|
||||
let mut s = session();
|
||||
let r = s.execute("type.create", json!({"x": 10, "y": 20, "text": "Hello", "font": "NoSuchFamily123"})).unwrap();
|
||||
assert_eq!(r["warnings"], json!(["font 'NoSuchFamily123' is not installed; text may render using a fallback face"]));
|
||||
let id = r["layer"].as_u64().unwrap();
|
||||
let styled = s.execute("type.setStyle", json!({"layer": id, "font": "StillNoSuchFamily456"})).unwrap();
|
||||
assert_eq!(styled["warnings"], json!(["font 'StillNoSuchFamily456' is not installed; text may render using a fallback face"]));
|
||||
let edited = s.execute("type.edit", json!({"layer": id, "runs": [{"start": 0, "end": 2, "font": "AnotherMissingFont789"}]})).unwrap();
|
||||
assert_eq!(
|
||||
edited["warnings"],
|
||||
json!([
|
||||
"font 'AnotherMissingFont789' is not installed; text may render using a fallback face",
|
||||
"font 'StillNoSuchFamily456' is not installed; text may render using a fallback face"
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -436,6 +436,33 @@ pub fn missing_fonts(doc: &Document) -> Vec<String> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Font families used by a type layer that the font database cannot supply.
|
||||
pub fn missing_fonts_in_layer(t: &TextLayer) -> Vec<String> {
|
||||
let have = installed_families();
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for r in t.char_runs() {
|
||||
let f = r.style.font_family;
|
||||
if !f.is_empty() && !have.contains(&f.to_lowercase()) && !out.contains(&f) {
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Warnings for missing font families in `doc`.
|
||||
pub fn missing_font_warnings(doc: &Document) -> Vec<String> {
|
||||
fonts_to_warnings(missing_fonts(doc))
|
||||
}
|
||||
|
||||
/// Warnings for missing font families in `layer`.
|
||||
pub fn missing_font_warnings_for_layer(t: &TextLayer) -> Vec<String> {
|
||||
fonts_to_warnings(missing_fonts_in_layer(t))
|
||||
}
|
||||
|
||||
fn fonts_to_warnings(fonts: Vec<String>) -> Vec<String> {
|
||||
fonts.into_iter().map(|font| format!("font '{font}' is not installed; text may render using a fallback face")).collect()
|
||||
}
|
||||
|
||||
/// Replace missing families per `map` (missing → installed; unmapped ones → the default family).
|
||||
fn replace_fonts(s: &mut Session, map: &serde_json::Map<String, Value>, all: bool) -> Result<Value> {
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
|
||||
@@ -110,12 +110,9 @@ pub fn warp_from_params(cmd: &str, p: &Value, rect: [f64; 4]) -> Result<Warp> {
|
||||
Ok(w)
|
||||
}
|
||||
|
||||
/// A Background is turned into a normal layer by the caller first
|
||||
/// ([`crate::extra_cmds::background_to_layer`]).
|
||||
fn warp_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, w: &Warp, rect: Rect, interp: Interp) -> Result<()> {
|
||||
if l.locks.position && l.name == "Background" {
|
||||
l.locks.position = false;
|
||||
l.locks.transparency = false;
|
||||
l.name = "Layer 0".into();
|
||||
}
|
||||
let locks = l.locks.union(group);
|
||||
if locks.position || locks.all {
|
||||
return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));
|
||||
@@ -270,6 +267,7 @@ fn apply(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
let sel = doc.selection.clone();
|
||||
let is_group = doc.layer(id).is_some_and(Layer::is_group);
|
||||
let group = crate::transform_cmds::group_locks(doc, id);
|
||||
crate::extra_cmds::background_to_layer(doc, id);
|
||||
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
warp_layer(if is_group { None } else { sel.as_ref() }, group, l, &w, rect, interp)?;
|
||||
let snapshot = doc.clone();
|
||||
|
||||
+24
-12
@@ -633,19 +633,31 @@ fn adjust(c: vec3<f32>) -> vec3<f32> {
|
||||
dl = lut(2, hsl.x) * chroma;
|
||||
}
|
||||
let sat = clamp(p0.y + ds, -1.0, 1.0);
|
||||
let light = clamp(p0.z + dl, -1.0, 1.0);
|
||||
let light = clamp(p0.z, -1.0, 1.0);
|
||||
if (p0.w > 0.5) {
|
||||
hh = rem_euclid(p0.x, 360.0) / 360.0;
|
||||
ss = min(abs(sat), 1.0);
|
||||
} else {
|
||||
hh = rem_euclid(hsl.x + (p0.x + dh) / 360.0, 1.0);
|
||||
ss = clamp(hsl.y * (1.0 + sat), 0.0, 1.0);
|
||||
// compose::adjust::hue_saturation: Colorize at the lightened / darkened lightness.
|
||||
var ll = hsl.z * (1.0 + light);
|
||||
if (light > 0.0) { ll = hsl.z + (1.0 - hsl.z) * light; }
|
||||
return hsl_to_rgb(rem_euclid(p0.x, 360.0) / 360.0, min(abs(sat), 1.0), ll);
|
||||
}
|
||||
var rgb = hsl_to_rgb(hh, ss, hsl.z);
|
||||
if (light > 0.0) {
|
||||
rgb = rgb + (1.0 - rgb) * light;
|
||||
} else if (light < 0.0) {
|
||||
rgb = rgb * (1.0 + light);
|
||||
// Lightness first, then hue and saturation of the result.
|
||||
var lc = c * (1.0 + light);
|
||||
if (light > 0.0) { lc = c + (1.0 - c) * light; }
|
||||
let lh = rgb_to_hsl(lc);
|
||||
hh = rem_euclid(lh.x + (p0.x + dh) / 360.0, 1.0);
|
||||
// Raising saturation divides by 1 - s; lowering it multiplies by 1 + s.
|
||||
if (sat > 0.0) {
|
||||
ss = clamp(lh.y / max(1.0 - sat, 1.0 / 512.0), 0.0, 1.0);
|
||||
} else {
|
||||
ss = clamp(lh.y * (1.0 + sat), 0.0, 1.0);
|
||||
}
|
||||
var rgb = hsl_to_rgb(hh, ss, lh.z);
|
||||
// compose::adjust::range_lightness: towards the brightest channel when raised, the darkest when lowered.
|
||||
let rl = clamp(dl, -1.0, 1.0);
|
||||
if (rl > 0.0) {
|
||||
rgb = rgb + (vec3(max(rgb.r, max(rgb.g, rgb.b))) - rgb) * rl;
|
||||
} else if (rl < 0.0) {
|
||||
rgb = rgb + (vec3(min(rgb.r, min(rgb.g, rgb.b))) - rgb) * -rl;
|
||||
}
|
||||
return rgb;
|
||||
}
|
||||
@@ -686,7 +698,7 @@ fn adjust(c: vec3<f32>) -> vec3<f32> {
|
||||
if (c.b <= c.r && c.b <= c.g) { secondary = 1; } else if (c.r <= c.g) { secondary = 3; }
|
||||
let g = clamp(mn + (mid - mn) * w[secondary] / 100.0 + (mx - mid) * w[primary] / 100.0, 0.0, 1.0);
|
||||
if (p1.z > 0.5) {
|
||||
return clamp(g * p2.rgb * 2.0, vec3(0.0), vec3(1.0)) * 0.5 + g * 0.5;
|
||||
return clamp(set_lum(p2.rgb, g, 1.0), vec3(0.0), vec3(1.0)); // Color blend of the tint
|
||||
}
|
||||
return vec3(g);
|
||||
}
|
||||
|
||||
@@ -353,7 +353,7 @@ pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool,
|
||||
}
|
||||
Effect::Satin(s) => {
|
||||
// satin_map
|
||||
let (dx, dy) = offset(s.angle, s.distance);
|
||||
let (dx, dy) = offset(s.angle, photocraft_compose::effects::satin_distance(s));
|
||||
let a = b.shift(In::Shape, dx, dy, 0.0, false);
|
||||
let a = b.conv(a, photocraft_compose::effects::tent_kernel(s.size));
|
||||
let c = b.shift(In::Shape, -dx, -dy, 0.0, false);
|
||||
|
||||
@@ -389,7 +389,9 @@ impl Mapper<'_> {
|
||||
t.invert = boolean(d, "InvT").unwrap_or(false);
|
||||
t.scale = pct(d, "textureScale").unwrap_or(1.0).clamp(0.01, 10.0);
|
||||
t.brightness = (num(d, "textureBrightness").unwrap_or(0.0) / 150.0).clamp(-1.0, 1.0) as f32;
|
||||
t.contrast = (num(d, "textureContrast").unwrap_or(0.0) / 50.0).clamp(-1.0, 2.0) as f32;
|
||||
// Photoshop's -50..100 onto the model's -1..1 (negative and positive scale apart).
|
||||
let c = num(d, "textureContrast").unwrap_or(0.0);
|
||||
t.contrast = (if c < 0.0 { c / 50.0 } else { c / 100.0 }).clamp(-1.0, 1.0) as f32;
|
||||
t.mode = mask_mode(enum_value(d, "textureBlendMode")).unwrap_or(MaskMode::Multiply);
|
||||
t.depth = pct(d, "textureDepth").unwrap_or(1.0).clamp(0.0, 1.0);
|
||||
let mut dj = self.dynamic(obj(d, "textureDepthDynamics"));
|
||||
|
||||
@@ -153,7 +153,7 @@ fn v6_settings_map_onto_brush_sections() {
|
||||
assert_eq!((sc.count, sc.scatter.jitter, sc.scatter.control, sc.scatter.fade_steps, sc.count_jitter.jitter), (3, 2.5, Control::Fade, 40, 0.5));
|
||||
let tx = &b.texture;
|
||||
assert!(tx.enabled && tx.each_tip && tx.invert);
|
||||
assert_eq!((tx.scale, tx.brightness, tx.contrast, tx.mode, tx.depth), (1.5, -0.5, 0.5, MaskMode::ColorBurn, 0.6));
|
||||
assert_eq!((tx.scale, tx.brightness, tx.contrast, tx.mode, tx.depth), (1.5, -0.5, 0.25, MaskMode::ColorBurn, 0.6));
|
||||
assert_eq!((tx.depth_jitter.jitter, tx.depth_jitter.minimum), (0.3, 0.2));
|
||||
let Pattern::Tile(pt) = &tx.pattern else { panic!("embedded pattern expected, got {:?}", tx.pattern) };
|
||||
assert_eq!((pt.width, pt.height, pt.data[3]), (4, 2, 65535));
|
||||
@@ -330,3 +330,50 @@ fn sampled_tip_paints_the_brush_colour_never_black() {
|
||||
assert!(painted > 0, "the imported tip painted nothing");
|
||||
assert!(painted < 64 * 64, "the tip covered everything - coverage was treated as solid colour");
|
||||
}
|
||||
|
||||
/// #3340: Photoshop's texture Contrast runs -50..100; the model maps -50..0 and 0..100 onto
|
||||
/// -1..0 and 0..1 (as Brush Settings shows it), so +24 must not read back as +48.
|
||||
#[test]
|
||||
fn texture_contrast_maps_both_halves() {
|
||||
for (c, want) in [(24, 0.24), (100, 1.0), (-30, -0.6), (-50, -1.0), (0, 0.0)] {
|
||||
let preset = Descriptor::new("brushPreset")
|
||||
.with("Nm ", t("C"))
|
||||
.with("Brsh", Value::Descriptor(Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 20.0))))
|
||||
.with("useTexture", Value::Boolean(true))
|
||||
.with("textureContrast", Value::Integer(c));
|
||||
let bytes = write_v6(2, &[], &[], &[preset], false).unwrap();
|
||||
let imp = read_abr(&bytes, "Test").unwrap();
|
||||
let got = imp.presets[0].brush.texture.contrast;
|
||||
assert!((got - want).abs() < 1e-6, "contrast {c}: {got}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3340: a Height-mode brush at a low depth with a darkened pattern (how Photoshop's own
|
||||
/// "Pen" presets in the reported file are set up) imported but painted nothing.
|
||||
#[test]
|
||||
fn low_depth_height_texture_brush_paints() {
|
||||
use photocraft_color::PixelFormat;
|
||||
use photocraft_paint::StrokePoint;
|
||||
use photocraft_paint::render::render_stroke;
|
||||
use photocraft_raster::Surface;
|
||||
|
||||
for mode in ["Hght", "linearHeight"] {
|
||||
let preset = Descriptor::new("brushPreset")
|
||||
.with("Nm ", t("Pen"))
|
||||
.with("Brsh", Value::Descriptor(Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 20.0)).with("Hrdn", prc(100.0)).with("Spcn", prc(5.0))))
|
||||
.with("useTexture", Value::Boolean(true))
|
||||
.with("textureBlendMode", en("BlnM", mode))
|
||||
.with("textureDepth", prc(13.0))
|
||||
.with("textureBrightness", Value::Integer(-87))
|
||||
.with("textureContrast", Value::Integer(5))
|
||||
.with("Txtr", Value::Descriptor(Descriptor::new("Ptrn").with("Nm ", t("Grit")).with("Idnt", t("pat-uuid"))));
|
||||
let bytes = write_v6(2, &[], &[grit_pattern()], &[preset], false).unwrap();
|
||||
let imp = read_abr(&bytes, "Test").unwrap();
|
||||
let b = imp.presets[0].brush.clone();
|
||||
let mut s = Surface::new(PixelFormat::RGBA32F);
|
||||
render_stroke(&mut s, &b, &[StrokePoint::new(10.0, 20.0, 1.0), StrokePoint::new(50.0, 20.0, 1.0)], None, false, 1.0);
|
||||
let covered = (12..48).filter(|&x| s.rgba(x, 20)[3] > 0.5).count();
|
||||
// 13 % depth reaches 1.55 pattern ranges: above the whole darkened Grit pattern.
|
||||
assert_eq!(covered, 36, "{mode}: the stroke painted {covered} of 36 pixels");
|
||||
}
|
||||
}
|
||||
@@ -151,6 +151,7 @@ impl Builder {
|
||||
bg.prune();
|
||||
let mut l = Layer::new("Background", LayerContent::Raster(bg));
|
||||
l.locks.transparency = true;
|
||||
l.locks.position = true;
|
||||
layers.insert(0, l);
|
||||
}
|
||||
self.doc.layers = layers;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! Alpha / spot channel options <-> PSD `DisplayInfo` image resources (1077, and the older 1007).
|
||||
//!
|
||||
//! Layout (Adobe PSD spec, "DisplayInfo"): resource 1077 starts with a 4-byte version (1), then
|
||||
//! one 14-byte record per extra channel: colour space (u16), four u16 colour components, opacity
|
||||
//! (u16, 0..100), kind (u8: 0 = colour indicates selected areas, 1 = masked ("protected") areas,
|
||||
//! 2 = spot channel) and one padding byte. Resource 1007 has the same records without the
|
||||
//! version and without the spot kind.
|
||||
//! one 13-byte record per extra channel: colour space (u16), four u16 colour components, opacity
|
||||
//! (u16, 0..100) and kind (u8: 0 = colour indicates selected areas, 1 = masked ("protected")
|
||||
//! areas, 2 = spot channel). Resource 1007 has the same records without the version and the spot
|
||||
//! kind, each followed by a padding byte (14 bytes).
|
||||
|
||||
use photocraft_color::{Color, ColorMode};
|
||||
use photocraft_doc::{AlphaChannel, ColorIndicates};
|
||||
@@ -59,6 +59,8 @@ pub(crate) fn apply_display_info(data: &[u8], versioned: bool, skip: usize, chan
|
||||
match rec[12] {
|
||||
2 => c.spot = Some((color, opacity)),
|
||||
k => {
|
||||
// An alpha channel, not an ink (a Multichannel import starts every channel as one).
|
||||
c.spot = None;
|
||||
c.color = color;
|
||||
c.opacity = opacity;
|
||||
c.indicates = if k == 0 { ColorIndicates::SelectedAreas } else { ColorIndicates::MaskedAreas };
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Krita .kra import: the merged PNG is an editable raster layer, not a replacement
|
||||
//! for Krita's native layer tree. Never write this document back to the .kra source.
|
||||
//! The ZIP reader checks entry bounds, sizes and CRC before the PNG decoder runs.
|
||||
|
||||
use photocraft_codecs::{self as codecs, DecodeOptions, Format};
|
||||
use photocraft_format::zip::ZipReader;
|
||||
use photocraft_raster::Interrupt;
|
||||
|
||||
use crate::{ImportResult, IoError};
|
||||
|
||||
const MIMETYPE: &[u8] = b"application/x-krita";
|
||||
const MAX_ENTRY: usize = 512 << 20;
|
||||
const MAX_PIXELS_BYTES: u64 = 1 << 30;
|
||||
|
||||
fn invalid(message: impl Into<String>) -> IoError {
|
||||
IoError::Kra(message.into())
|
||||
}
|
||||
|
||||
/// Krita writes its mimetype as the first, uncompressed ZIP entry.
|
||||
pub(crate) fn is_kra(bytes: &[u8]) -> bool {
|
||||
crate::ora::zip_mimetype(bytes).is_some_and(|mime| mime.trim_ascii() == MIMETYPE)
|
||||
}
|
||||
|
||||
/// Import Krita's official merged preview as a flattened, editable PhotoCraft document.
|
||||
/// Do not silently pretend this imported a layered or lossless Krita document.
|
||||
pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result<ImportResult, IoError> {
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
let archive = ZipReader::new(bytes).map_err(|e| invalid(e.to_string()))?;
|
||||
let mime = archive.read_by_name("mimetype", 256).map_err(|e| invalid(e.to_string()))?;
|
||||
if mime.trim_ascii() != MIMETYPE {
|
||||
return Err(invalid("the archive's mimetype is not application/x-krita"));
|
||||
}
|
||||
ctl.progress(0.10);
|
||||
let merged = archive.read_by_name("mergedimage.png", MAX_ENTRY).map_err(|e| invalid(format!("mergedimage.png: {e}")))?;
|
||||
if codecs::detect(&merged) != Some(Format::Png) {
|
||||
return Err(invalid("mergedimage.png is not a PNG image"));
|
||||
}
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
let mut opts = DecodeOptions::default();
|
||||
opts.limits.max_width = crate::ora::MAX_SIDE;
|
||||
opts.limits.max_height = crate::ora::MAX_SIDE;
|
||||
opts.limits.max_alloc = MAX_PIXELS_BYTES;
|
||||
let image = codecs::decode_with(&merged, &opts).map_err(|e| invalid(format!("mergedimage.png: {e}")))?;
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
let mut result = crate::flat::image_to_document(name, &image)?;
|
||||
result.source_read_only = true;
|
||||
result.warnings.push("Krita layers, masks and editable document structure were not imported; only mergedimage.png is available".into());
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_codecs::{ChannelLayout, EncodeOptions, Image, SampleType};
|
||||
use photocraft_format::zip::ZipWriter;
|
||||
|
||||
fn png() -> Vec<u8> {
|
||||
let image = Image::from_raw(2, 1, ChannelLayout::Rgba, SampleType::U8, vec![255, 0, 0, 255, 0, 0, 255, 128]).unwrap();
|
||||
codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
fn archive(mime: &[u8], with_merged: bool) -> Vec<u8> {
|
||||
let mut zip = ZipWriter::new();
|
||||
zip.add("mimetype", mime).unwrap();
|
||||
zip.add("maindoc.xml", b"<DOC/>").unwrap();
|
||||
if with_merged {
|
||||
zip.add("mergedimage.png", &png()).unwrap();
|
||||
}
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_krita_composite_without_claiming_to_preserve_layers() {
|
||||
let bytes = archive(MIMETYPE, true);
|
||||
assert!(is_kra(&bytes));
|
||||
// The mimetype is authoritative even without a .kra extension.
|
||||
for name in ["scene.kra", "download"] {
|
||||
let r = crate::import(name, &bytes).unwrap();
|
||||
assert_eq!((r.document.size.width, r.document.size.height), (2, 1));
|
||||
assert_eq!(r.document.name, name);
|
||||
assert_eq!(r.document.layers.len(), 1);
|
||||
assert_eq!(r.document.layers[0].name, "Layer 0", "alpha-bearing composite");
|
||||
let pixels = r.document.layers[0].surface().unwrap();
|
||||
assert!(pixels.rgba(0, 0)[0] > 0.99);
|
||||
assert!(pixels.rgba(1, 0)[2] > 0.99);
|
||||
assert!((pixels.rgba(1, 0)[3] - 128.0 / 255.0).abs() < 0.01);
|
||||
assert!(r.source_read_only, ".kra must not be overwritten by a flat save");
|
||||
assert!(!r.preview_only, "the flattened image is editable");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("layers") && w.contains("not imported")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_or_non_krita_archives_do_not_open_as_krita() {
|
||||
let wrong = archive(b"image/openraster", true);
|
||||
assert!(!is_kra(&wrong));
|
||||
assert!(import("wrong.kra", &wrong, &Interrupt::NONE).is_err());
|
||||
assert!(import("missing.kra", &archive(MIMETYPE, false), &Interrupt::NONE).is_err());
|
||||
assert!(import("broken.kra", b"not a zip", &Interrupt::NONE).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_png_with_a_misleading_kra_extension_remains_a_png() {
|
||||
let r = crate::import("renamed.kra", &png()).unwrap();
|
||||
assert_eq!(r.document.size.width, 2);
|
||||
assert!(!r.source_read_only, "a real PNG must not be treated as a Krita source");
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
//! * Paint.NET PDN3 documents open as editable bitmap layers (import only).
|
||||
//! * OpenRaster (`.ora`) documents open and save with their layers, groups, blend modes,
|
||||
//! opacity and visibility; see `ora`.
|
||||
//! * Krita (`.kra`) documents open as their merged composite; source layers are not imported.
|
||||
//! * Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`) open natively
|
||||
//! with no source save path, what isn't imported listed in the warnings; a file
|
||||
//! whose native data can't be read opens as its embedded preview; see `affinity`.
|
||||
@@ -41,6 +42,7 @@ pub mod effects_map;
|
||||
pub mod exr_parts;
|
||||
mod flat;
|
||||
mod gradient_bake;
|
||||
mod kra;
|
||||
pub mod linked;
|
||||
mod multichannel_map;
|
||||
mod ora;
|
||||
@@ -80,6 +82,9 @@ pub enum IoError {
|
||||
/// OpenRaster read failure.
|
||||
#[error("OpenRaster: {0}")]
|
||||
Ora(String),
|
||||
/// Krita document decode failure.
|
||||
#[error("Krita: {0}")]
|
||||
Kra(String),
|
||||
/// PSD parse/write failure.
|
||||
#[error("PSD: {0}")]
|
||||
Psd(#[from] PsdError),
|
||||
@@ -268,6 +273,11 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, m
|
||||
if ora::is_ora(bytes) || has_extension(name, "ora") {
|
||||
return ora::import(name, bytes, ctl);
|
||||
}
|
||||
// Krita files are ZIP containers carrying a merged PNG. A recognized raster signature
|
||||
// still wins over a misleading .kra suffix (as with SVG imports).
|
||||
if kra::is_kra(bytes) || (has_extension(name, "kra") && photocraft_codecs::detect(bytes).is_none()) {
|
||||
return kra::import(name, bytes, ctl);
|
||||
}
|
||||
if has_extension(name, "pdn") || bytes.starts_with(b"PDN3") {
|
||||
return pdn::import(name, bytes, ctl);
|
||||
}
|
||||
|
||||
@@ -9,13 +9,21 @@
|
||||
use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_doc::{AlphaChannel, Document};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_psd::file::LayerInfoPlacement;
|
||||
use photocraft_psd::file::{GlobalLayerMask, LayerInfoPlacement};
|
||||
use photocraft_psd::resources::{ImageResource, ResolutionInfo, ids, version_info_resource};
|
||||
use photocraft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, PsdFile};
|
||||
use photocraft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, PsdFile, TaggedBlock};
|
||||
use photocraft_raster::Surface;
|
||||
|
||||
use crate::pixels::{encode_be, psd_depth};
|
||||
|
||||
/// Grid and guides.
|
||||
const GRID_AND_GUIDES: u16 = 1032;
|
||||
/// Alpha identifiers: one u32 per extra channel.
|
||||
const ALPHA_IDENTIFIERS: u16 = 1053;
|
||||
/// Resources that only describe layers: target layer (1024), layer groups (1026), layer
|
||||
/// selection ids (1069) and layer groups enabled (1072). A Multichannel document has no layers.
|
||||
const LAYER_ONLY_RESOURCES: [u16; 4] = [ids::LAYER_STATE, ids::LAYER_GROUP_INFO, 1069, 1072];
|
||||
|
||||
/// Value of sample `i` of a big-endian plane.
|
||||
fn decode(plane: &[u8], i: usize, s: SampleType) -> f32 {
|
||||
match s {
|
||||
@@ -44,7 +52,8 @@ pub(crate) fn import(file: &PsdFile, all: &[u8], doc: &mut Document, names: &[St
|
||||
s.write_region(canvas, &vals);
|
||||
s.prune();
|
||||
let name = names.get(k).cloned().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Channel {}", k + 1));
|
||||
// Without DisplayInfo the channels print in black, as Photoshop shows them.
|
||||
// Without DisplayInfo the channels print in black, as Photoshop shows them. DisplayInfo
|
||||
// turns alpha-type channels (selected / masked areas) back into alpha channels.
|
||||
doc.channels.push(AlphaChannel { spot: Some((Color::BLACK, 0.0)), ..AlphaChannel::new(name, s) });
|
||||
}
|
||||
if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO) {
|
||||
@@ -97,17 +106,54 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec<
|
||||
let image_data = ImageData::encode(Compression::Rle, &planes, &header)
|
||||
.or_else(|_| ImageData::encode(Compression::Raw, &planes, &header))
|
||||
.unwrap_or(ImageData { compression: Compression::Raw, data: planes });
|
||||
let mut resources = vec![ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes())];
|
||||
let mut resources = vec![
|
||||
ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()),
|
||||
ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()),
|
||||
ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()),
|
||||
];
|
||||
// Grid and guides: Photoshop writes it in every file, guides or not.
|
||||
resources.push(ImageResource::new(GRID_AND_GUIDES, crate::psd_export::guides_resource(doc)));
|
||||
if !channels.is_empty() {
|
||||
let names: Vec<&str> = channels.iter().map(|c| c.name.as_str()).collect();
|
||||
resources.push(ImageResource::new(1006, crate::psd_export::pascal_names_resource(&names)));
|
||||
resources.push(ImageResource::new(1045, crate::psd_export::unicode_names_resource(&names)));
|
||||
resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&channels, false)));
|
||||
}
|
||||
resources.extend(crate::psd_export::path_resources(doc, &mut warnings));
|
||||
// The XMP and EXIF resolution follow the ResolutionInfo resource, so no copy contradicts it.
|
||||
let ppi = Some((doc.resolution_dpi, doc.resolution_dpi)).filter(|d| d.0 > 0.0);
|
||||
if let Some(x) = &doc.metadata.xmp {
|
||||
resources.push(ImageResource::new(ids::XMP, x.as_bytes().to_vec()));
|
||||
resources.push(ImageResource::new(ids::XMP, photocraft_codecs::export_xmp(x, ppi).as_bytes().to_vec()));
|
||||
}
|
||||
if let Some(e) = &doc.metadata.exif {
|
||||
resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::export_exif(e, ppi).into_owned()));
|
||||
}
|
||||
// Every other imported resource (print settings, IPTC, the layer-id seed, ...), except the
|
||||
// ones that only describe layers and any already written above.
|
||||
let written: Vec<u16> = resources.iter().map(|r| r.id).collect();
|
||||
for (id, name, data) in &doc.metadata.psd_resources {
|
||||
if LAYER_ONLY_RESOURCES.contains(id) || written.contains(id) || !crate::psd_export::keep_imported_resource(doc, *id, data) {
|
||||
continue;
|
||||
}
|
||||
// Alpha identifiers: one u32 per channel, only while they still match the channels.
|
||||
if *id == ALPHA_IDENTIFIERS && data.len() != channels.len().saturating_mul(4) {
|
||||
continue;
|
||||
}
|
||||
let mut r = ImageResource::new(*id, data.to_vec());
|
||||
r.name = crate::psd_export::legacy_name(name);
|
||||
resources.push(r);
|
||||
}
|
||||
if let Some(data) = crate::annotations_map::fresh_scale_resource(doc) {
|
||||
resources.push(ImageResource::new(crate::annotations_map::MEASUREMENT_SCALE, data));
|
||||
}
|
||||
resources.push(version_info_resource(true));
|
||||
// Document-level tagged blocks (patterns, notes, ...) are valid without a layer section; a
|
||||
// kept layer block would describe layers the document doesn't have.
|
||||
let global_blocks: Vec<TaggedBlock> = crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc))
|
||||
.into_iter()
|
||||
.filter(|(_, key, _)| !matches!(key, b"Layr" | b"Lr16" | b"Lr32"))
|
||||
.map(|(sig, key, data)| crate::psd_export::global_block(sig, key, &data))
|
||||
.collect();
|
||||
let color_mode_data = photocraft_psd::hdr::color_mode_data_for_depth(header.depth);
|
||||
let file = PsdFile {
|
||||
header,
|
||||
@@ -115,8 +161,8 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec<
|
||||
resources,
|
||||
layer_info: None,
|
||||
layer_info_placement: LayerInfoPlacement::Section,
|
||||
global_layer_mask: None,
|
||||
global_blocks: Vec::new(),
|
||||
global_layer_mask: (!global_blocks.is_empty()).then(GlobalLayerMask::default),
|
||||
global_blocks,
|
||||
layer_mask_trailing: Vec::new(),
|
||||
image_data,
|
||||
};
|
||||
|
||||
+71
-56
@@ -1053,7 +1053,7 @@ fn effects_unchanged(l: &Layer) -> Option<bool> {
|
||||
Some(m == l.effects.enabled && items == l.effects.items)
|
||||
}
|
||||
|
||||
fn legacy_name(s: &str) -> Vec<u8> {
|
||||
pub(crate) fn legacy_name(s: &str) -> Vec<u8> {
|
||||
s.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect()
|
||||
}
|
||||
|
||||
@@ -1079,7 +1079,7 @@ pub(crate) fn pascal_names_resource(names: &[&str]) -> Vec<u8> {
|
||||
v
|
||||
}
|
||||
|
||||
fn guides_resource(doc: &Document) -> Vec<u8> {
|
||||
pub(crate) fn guides_resource(doc: &Document) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
v.extend_from_slice(&1u32.to_be_bytes());
|
||||
v.extend_from_slice(&576u32.to_be_bytes());
|
||||
@@ -1095,6 +1095,72 @@ fn guides_resource(doc: &Document) -> Vec<u8> {
|
||||
v
|
||||
}
|
||||
|
||||
/// Path resources: saved paths (2000+), the work path (1025) and the clipping path name (2999),
|
||||
/// the last only when the imported one doesn't already name the document's clipping path.
|
||||
pub(crate) fn path_resources(doc: &Document, warnings: &mut Vec<String>) -> Vec<ImageResource> {
|
||||
use crate::vector_map::{CLIPPING_PATH, WORK_PATH, path_from_resource, path_to_records};
|
||||
let mut out = Vec::new();
|
||||
let (w, h) = (doc.size.width, doc.size.height);
|
||||
let max = (*crate::vector_map::SAVED_PATHS.end() - *crate::vector_map::SAVED_PATHS.start() + 1) as usize;
|
||||
if doc.paths.len() > max {
|
||||
warnings.push(format!("only {max} saved paths fit in PSD; the rest were dropped"));
|
||||
}
|
||||
for (i, p) in doc.paths.iter().take(max).enumerate() {
|
||||
let data = match &p.psd_raw {
|
||||
Some(r) if path_from_resource(r, w, h).as_ref() == Some(&p.path) => r.to_vec(),
|
||||
_ => path_to_records(&p.path, w, h).to_bytes(),
|
||||
};
|
||||
let mut r = ImageResource::new(crate::vector_map::SAVED_PATHS.start() + i as u16, data);
|
||||
r.name = legacy_name(&p.name);
|
||||
out.push(r);
|
||||
}
|
||||
if let Some(wp) = &doc.work_path {
|
||||
out.push(ImageResource::new(WORK_PATH, path_to_records(wp, w, h).to_bytes()));
|
||||
}
|
||||
let raw_clip = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == CLIPPING_PATH);
|
||||
let raw_name = raw_clip.map(|(_, _, d)| {
|
||||
let n = usize::from(d.first().copied().unwrap_or(0));
|
||||
d.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default()
|
||||
});
|
||||
if let Some(c) = &doc.clipping_path
|
||||
&& raw_name.as_deref() != Some(c.name.as_str())
|
||||
{
|
||||
// Pascal name, then flatness as 16.16 fixed (best effort; see vector_map docs).
|
||||
let mut data = vec![0u8];
|
||||
let name = legacy_name(&c.name);
|
||||
data[0] = name.len() as u8;
|
||||
data.extend_from_slice(&name);
|
||||
data.extend_from_slice(&((c.flatness.max(0.0) * 65536.0) as u32).to_be_bytes());
|
||||
out.push(ImageResource::new(CLIPPING_PATH, data));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether an imported (unmodelled) resource still describes the document and is written back.
|
||||
pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> bool {
|
||||
// Measurement scale / count resources: only while they still describe the document.
|
||||
if !crate::annotations_map::keep_resource(doc, id) {
|
||||
return false;
|
||||
}
|
||||
// A preserved clipping-path resource is only valid while it names the current one.
|
||||
if id == crate::vector_map::CLIPPING_PATH {
|
||||
let n = usize::from(data.first().copied().unwrap_or(0));
|
||||
let raw_name = data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();
|
||||
return doc.clipping_path.as_ref().is_some_and(|c| c.name == raw_name);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A document-level (global) tagged block. Photoshop pads these to a multiple of 4, and readers
|
||||
/// such as psd-tools step to the next block that way: an even pad after `CAI ` (77 bytes)
|
||||
/// misaligned every block after it (#200).
|
||||
pub(crate) fn global_block(signature: [u8; 4], key: [u8; 4], data: &[u8]) -> TaggedBlock {
|
||||
let mut tb = TaggedBlock::new(key, data.to_vec());
|
||||
tb.signature = signature;
|
||||
tb.padding = Some(vec![0; (4 - data.len() % 4) % 4]);
|
||||
tb
|
||||
}
|
||||
|
||||
fn cmyk_of(fmt: &PixelFormat) -> bool {
|
||||
fmt.mode == ColorMode::Cmyk
|
||||
}
|
||||
@@ -1467,43 +1533,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c
|
||||
data.push(0);
|
||||
resources.push(ImageResource::new(crate::channel_map::QUICK_MASK_INFO, data));
|
||||
}
|
||||
// Paths: saved paths (2000+), the work path (1025), the clipping path name (2999).
|
||||
{
|
||||
use crate::vector_map::{CLIPPING_PATH, WORK_PATH, path_from_resource, path_to_records};
|
||||
let (w, h) = (doc.size.width, doc.size.height);
|
||||
let max = (*crate::vector_map::SAVED_PATHS.end() - *crate::vector_map::SAVED_PATHS.start() + 1) as usize;
|
||||
if doc.paths.len() > max {
|
||||
ex.warnings.push(format!("only {max} saved paths fit in PSD; the rest were dropped"));
|
||||
}
|
||||
for (i, p) in doc.paths.iter().take(max).enumerate() {
|
||||
let data = match &p.psd_raw {
|
||||
Some(r) if path_from_resource(r, w, h).as_ref() == Some(&p.path) => r.to_vec(),
|
||||
_ => path_to_records(&p.path, w, h).to_bytes(),
|
||||
};
|
||||
let mut r = ImageResource::new(crate::vector_map::SAVED_PATHS.start() + i as u16, data);
|
||||
r.name = legacy_name(&p.name);
|
||||
resources.push(r);
|
||||
}
|
||||
if let Some(wp) = &doc.work_path {
|
||||
resources.push(ImageResource::new(WORK_PATH, path_to_records(wp, w, h).to_bytes()));
|
||||
}
|
||||
let raw_clip = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == CLIPPING_PATH);
|
||||
let raw_name = raw_clip.map(|(_, _, d)| {
|
||||
let n = usize::from(d.first().copied().unwrap_or(0));
|
||||
d.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default()
|
||||
});
|
||||
if let Some(c) = &doc.clipping_path
|
||||
&& raw_name.as_deref() != Some(c.name.as_str())
|
||||
{
|
||||
// Pascal name, then flatness as 16.16 fixed (best effort; see vector_map docs).
|
||||
let mut data = vec![0u8];
|
||||
let name = legacy_name(&c.name);
|
||||
data[0] = name.len() as u8;
|
||||
data.extend_from_slice(&name);
|
||||
data.extend_from_slice(&((c.flatness.max(0.0) * 65536.0) as u32).to_be_bytes());
|
||||
resources.push(ImageResource::new(CLIPPING_PATH, data));
|
||||
}
|
||||
}
|
||||
resources.extend(path_resources(doc, &mut ex.warnings));
|
||||
if let Some(groups) = link_group_resource(&doc.layers) {
|
||||
resources.push(ImageResource::new(ids::LAYER_GROUP_INFO, groups));
|
||||
}
|
||||
@@ -1548,13 +1578,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c
|
||||
if !ex.records.is_empty() && matches!(&key, b"Lr16" | b"Lr32" | b"Layr") {
|
||||
continue;
|
||||
}
|
||||
let mut tb = TaggedBlock::new(key, data.to_vec());
|
||||
tb.signature = sig;
|
||||
// Photoshop pads document-level (global) blocks to a multiple of 4, and readers such as
|
||||
// psd-tools step to the next block that way: an even pad after `CAI ` (77 bytes)
|
||||
// misaligned every block after it (#200).
|
||||
tb.padding = Some(vec![0; (4 - data.len() % 4) % 4]);
|
||||
global_blocks.push(tb);
|
||||
global_blocks.push(global_block(sig, key, &data));
|
||||
}
|
||||
if let Some(txt2) = txt2 {
|
||||
let mut tb = TaggedBlock::new(*b"Txt2", txt2.clone());
|
||||
@@ -1576,18 +1600,9 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c
|
||||
if *id == crate::slices_map::SLICES && slices_resource.is_some() {
|
||||
continue;
|
||||
}
|
||||
// Measurement scale / count resources: only while they still describe the document.
|
||||
if !crate::annotations_map::keep_resource(doc, *id) {
|
||||
if !keep_imported_resource(doc, *id, data) {
|
||||
continue;
|
||||
}
|
||||
// A preserved clipping-path resource is only valid while it names the current one.
|
||||
if *id == crate::vector_map::CLIPPING_PATH {
|
||||
let n = usize::from(data.first().copied().unwrap_or(0));
|
||||
let raw_name = data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();
|
||||
if doc.clipping_path.as_ref().is_none_or(|c| c.name != raw_name) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let mut r = ImageResource::new(*id, data.to_vec());
|
||||
r.name = legacy_name(name);
|
||||
resources.push(r);
|
||||
|
||||
@@ -706,6 +706,16 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)
|
||||
// its own profile, as the compositor and the PSD writer read them.
|
||||
let space = photocraft_compose::cmyk_space(&doc);
|
||||
doc.layers = photocraft_color::convert::with_cmyk_space(space.as_ref(), || cx.build(&tree, 0));
|
||||
// Photoshop's Background: the bottom record, a transparency-protected pixel layer stored
|
||||
// without a transparency channel (-1). It is also position-locked, whatever its
|
||||
// (localized) name and whether or not the file carries an `lspf` block.
|
||||
if let (Some(rec), Some(bottom)) = (file.layers().first(), doc.layers.first_mut())
|
||||
&& rec.flags.transparency_protected()
|
||||
&& !rec.channels.iter().any(|c| c.id == -1)
|
||||
&& matches!(bottom.content, LayerContent::Raster(_))
|
||||
{
|
||||
bottom.locks.position = true;
|
||||
}
|
||||
// Layer › Link Layers: resource 1026 holds one group id per layer record (0 = unlinked).
|
||||
if let Some(Ok(photocraft_psd::resources::ResourceData::LayerGroupInfo(groups))) =
|
||||
file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(photocraft_psd::resources::ImageResource::parsed)
|
||||
|
||||
+45
-11
@@ -14,7 +14,7 @@ use std::sync::Arc;
|
||||
|
||||
use photocraft_cms::{Builtin, Intent, Profile, Transform};
|
||||
use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType};
|
||||
use photocraft_raw::{CameraLook, DevelopOptions, Limits, RawError, Reference, Sensor, WhiteBalance};
|
||||
use photocraft_raw::{CameraLook, DevelopOptions, Limits, PreviewColorSpace, RawError, Reference, Sensor, WhiteBalance};
|
||||
|
||||
use crate::flat::image_to_document;
|
||||
use crate::{ImportResult, IoError};
|
||||
@@ -133,10 +133,23 @@ pub fn import_raw(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
|
||||
/// the fit grid is at most `PROXY_EDGE` cells and wants about two pixels per cell).
|
||||
const FIT_PREVIEW_EDGE: u32 = 2 * photocraft_raw::PROXY_EDGE as u32;
|
||||
|
||||
/// The colour space of a raw's decoded preview when it is not sRGB: its own ICC profile, else the
|
||||
/// one the raw's EXIF states (a Sony body set to Adobe RGB writes no profile into the JPEG).
|
||||
/// `None` means sRGB.
|
||||
fn preview_profile(raw: &[u8], icc: Option<&[u8]>) -> Result<Option<Cow<'static, Profile>>, String> {
|
||||
let src = match icc {
|
||||
Some(icc) => Cow::Owned(Profile::parse(icc).map_err(|e| format!("the preview's ICC profile does not parse: {e}"))?),
|
||||
None if photocraft_raw::embedded_preview_color_space(raw) == Some(PreviewColorSpace::AdobeRgb) => Cow::Borrowed(Builtin::AdobeRgbCompat.profile()),
|
||||
None => return Ok(None),
|
||||
};
|
||||
Ok((!src.same_colors(Builtin::Srgb.profile())).then_some(src))
|
||||
}
|
||||
|
||||
/// Fits the colour of a decoded raw to the camera's embedded JPEG (see
|
||||
/// [`photocraft_raw::fit_look`]): picks the smallest preview at least
|
||||
/// `FIT_PREVIEW_EDGE` pixels long (else the largest), decodes it, turns it upright and
|
||||
/// converts it to sRGB when it carries another ICC profile. `Err` says why there is no fit.
|
||||
/// converts it to sRGB when it is in another colour space ([`preview_profile`]). `Err` says
|
||||
/// why there is no fit.
|
||||
pub fn fit_preview_look(raw: &[u8], sensor: &Sensor, opts: &DevelopOptions) -> Result<CameraLook, String> {
|
||||
let previews = photocraft_raw::embedded_previews(raw);
|
||||
let long = |p: &photocraft_raw::Preview| p.width.max(p.height);
|
||||
@@ -152,15 +165,11 @@ pub fn fit_preview_look(raw: &[u8], sensor: &Sensor, opts: &DevelopOptions) -> R
|
||||
}
|
||||
let (w, h) = img.dimensions();
|
||||
let mut rgb: Cow<[u8]> = Cow::Borrowed(img.data());
|
||||
if let Some(icc) = img.icc.as_deref() {
|
||||
let srgb = Builtin::Srgb.profile();
|
||||
let src = Profile::parse(icc).map_err(|e| format!("the preview's ICC profile does not parse: {e}"))?;
|
||||
if !src.same_colors(srgb) {
|
||||
let t = Transform::new(&src, srgb, Intent::RelativeColorimetric, false).map_err(|e| e.to_string())?;
|
||||
let mut out = vec![0u8; rgb.len()];
|
||||
t.convert_u8(&rgb, 3, &mut out, 3, false);
|
||||
rgb = Cow::Owned(out);
|
||||
}
|
||||
if let Some(src) = preview_profile(raw, img.icc.as_deref())? {
|
||||
let t = Transform::new(&src, Builtin::Srgb.profile(), Intent::RelativeColorimetric, false).map_err(|e| e.to_string())?;
|
||||
let mut out = vec![0u8; rgb.len()];
|
||||
t.convert_u8(&rgb, 3, &mut out, 3, false);
|
||||
rgb = Cow::Owned(out);
|
||||
}
|
||||
photocraft_raw::fit_look(sensor, opts, &Reference { width: w, height: h, rgb: &rgb }).map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -223,4 +232,29 @@ mod tests {
|
||||
assert_eq!(camera_name(None, Some("X")), "X");
|
||||
assert_eq!(camera_name(Some("Panasonic"), Some("DC-G9")), "Panasonic DC-G9");
|
||||
}
|
||||
|
||||
/// A Sony body set to Adobe RGB says so only in the raw's EXIF (ColorSpace Uncalibrated, InteropIndex "R03"):
|
||||
/// its preview, which has no ICC profile, is read as Adobe RGB for the colour fit, not as sRGB.
|
||||
#[test]
|
||||
fn a_preview_without_a_profile_takes_the_raws_exif_colour_space() {
|
||||
use photocraft_raw::testgen::{TiffBuilder, Val};
|
||||
let raw = |color_space: u16, index: &str| {
|
||||
let mut t = TiffBuilder::default();
|
||||
let interop = t.ifd(vec![(0x0001, Val::Ascii(index.into()))]);
|
||||
let exif = t.ifd(vec![(0xA001, Val::Short(vec![color_space])), (0xA005, Val::Ifds(vec![interop]))]);
|
||||
t.chain = vec![t.ifd(vec![(271, Val::Ascii("SONY".into())), (34665, Val::Ifds(vec![exif]))])];
|
||||
t.build()
|
||||
};
|
||||
let adobe = raw(0xFFFF, "R03");
|
||||
let srgb = raw(1, "R98");
|
||||
assert!(preview_profile(&adobe, None).unwrap().unwrap().same_colors(Builtin::AdobeRgbCompat.profile()));
|
||||
assert!(preview_profile(&srgb, None).unwrap().is_none());
|
||||
assert!(preview_profile(b"not a raw", None).unwrap().is_none(), "unstated: sRGB");
|
||||
// the preview's own profile wins over the raw's EXIF
|
||||
let srgb_icc = Builtin::Srgb.profile().to_bytes().to_vec();
|
||||
assert!(preview_profile(&adobe, Some(srgb_icc.as_slice())).unwrap().is_none());
|
||||
let p3_icc = Builtin::DisplayP3.profile().to_bytes().to_vec();
|
||||
assert!(preview_profile(&srgb, Some(p3_icc.as_slice())).unwrap().unwrap().same_colors(Builtin::DisplayP3.profile()));
|
||||
assert!(preview_profile(&adobe, Some(b"not an ICC profile")).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Multichannel PSDs: alpha-type channels and the document's resources and global blocks survive
|
||||
//! an import → export → import round trip.
|
||||
|
||||
use photocraft_doc::{ColorIndicates, Knot, NamedPath, Path, PathOp, Subpath};
|
||||
use photocraft_io::*;
|
||||
use photocraft_psd::resources::ImageResource;
|
||||
use photocraft_psd::{ColorMode, Compression, PsdFile, TaggedBlock, Version, testgen};
|
||||
|
||||
/// DisplayInfo (1077) record: RGB colour, opacity (0..100) and kind (0/1 alpha, 2 spot).
|
||||
fn display_record(out: &mut Vec<u8>, rgb: [u16; 3], opacity: u16, kind: u8) {
|
||||
out.extend_from_slice(&0u16.to_be_bytes());
|
||||
for v in [rgb[0], rgb[1], rgb[2], 0] {
|
||||
out.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
out.extend_from_slice(&opacity.to_be_bytes());
|
||||
out.push(kind);
|
||||
}
|
||||
|
||||
/// A two-channel Multichannel file: a cyan spot ink and an alpha channel (masked areas, red 50 %).
|
||||
fn file(depth: u16) -> PsdFile {
|
||||
let mut f = testgen::merged_only(Version::Psd, ColorMode::Multichannel, depth, Compression::Rle, 9, 5);
|
||||
let mut info = 1u32.to_be_bytes().to_vec();
|
||||
display_record(&mut info, [0, 65535, 65535], 0, 2);
|
||||
display_record(&mut info, [65535, 0, 0], 50, 1);
|
||||
f.resources.push(ImageResource::new(1077, info));
|
||||
f
|
||||
}
|
||||
|
||||
fn roundtrip(d: &photocraft_doc::Document) -> (PsdFile, photocraft_doc::Document) {
|
||||
let out = export(d, "x.psd", &ExportOptions::default()).unwrap();
|
||||
let back = PsdFile::from_bytes(&out.bytes).unwrap();
|
||||
let (doc, _) = psd_to_document(&back);
|
||||
(back, doc)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alpha_type_channels_import_as_alpha_and_round_trip() {
|
||||
for depth in [8, 16] {
|
||||
let f = file(depth);
|
||||
let (d, _) = psd_to_document(&f);
|
||||
assert_eq!(d.channels.len(), 2);
|
||||
assert_eq!(d.channels[0].spot.map(|(c, _)| c.to_rgb()), Some([0.0, 1.0, 1.0]));
|
||||
let a = &d.channels[1];
|
||||
assert_eq!(a.spot, None, "an alpha-type channel is not a spot ink ({depth}-bit)");
|
||||
assert_eq!(a.color.to_rgb(), [1.0, 0.0, 0.0]);
|
||||
assert!((a.opacity - 0.5).abs() < 1e-6);
|
||||
assert_eq!(a.indicates, ColorIndicates::MaskedAreas);
|
||||
|
||||
// It still prints as black ink, so the composite is what a black spot channel gives.
|
||||
let mut as_ink = d.clone();
|
||||
as_ink.channels[1].spot = Some((photocraft_color::Color::BLACK, 0.0));
|
||||
assert_eq!(photocraft_compose::flatten(&d).px, photocraft_compose::flatten(&as_ink).px);
|
||||
|
||||
// Saved back unchanged: same DisplayInfo, same planes, same channels on reopening.
|
||||
let (back, d2) = roundtrip(&d);
|
||||
assert_eq!(back.resource(1077).map(|r| r.data.clone()), f.resource(1077).map(|r| r.data.clone()));
|
||||
assert_eq!(back.decode_merged().unwrap(), f.decode_merged().unwrap());
|
||||
assert_eq!(d2.channels[1].spot, None);
|
||||
assert_eq!(d2.channels[1].indicates, ColorIndicates::MaskedAreas);
|
||||
assert!((d2.channels[1].opacity - 0.5).abs() < 1e-6);
|
||||
assert!(d2.channels[0].spot.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resources_and_global_blocks_survive_a_save() {
|
||||
let mut f = file(8);
|
||||
let iptc = vec![0x1c, 2, 0, 0, 2, 0, 4];
|
||||
let print_flags = vec![0, 0, 0, 0, 0, 0, 0, 1, 0];
|
||||
let seed = 7u32.to_be_bytes().to_vec();
|
||||
let alpha_ids = [0u32, 1].iter().flat_map(|v| v.to_be_bytes()).collect::<Vec<u8>>();
|
||||
f.resources.push(ImageResource::new(1028, iptc.clone()));
|
||||
f.resources.push(ImageResource::new(1011, print_flags.clone()));
|
||||
f.resources.push(ImageResource::new(1044, seed.clone()));
|
||||
f.resources.push(ImageResource::new(1053, alpha_ids.clone()));
|
||||
// A target-layer index describes layers, which a Multichannel document doesn't have.
|
||||
f.resources.push(ImageResource::new(1024, vec![0, 0]));
|
||||
let fmsk = vec![0, 0, 0, 0, 0, 50];
|
||||
f.global_blocks.push(TaggedBlock::new(*b"FMsk", fmsk.clone()));
|
||||
let (mut d, _) = psd_to_document(&f);
|
||||
d.guides.horizontal.push(2.0);
|
||||
d.guides.vertical.push(3.0);
|
||||
d.global_light.angle = 60.0;
|
||||
let path =
|
||||
Path::new(vec![Subpath { closed: true, op: PathOp::Combine, knots: vec![Knot::corner(1.0, 1.0), Knot::corner(8.0, 1.0), Knot::corner(4.0, 4.0)] }]);
|
||||
d.paths.push(NamedPath { name: "Outline".into(), path, psd_raw: None });
|
||||
|
||||
let (back, d2) = roundtrip(&d);
|
||||
let res = |id: u16| back.resource(id).map(|r| r.data.clone());
|
||||
assert_eq!(res(1028), Some(iptc));
|
||||
assert_eq!(res(1011), Some(print_flags));
|
||||
assert_eq!(res(1044), Some(seed));
|
||||
assert_eq!(res(1053), Some(alpha_ids));
|
||||
assert_eq!(res(1024), None);
|
||||
let blocks: Vec<_> = back.global_blocks.iter().filter(|b| &b.key == b"FMsk").collect();
|
||||
assert_eq!(blocks.len(), 1);
|
||||
assert_eq!(blocks[0].data, fmsk);
|
||||
assert_eq!(d2.guides.horizontal, vec![2.0]);
|
||||
assert_eq!(d2.guides.vertical, vec![3.0]);
|
||||
assert_eq!(d2.global_light.angle, 60.0);
|
||||
// The file's own saved path and the new one.
|
||||
let names: Vec<&str> = d2.paths.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(names, ["Path 1", "Outline"]);
|
||||
let anchors = |p: &Path| p.subpaths.iter().flat_map(|s| s.knots.iter().map(|k| (k.anchor.x, k.anchor.y))).collect::<Vec<_>>();
|
||||
let (got, want) = (anchors(&d2.paths[1].path), anchors(&d.paths[1].path));
|
||||
assert_eq!(got.len(), want.len());
|
||||
assert!(got.iter().zip(&want).all(|(a, b)| (a.0 - b.0).abs() < 1e-3 && (a.1 - b.1).abs() < 1e-3), "{got:?}");
|
||||
assert_eq!(back.decode_merged().unwrap(), f.decode_merged().unwrap());
|
||||
|
||||
// Alpha identifiers that no longer match the channels are not written.
|
||||
d.channels.pop();
|
||||
let (back, _) = roundtrip(&d);
|
||||
assert!(back.resource(1053).is_none());
|
||||
}
|
||||
|
||||
/// A Photoshop Multichannel file: its alpha-type channel stays an alpha channel and a save keeps
|
||||
/// every resource except the thumbnail (regenerated) and every document-level block.
|
||||
#[cfg(feature = "corpus")]
|
||||
#[test]
|
||||
fn corpus_multichannel_round_trip_keeps_channels_and_resources() {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/psd/psd-tools/colormodes/4x4_16bit_multichannel.psd");
|
||||
assert!(path.is_file(), "{} is missing: run `cargo xtask corpus --all`", path.display());
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let f = PsdFile::from_bytes(&bytes).unwrap();
|
||||
let (d, _) = psd_to_document(&f);
|
||||
let alpha: Vec<_> = d.channels.iter().filter(|c| c.spot.is_none()).collect();
|
||||
assert!(!alpha.is_empty(), "the file's alpha-type channel imports as an alpha channel");
|
||||
for a in &alpha {
|
||||
assert_eq!(a.indicates, ColorIndicates::MaskedAreas);
|
||||
assert_eq!(a.color.to_rgb(), [1.0, 0.0, 0.0]);
|
||||
assert!((a.opacity - 0.5).abs() < 1e-6);
|
||||
}
|
||||
let (back, d2) = roundtrip(&d);
|
||||
assert_eq!(back.resource(1077).map(|r| r.data.clone()), f.resource(1077).map(|r| r.data.clone()));
|
||||
assert_eq!(back.decode_merged().unwrap(), f.decode_merged().unwrap());
|
||||
assert_eq!(d2.channels.iter().filter(|c| c.spot.is_none()).count(), alpha.len());
|
||||
let mut lost: Vec<u16> = f.resources.iter().map(|r| r.id).filter(|id| back.resource(*id).is_none()).collect();
|
||||
lost.retain(|id| *id != 1036);
|
||||
assert!(lost.is_empty(), "resources lost on save: {lost:?}");
|
||||
let keys = |f: &PsdFile| f.global_blocks.iter().map(|b| b.key).collect::<Vec<_>>();
|
||||
assert_eq!(keys(&back), keys(&f));
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! A PSD's Background is recognised by its structure (the bottom record, transparency-protected,
|
||||
//! stored without a transparency channel), whatever its name in the Photoshop language that
|
||||
//! saved the file.
|
||||
|
||||
use photocraft_io::psd_to_document;
|
||||
use photocraft_psd::{ColorMode, Compression, PsdFile, TaggedBlock, Version, testgen};
|
||||
|
||||
/// `testgen::layered` with its bottom layer turned into a Photoshop Background named `name`.
|
||||
fn file(name: &str, transparency_channel: bool) -> PsdFile {
|
||||
let mut f = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle);
|
||||
let bottom = f.layers_mut().first_mut().unwrap();
|
||||
bottom.name = name.bytes().filter(u8::is_ascii).collect();
|
||||
bottom.blocks.retain(|b| &b.key != b"luni" && &b.key != b"lspf");
|
||||
bottom.blocks.push(TaggedBlock::unicode_name(name));
|
||||
bottom.flags.set_transparency_protected(true);
|
||||
if !transparency_channel {
|
||||
bottom.channels.retain(|c| c.id != -1);
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_localized_background_is_the_background() {
|
||||
for name in ["Hintergrund", "背景", "Arrière-plan"] {
|
||||
let (d, _) = psd_to_document(&file(name, false));
|
||||
let bg = d.background().unwrap_or_else(|| panic!("{name}: no Background"));
|
||||
assert_eq!(bg.name, name);
|
||||
assert!(bg.locks.transparency && bg.locks.position, "{name}");
|
||||
assert_eq!(bg.id, d.layers[0].id);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_protected_layer_with_transparency_is_not_the_background() {
|
||||
// Lock Transparent Pixels on an ordinary bottom layer: it keeps its transparency channel.
|
||||
let (d, _) = psd_to_document(&file("Background", true));
|
||||
assert!(d.layers[0].locks.transparency);
|
||||
assert!(d.background().is_none());
|
||||
}
|
||||
@@ -270,7 +270,7 @@ pub struct Texture {
|
||||
pub scale: f32,
|
||||
/// -1..1 (Photoshop's -150..150 mapped to ±1).
|
||||
pub brightness: f32,
|
||||
/// -1..1.
|
||||
/// -1..1: Photoshop's -50..0 mapped to -1..0 and its 0..100 to 0..1.
|
||||
pub contrast: f32,
|
||||
/// Apply the texture to every dab (enables depth jitter) instead of once to the stroke.
|
||||
pub each_tip: bool,
|
||||
@@ -281,6 +281,21 @@ pub struct Texture {
|
||||
pub depth_jitter: Dynamic,
|
||||
}
|
||||
|
||||
impl Texture {
|
||||
/// A pattern value (0..1) after Brightness, Contrast and Invert: the value the mode combines
|
||||
/// with the brush. Measured against Photoshop (#3340): Brightness shifts the pattern by
|
||||
/// `brightness / 255` (±150 moves it 150 levels of 255, not all the way to white or black);
|
||||
/// positive Contrast steepens it around mid-grey by `1 / (1 − c/100)` after the shift (100 is
|
||||
/// a threshold), negative Contrast flattens it by `1 + c/100` before the shift; Invert is last.
|
||||
pub fn level(&self, v: f32) -> f32 {
|
||||
let b = if self.brightness.is_finite() { self.brightness.clamp(-1.0, 1.0) * (150.0 / 255.0) } else { 0.0 };
|
||||
let c = if self.contrast.is_finite() { self.contrast.clamp(-1.0, 1.0) } else { 0.0 };
|
||||
let x = if c >= 0.0 { (v + b - 0.5) / (1.0 - c).max(1e-4) + 0.5 } else { (v - 0.5) * (1.0 + c / 2.0) + 0.5 + b };
|
||||
let x = if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.5 };
|
||||
if self.invert { 1.0 - x } else { x }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Texture {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
|
||||
@@ -6,7 +6,7 @@ use photocraft_raster::Surface;
|
||||
|
||||
use crate::brush::*;
|
||||
use crate::dynamics::{Smoother, smooth_points};
|
||||
use crate::render::{BrushContext, StrokeRenderer, mask_combine, render_stroke};
|
||||
use crate::render::{BrushContext, StrokeRenderer, mask_combine, render_stroke, texture_combine};
|
||||
use crate::tile::GrayTile;
|
||||
use crate::{Dab, Stroke, StrokePoint, dabs};
|
||||
|
||||
@@ -525,7 +525,9 @@ fn texture_modulates_coverage() {
|
||||
b.texture.invert = false;
|
||||
b.texture.brightness = 1.0;
|
||||
let s = paint(&b, &line(20.0, 80.0, 30.0), 100, 60);
|
||||
assert!(s.rgba(46, 30)[3] > 0.9);
|
||||
// +150 lifts a black texel by 150 levels of 255, not to white (#3340).
|
||||
let lifted = s.rgba(46, 30)[3];
|
||||
assert!((lifted - 150.0 / 255.0).abs() < 0.02, "{lifted}");
|
||||
// All modes keep zero coverage at zero and stay in range.
|
||||
for m in [
|
||||
MaskMode::Multiply,
|
||||
@@ -544,6 +546,12 @@ fn texture_modulates_coverage() {
|
||||
let v = mask_combine(m, 0.7, t, 0.8);
|
||||
assert!((0.0..=1.0).contains(&v), "{m:?}");
|
||||
}
|
||||
for t in [0.0, 0.3, 1.0] {
|
||||
assert_eq!(texture_combine(m, 0.0, t, 1.0), 0.0, "{m:?}");
|
||||
let v = texture_combine(m, 0.7, t, 0.8);
|
||||
assert!((0.0..=1.0).contains(&v), "{m:?}");
|
||||
}
|
||||
assert!((0.0..=1.0).contains(&texture_combine(m, 0.7, f32::NAN, f32::INFINITY)), "{m:?}");
|
||||
// Full-white texture never reduces multiply-like masks below the brush.
|
||||
assert!(mask_combine(m, 0.6, 1.0, 1.0) >= 0.6 - 1e-5 || matches!(m, MaskMode::Overlay), "{m:?}");
|
||||
}
|
||||
@@ -555,6 +563,98 @@ fn texture_modulates_coverage() {
|
||||
assert!(d.iter().any(|x| x.depth < 0.6));
|
||||
}
|
||||
|
||||
/// Texture Brightness and Contrast as Photoshop applies them, measured by stroking a 0..255 grey
|
||||
/// ramp pattern in Multiply mode at 100 % depth (the stroke's opacity is then the pattern value):
|
||||
/// (setting, ramp value, opacity read back), in levels of 255 (#3340).
|
||||
#[test]
|
||||
fn texture_brightness_and_contrast_match_photoshop() {
|
||||
let level = |brightness: f32, contrast: f32, invert: bool, v: f32| {
|
||||
// The model's ranges: brightness ±150 → ±1; contrast -50..0 → -1..0, 0..100 → 0..1.
|
||||
let c = if contrast < 0.0 { contrast / 50.0 } else { contrast / 100.0 };
|
||||
let t = Texture { brightness: brightness / 150.0, contrast: c, invert, ..Default::default() };
|
||||
t.level(v / 255.0) * 255.0
|
||||
};
|
||||
for (b, c, inv, v, want) in [
|
||||
(87.0, 0.0, false, 8.0, 95.0),
|
||||
(87.0, 0.0, false, 200.0, 255.0),
|
||||
(-87.0, 0.0, false, 104.0, 17.0),
|
||||
(150.0, 0.0, false, 8.0, 158.0),
|
||||
(0.0, 50.0, false, 104.0, 81.0),
|
||||
(0.0, 50.0, false, 136.0, 145.0),
|
||||
(0.0, -50.0, false, 8.0, 67.0),
|
||||
(0.0, -50.0, false, 248.0, 188.0),
|
||||
(0.0, 100.0, false, 120.0, 0.0),
|
||||
(0.0, 100.0, false, 136.0, 255.0),
|
||||
// Positive contrast after the shift, negative contrast before it.
|
||||
(40.0, 50.0, false, 104.0, 161.0),
|
||||
(40.0, 50.0, false, 40.0, 33.0),
|
||||
(-40.0, -30.0, false, 120.0, 82.0),
|
||||
(-40.0, -30.0, false, 248.0, 172.0),
|
||||
// Invert comes last.
|
||||
(40.0, 0.0, true, 8.0, 207.0),
|
||||
(0.0, 50.0, true, 72.0, 238.0),
|
||||
] {
|
||||
let got = level(b, c, inv, v);
|
||||
assert!((got - want).abs() <= 2.0, "brightness {b}, contrast {c}, invert {inv}, ramp {v}: {got} (Photoshop {want})");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Texture modes that differ from the Dual Brush's, against single Photoshop dabs over a
|
||||
/// 0..255 ramp: (mode, depth, brush coverage, ramp value, opacity read back), in levels of 255.
|
||||
#[test]
|
||||
fn texture_modes_match_photoshop() {
|
||||
use MaskMode::*;
|
||||
for (m, d, v, t, want) in [
|
||||
// Height: a low depth paints the dark valleys only, more depth fills the pattern.
|
||||
(Height, 0.0, 255.0, 8.0, 0.0),
|
||||
(Height, 0.01, 255.0, 8.0, 28.0),
|
||||
(Height, 0.05, 255.0, 8.0, 148.0),
|
||||
(Height, 0.05, 255.0, 136.0, 20.0),
|
||||
(Height, 0.13, 255.0, 8.0, 255.0),
|
||||
(Height, 0.13, 255.0, 152.0, 244.0),
|
||||
(Height, 0.13, 255.0, 248.0, 148.0),
|
||||
(Height, 0.13, 186.0, 88.0, 201.0),
|
||||
(Height, 0.13, 142.0, 104.0, 116.0),
|
||||
(Height, 0.25, 255.0, 248.0, 255.0),
|
||||
// Linear Height: graded by the pattern while the reach stays below its top.
|
||||
(LinearHeight, 0.01, 255.0, 152.0, 15.0),
|
||||
(LinearHeight, 0.05, 255.0, 8.0, 151.0),
|
||||
(LinearHeight, 0.05, 255.0, 152.0, 63.0),
|
||||
(LinearHeight, 0.10, 255.0, 72.0, 240.0),
|
||||
(LinearHeight, 0.13, 101.0, 120.0, 82.0),
|
||||
(LinearHeight, 0.13, 142.0, 104.0, 130.0),
|
||||
// Subtract: the light parts take paint away.
|
||||
(Subtract, 1.0, 255.0, 8.0, 247.0),
|
||||
(Subtract, 1.0, 255.0, 248.0, 7.0),
|
||||
(Subtract, 0.5, 224.0, 72.0, 188.0),
|
||||
// Color Burn / Color Dodge below full depth.
|
||||
(ColorBurn, 0.5, 224.0, 72.0, 207.0),
|
||||
(ColorDodge, 0.5, 99.0, 120.0, 130.0),
|
||||
// Unchanged modes.
|
||||
(Multiply, 0.13, 255.0, 8.0, 223.0),
|
||||
(Darken, 0.5, 255.0, 8.0, 131.0),
|
||||
] {
|
||||
let got = texture_combine(m, v / 255.0, t / 255.0, d) * 255.0;
|
||||
assert!((got - want).abs() <= 3.0, "{m:?} depth {d}, coverage {v}, ramp {t}: {got} (Photoshop {want})");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3340: an imported Height-mode brush at a low depth with a darkened pattern painted nothing.
|
||||
#[test]
|
||||
fn low_depth_height_texture_paints() {
|
||||
let tile = GrayTile::from_fn(8, 8, |x, y| if (x + y) % 2 == 0 { 0.45 } else { 0.6 });
|
||||
for mode in [MaskMode::Height, MaskMode::LinearHeight] {
|
||||
let b = BrushSettings {
|
||||
size: 40.0,
|
||||
texture: Texture { enabled: true, pattern: Pattern::Tile(tile.clone()), mode, depth: 0.13, brightness: -87.0 / 150.0, ..Default::default() },
|
||||
..brush()
|
||||
};
|
||||
let s = paint(&b, &line(20.0, 80.0, 30.0), 100, 60);
|
||||
let a = s.rgba(50, 30)[3];
|
||||
assert!(a > 0.95, "{mode:?}: {a}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dual_brush_intersects() {
|
||||
// Dual tip: small dabs far apart → the stroke survives only where they land.
|
||||
|
||||
@@ -107,7 +107,9 @@ fn dry_media(base: &BrushSettings) -> Vec<BrushPreset> {
|
||||
spacing: 0.12,
|
||||
shape_dynamics: ShapeDynamics { enabled: true, size: pressure_min(0.5), angle: Dynamic::controlled(Control::Direction), ..Default::default() },
|
||||
transfer: transfer(pressure_min(0.3), Dynamic::default()),
|
||||
texture: Texture { mode: MaskMode::Subtract, ..paper(5, 0.7) },
|
||||
// Subtract takes paint away where the pattern is light (#3340); inverting keeps
|
||||
// these presets as they were designed, with the dark parts taking it away.
|
||||
texture: Texture { mode: MaskMode::Subtract, invert: true, ..paper(5, 0.7) },
|
||||
..base.clone()
|
||||
},
|
||||
),
|
||||
@@ -129,6 +131,7 @@ fn dry_media(base: &BrushSettings) -> Vec<BrushPreset> {
|
||||
pattern: Pattern::Procedural { style: PatternStyle::Canvas, size: 64, seed: 2 },
|
||||
depth: 0.55,
|
||||
mode: MaskMode::Subtract,
|
||||
invert: true,
|
||||
..Default::default()
|
||||
},
|
||||
..base.clone()
|
||||
@@ -379,6 +382,7 @@ fn special_effects(base: &BrushSettings) -> Vec<BrushPreset> {
|
||||
enabled: true,
|
||||
pattern: Pattern::Procedural { style: PatternStyle::Canvas, size: 64, seed: 1 },
|
||||
mode: MaskMode::Subtract,
|
||||
invert: true,
|
||||
depth: 0.7,
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -108,6 +108,40 @@ pub fn mask_combine(mode: MaskMode, v: f32, t: f32, d: f32) -> f32 {
|
||||
r.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// How far a Height-mode dab at full depth and coverage reaches into the pattern, in pattern
|
||||
/// ranges (measured against Photoshop, #3340).
|
||||
const HEIGHT_REACH: f32 = 12.0;
|
||||
|
||||
/// Combine brush coverage `v` with a Texture pattern value `t` at `depth` (Brush Settings ›
|
||||
/// Texture). Where it differs from [`mask_combine`] (still used for the Dual Brush) it follows
|
||||
/// Photoshop as measured with single dabs over a grey ramp (#3340):
|
||||
/// - Subtract takes `depth × t` away, so a white pattern removes the most paint.
|
||||
/// - Color Dodge and Color Burn move the pattern toward their neutral colour as depth falls.
|
||||
/// - Height treats the pattern as a height field the brush presses into: the paint reaches
|
||||
/// `12 × depth × v` and fills whatever lies below that, so a low depth paints only the dark
|
||||
/// valleys, from about 17 % the whole pattern is under the paint, and a brighter pattern
|
||||
/// takes paint away.
|
||||
/// - Linear Height is Height, but where the reach stays below the top of the pattern the paint
|
||||
/// fades with the pattern instead of being cut off.
|
||||
pub fn texture_combine(mode: MaskMode, v: f32, t: f32, d: f32) -> f32 {
|
||||
if v <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let r = match mode {
|
||||
MaskMode::Subtract => v - d * t,
|
||||
MaskMode::ColorDodge => v / (1.0 - d * t).max(1e-3),
|
||||
MaskMode::ColorBurn => 1.0 - (1.0 - v) / (1.0 - d + d * t).max(1e-3),
|
||||
// Photoshop steps the depth in 1/255ths here, which shows at the lowest depths.
|
||||
MaskMode::Height => HEIGHT_REACH * (d * 255.0).round() / 255.0 * v - t,
|
||||
MaskMode::LinearHeight => {
|
||||
let reach = HEIGHT_REACH * (d * 255.0).round() / 255.0 * v;
|
||||
if reach < 1.0 { reach * (1.0 - t) } else { reach - t }
|
||||
}
|
||||
_ => mask_combine(mode, v, t, d),
|
||||
};
|
||||
if r.is_finite() { r.clamp(0.0, 1.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A stroke-ready brush: the settings plus prepared tip mips and texture.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BrushContext {
|
||||
@@ -129,11 +163,8 @@ fn prepare_pattern(b: &BrushSettings) -> Option<Arc<PatternImage>> {
|
||||
_ => return None,
|
||||
},
|
||||
};
|
||||
let (br, ct) = (t.brightness.clamp(-1.0, 1.0), t.contrast.clamp(-1.0, 1.0));
|
||||
for v in &mut img.data {
|
||||
let mut x = (*v - 0.5) * (1.0 + ct) + 0.5 + br;
|
||||
x = x.clamp(0.0, 1.0);
|
||||
*v = if t.invert { 1.0 - x } else { x };
|
||||
*v = t.level(*v);
|
||||
}
|
||||
Some(Arc::new(img))
|
||||
}
|
||||
@@ -326,7 +357,7 @@ impl BrushContext {
|
||||
val += (hard - val) * 0.7;
|
||||
}
|
||||
if tex_tip {
|
||||
val = mask_combine(b.texture.mode, val, self.texture_at(x, y), d.depth);
|
||||
val = texture_combine(b.texture.mode, val, self.texture_at(x, y), d.depth);
|
||||
}
|
||||
if wet {
|
||||
val *= wet_factor(rn);
|
||||
@@ -366,7 +397,7 @@ impl BrushContext {
|
||||
m = mask_combine(b.dual_brush.mode, m, dv, 1.0);
|
||||
}
|
||||
if self.texture.is_some() && !b.texture.each_tip {
|
||||
m = mask_combine(b.texture.mode, m, self.texture_at(x, y), b.texture.depth.clamp(0.0, 1.0));
|
||||
m = texture_combine(b.texture.mode, m, self.texture_at(x, y), b.texture.depth.clamp(0.0, 1.0));
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
@@ -137,7 +137,11 @@ impl PsdFile {
|
||||
pub fn to_bytes(&self) -> Result<Vec<u8>> {
|
||||
let v = self.header.version;
|
||||
let psb = v.is_psb();
|
||||
// Reserve the pixel data up front: appending it to an empty Vec reallocates and copies
|
||||
// repeatedly. Everything else (headers, resources, records) is small by comparison.
|
||||
let hint = self.layer_info.as_ref().map_or(0, LayerInfo::channel_data_len).saturating_add(self.image_data.data.len());
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve(hint).map_err(|_| PsdError::LimitExceeded("not enough memory to serialize the file"))?;
|
||||
self.header.write(&mut out);
|
||||
out.put_len(self.color_mode_data.len() as u64, false)?;
|
||||
out.put(&self.color_mode_data);
|
||||
|
||||
+54
-6
@@ -684,15 +684,25 @@ impl LayerInfo {
|
||||
/// block in 4-byte units (psd-tools) misread the blocks after a body that
|
||||
/// is only padded to even.
|
||||
pub fn pad_to(&mut self, version: Version, align: u64) -> Result<()> {
|
||||
let align = align.max(1);
|
||||
let len = self.unpadded_len(version)?;
|
||||
self.padding = Some(vec![0; ((align - len % align) % align) as usize]);
|
||||
self.padding = Some(vec![0; self.pad_len(version, align)?]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Serializes the body (without a length field).
|
||||
pub(crate) fn write_body(&self, out: &mut Vec<u8>, version: Version) -> Result<()> {
|
||||
let start = out.len();
|
||||
/// Number of zero bytes [`Self::pad_to`] would set, without touching `self`.
|
||||
pub(crate) fn pad_len(&self, version: Version, align: u64) -> Result<usize> {
|
||||
let align = align.max(1);
|
||||
let len = self.unpadded_len(version)?;
|
||||
Ok(((align - len % align) % align) as usize)
|
||||
}
|
||||
|
||||
/// Bytes of channel data and their compression fields: the part of the body worth reserving up
|
||||
/// front (the records are small next to the pixels). Saturates instead of overflowing.
|
||||
pub(crate) fn channel_data_len(&self) -> usize {
|
||||
self.layers.iter().flat_map(|l| &l.channels).filter(|c| c.compression.is_some()).fold(0usize, |n, c| n.saturating_add(2).saturating_add(c.data.len()))
|
||||
}
|
||||
|
||||
/// Serializes the body without any trailing padding (the padding field is ignored).
|
||||
pub(crate) fn write_unpadded(&self, out: &mut Vec<u8>, version: Version) -> Result<()> {
|
||||
let n = i16::try_from(self.layers.len()).map_err(|_| PsdError::LimitExceeded("more than 32767 layers"))?;
|
||||
out.put_i16(if self.merged_alpha { -n } else { n });
|
||||
for l in &self.layers {
|
||||
@@ -706,6 +716,13 @@ impl LayerInfo {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Serializes the body (without a length field).
|
||||
pub(crate) fn write_body(&self, out: &mut Vec<u8>, version: Version) -> Result<()> {
|
||||
let start = out.len();
|
||||
self.write_unpadded(out, version)?;
|
||||
match &self.padding {
|
||||
Some(p) => out.put(p),
|
||||
None => {
|
||||
@@ -1022,6 +1039,37 @@ mod tests {
|
||||
assert_eq!(info.layers[0].decode_channel(0, 8, Version::Psd).unwrap(), Vec::<u8>::new());
|
||||
}
|
||||
|
||||
/// Padding without cloning the layers writes the same bytes as `pad_to` on a clone, and the
|
||||
/// channel data length hint is exact.
|
||||
#[test]
|
||||
fn unpadded_write_matches_pad_to_on_a_clone() {
|
||||
use crate::{ColorMode, Compression, testgen};
|
||||
for version in [Version::Psd, Version::Psb] {
|
||||
for depth in [8u16, 16, 32] {
|
||||
for compression in [Compression::Raw, Compression::Rle] {
|
||||
let file = testgen::layered(version, ColorMode::Rgb, depth, compression);
|
||||
let mut info = file.layer_info.clone().unwrap();
|
||||
for align in [1u64, 2, 4, 8] {
|
||||
let mut cloned = info.clone();
|
||||
cloned.pad_to(version, align).unwrap();
|
||||
let mut want = Vec::new();
|
||||
cloned.write_body(&mut want, version).unwrap();
|
||||
let pad = info.pad_len(version, align).unwrap();
|
||||
let mut got = Vec::new();
|
||||
info.write_unpadded(&mut got, version).unwrap();
|
||||
assert!(got.len() >= info.channel_data_len());
|
||||
got.resize(got.len() + pad, 0);
|
||||
assert_eq!(got, want, "{version:?} {depth} {compression:?} align {align}");
|
||||
}
|
||||
info.padding = Some(vec![7, 7]);
|
||||
let mut with_padding = Vec::new();
|
||||
info.write_body(&mut with_padding, version).unwrap();
|
||||
assert!(with_padding.ends_with(&[7, 7]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nondefault_padding_kept() {
|
||||
let info = LayerInfo { padding: Some(vec![0, 0]), ..Default::default() };
|
||||
|
||||
@@ -155,10 +155,12 @@ impl ImageSourceData {
|
||||
let version = self.version;
|
||||
let mut blocks = Vec::with_capacity(self.global_blocks.len() + 2);
|
||||
if let Some(info) = &self.layer_info {
|
||||
let mut info = info.clone();
|
||||
info.pad_to(version, 4)?;
|
||||
// Pad to 4 without cloning the layers (and all their pixel data) just to set `padding`.
|
||||
let pad = info.pad_len(version, 4)?;
|
||||
let mut data = Vec::new();
|
||||
info.write_body(&mut data, version)?;
|
||||
data.try_reserve(info.channel_data_len().saturating_add(pad)).map_err(|_| PsdError::LimitExceeded("not enough memory for the layer data"))?;
|
||||
info.write_unpadded(&mut data, version)?;
|
||||
data.resize(data.len() + pad, 0);
|
||||
blocks.push(padded_block(self.layer_info_key, data));
|
||||
}
|
||||
if let Some(m) = &self.global_layer_mask {
|
||||
|
||||
@@ -74,7 +74,7 @@ pub use crate::develop::{DevelopOptions, Developed, RawInfo, WhiteBalance, devel
|
||||
pub use crate::error::RawError;
|
||||
pub use crate::look::{CameraLook, LookRejected, PROXY_EDGE, Reference, ToneCurve, fit_look};
|
||||
pub use crate::opcodes::GainMap;
|
||||
pub use crate::preview::{Preview, embedded_preview, embedded_previews};
|
||||
pub use crate::preview::{Preview, PreviewColorSpace, embedded_preview, embedded_preview_color_space, embedded_previews};
|
||||
pub use crate::sensor::{BlackLevels, Cfa, Rect, Sensor};
|
||||
|
||||
use crate::tiff::{Tiff, tag};
|
||||
|
||||
@@ -97,3 +97,72 @@ pub fn embedded_previews(bytes: &[u8]) -> Vec<Preview<'_>> {
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// The colour space a raw file states for its embedded previews, which carry no ICC profile of their own.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PreviewColorSpace {
|
||||
Srgb,
|
||||
AdobeRgb,
|
||||
}
|
||||
|
||||
/// The colour space the raw's EXIF gives for the camera's JPEG rendering, for a preview that declares none itself:
|
||||
/// ColorSpace (0xA001) 1 = sRGB, or Uncalibrated (0xFFFF) with the Interoperability IFD's InteropIndex "R03", the
|
||||
/// DCF option file for Adobe RGB (as a Sony body set to Adobe RGB writes; Exif and DCF specifications). `None` when
|
||||
/// the file doesn't say, and for a DNG, whose EXIF describes the original capture while its previews are the
|
||||
/// converter's. A preview's own ICC profile takes precedence over this.
|
||||
pub fn embedded_preview_color_space(bytes: &[u8]) -> Option<PreviewColorSpace> {
|
||||
let t = Tiff::new(bytes)?;
|
||||
let ifd0 = t.ifd_at(t.first_ifd, 0)?;
|
||||
if ifd0.has(tag::DNG_VERSION) {
|
||||
return None;
|
||||
}
|
||||
let exif = t.ifd_at(t.tag_uint(&ifd0, tag::EXIF_IFD)? as usize, 0)?;
|
||||
match t.tag_uint(&exif, tag::COLOR_SPACE)? {
|
||||
1 => Some(PreviewColorSpace::Srgb),
|
||||
0xFFFF => {
|
||||
let interop = t.ifd_at(t.tag_uint(&exif, tag::INTEROP_IFD)? as usize, 0)?;
|
||||
t.raw(interop.get(tag::INTEROP_INDEX)?)?.starts_with(b"R03").then_some(PreviewColorSpace::AdobeRgb)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testgen::{TiffBuilder, Val};
|
||||
|
||||
/// A raw-like TIFF whose EXIF IFD has `color_space` and, when given, an Interoperability IFD with `index`.
|
||||
fn raw_with(color_space: Option<u16>, index: Option<&str>, dng: bool) -> Vec<u8> {
|
||||
let mut t = TiffBuilder::default();
|
||||
let mut exif = Vec::new();
|
||||
if let Some(cs) = color_space {
|
||||
exif.push((tag::COLOR_SPACE, Val::Short(vec![cs])));
|
||||
}
|
||||
if let Some(index) = index {
|
||||
let interop = t.ifd(vec![(tag::INTEROP_INDEX, Val::Ascii(index.into()))]);
|
||||
exif.push((tag::INTEROP_IFD, Val::Ifds(vec![interop])));
|
||||
}
|
||||
let exif = t.ifd(exif);
|
||||
let mut ifd0 = vec![(tag::MAKE, Val::Ascii("SONY".into())), (tag::EXIF_IFD, Val::Ifds(vec![exif]))];
|
||||
if dng {
|
||||
ifd0.push((tag::DNG_VERSION, Val::Byte(vec![1, 6, 0, 0])));
|
||||
}
|
||||
t.chain = vec![t.ifd(ifd0)];
|
||||
t.build()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exif_colour_space_of_the_previews() {
|
||||
assert_eq!(embedded_preview_color_space(&raw_with(Some(1), Some("R98"), false)), Some(PreviewColorSpace::Srgb));
|
||||
assert_eq!(embedded_preview_color_space(&raw_with(Some(0xFFFF), Some("R03"), false)), Some(PreviewColorSpace::AdobeRgb));
|
||||
for (cs, index) in [(Some(0xFFFF), Some("R98")), (Some(0xFFFF), None), (Some(2), Some("R03")), (None, Some("R03"))] {
|
||||
assert_eq!(embedded_preview_color_space(&raw_with(cs, index, false)), None, "{cs:?} {index:?}");
|
||||
}
|
||||
// a DNG's previews are the converter's, whatever the capture was
|
||||
assert_eq!(embedded_preview_color_space(&raw_with(Some(0xFFFF), Some("R03"), true)), None);
|
||||
for junk in [&b""[..], b"II*\0", b"II*\0\x08\0\0\0\xff\xff", b"not a tiff at all"] {
|
||||
assert_eq!(embedded_preview_color_space(junk), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,10 @@ pub(crate) mod tag {
|
||||
pub const EXIF_IFD: u16 = 34665;
|
||||
pub const EXIF_CFA_PATTERN: u16 = 41730;
|
||||
pub const MAKER_NOTE: u16 = 37500;
|
||||
pub const COLOR_SPACE: u16 = 40961;
|
||||
pub const INTEROP_IFD: u16 = 40965;
|
||||
/// In the Interoperability IFD.
|
||||
pub const INTEROP_INDEX: u16 = 1;
|
||||
pub const DNG_VERSION: u16 = 50706;
|
||||
pub const UNIQUE_CAMERA_MODEL: u16 = 50708;
|
||||
pub const CFA_PLANE_COLOR: u16 = 50710;
|
||||
|
||||
@@ -88,6 +88,7 @@ fn exercise(b: &[u8]) {
|
||||
let _ = identify(b);
|
||||
let _ = embedded_preview(b);
|
||||
let _ = embedded_previews(b);
|
||||
let _ = embedded_preview_color_space(b);
|
||||
let opts = DevelopOptions { limits: Limits { max_alloc: 64 << 20, ..Limits::default() }, ..Default::default() };
|
||||
if let Ok(s) = decode(b, &opts.limits) {
|
||||
for m in [Demosaic::Bilinear, Demosaic::Ahd] {
|
||||
|
||||
+51
-9
@@ -140,9 +140,11 @@ pub fn parse_txt2(data: &[u8]) -> Option<E> {
|
||||
ed::parse(&wrapped).ok().filter(|v| matches!(v, E::Dict(_)))
|
||||
}
|
||||
|
||||
/// Applies the automatic kerning modes that Photoshop keeps only in `Txt2` (EngineData writes
|
||||
/// Optical and "0" alike as `AutoKerning true`) to `layer`, read from `tysh`. Only when the
|
||||
/// layer's `TextIndex` entry still holds the layer's text (an edit elsewhere leaves `Txt2`
|
||||
/// Applies what Photoshop keeps only in `Txt2` to `layer`, read from `tysh`: the automatic
|
||||
/// kerning modes (EngineData writes Optical and "0" alike as `AutoKerning true`) and the
|
||||
/// OpenType settings besides (discretionary) ligatures: stylistic sets, contextual alternates,
|
||||
/// swashes and the rest ([`TXT2_FEATURES`]), which Photoshop leaves out of EngineData. Only when
|
||||
/// the layer's `TextIndex` entry still holds the layer's text (an edit elsewhere leaves `Txt2`
|
||||
/// stale).
|
||||
///
|
||||
/// Observed layout: `Txt2 /1` is the list of text objects; an object's `/0` is its text model
|
||||
@@ -168,11 +170,10 @@ pub fn apply_txt2(layer: &mut TextLayer, tysh: &[u8], txt2: &E) {
|
||||
let Some(style_runs) = model.path(&["6", "0"]).and_then(E::as_array) else {
|
||||
return;
|
||||
};
|
||||
let modes: Vec<(f64, Option<i64>)> =
|
||||
style_runs.iter().map(|r| (r.get("1").and_then(E::as_f64).unwrap_or(0.0), r.path(&["0", "0", "6", "11"]).and_then(E::as_i64))).collect();
|
||||
let lens = utf16_to_byte_lengths(text, &modes.iter().map(|m| m.0).collect::<Vec<_>>());
|
||||
// Auto-kern mode per byte segment, then split the model runs at segment boundaries.
|
||||
let mut segs: Vec<(usize, Option<i64>)> = lens.into_iter().zip(modes.iter().map(|m| m.1)).collect();
|
||||
let styles: Vec<(f64, Option<&E>)> = style_runs.iter().map(|r| (r.get("1").and_then(E::as_f64).unwrap_or(0.0), r.path(&["0", "0", "6"]))).collect();
|
||||
let lens = utf16_to_byte_lengths(text, &styles.iter().map(|m| m.0).collect::<Vec<_>>());
|
||||
// Txt2 style per byte segment, then split the model runs at segment boundaries.
|
||||
let mut segs: Vec<(usize, Option<&E>)> = lens.into_iter().zip(styles.iter().map(|m| m.1)).collect();
|
||||
segs.retain(|s| s.0 > 0);
|
||||
let runs = layer.char_runs();
|
||||
let mut out: Vec<TextRun> = Vec::new();
|
||||
@@ -187,14 +188,18 @@ pub fn apply_txt2(layer: &mut TextLayer, tysh: &[u8], txt2: &E) {
|
||||
}
|
||||
let piece_end = if at < seg_end { end.min(seg_end) } else { end };
|
||||
let mut style = r.style.clone();
|
||||
let txt2_style = segs.get(si).and_then(|s| s.1).filter(|_| at < seg_end);
|
||||
// Txt2 has the exact mode (EngineData's reading also marks neighbours of manual
|
||||
// kerns manual, like Photoshop's legacy reader).
|
||||
match segs.get(si).and_then(|s| s.1).filter(|_| at < seg_end) {
|
||||
match txt2_style.and_then(|st| st.get("11")).and_then(E::as_i64) {
|
||||
Some(0) => style.kerning = Kerning::Off,
|
||||
Some(1) => style.kerning = Kerning::Metrics,
|
||||
Some(2) => style.kerning = Kerning::Optical,
|
||||
_ => {}
|
||||
}
|
||||
if let Some(st) = txt2_style {
|
||||
add_txt2_features(&mut style, st);
|
||||
}
|
||||
let len = piece_end - at;
|
||||
match out.last_mut() {
|
||||
Some(last) if last.style == style => last.len += len,
|
||||
@@ -207,6 +212,43 @@ pub fn apply_txt2(layer: &mut TextLayer, tysh: &[u8], txt2: &E) {
|
||||
layer.sync_summary();
|
||||
}
|
||||
|
||||
/// OpenType settings of a `Txt2` style that are on/off flags, by style key, as Photoshop
|
||||
/// writes them (each turned on alone in the Character panel's OpenType settings and read back):
|
||||
/// `/20` Contextual Alternates, `/23` Fractions, `/24` Ordinals, `/25` Swash, `/26` Titling
|
||||
/// Alternates, `/28` Stylistic Alternates, `/29` Ornaments. (`/18` and `/19` are the standard and
|
||||
/// discretionary ligatures, which EngineData carries too; `/27` is Arabic connection forms.)
|
||||
pub const TXT2_FEATURES: [(&str, &str); 7] = [("20", "calt"), ("23", "frac"), ("24", "ordn"), ("25", "swsh"), ("26", "titl"), ("28", "salt"), ("29", "ornm")];
|
||||
|
||||
/// The `Txt2` style key holding the Stylistic Sets as a bit mask: bit n is set n + 1
|
||||
/// (`ss01`..`ss20`).
|
||||
pub const TXT2_STYLISTIC_SETS: &str = "85";
|
||||
|
||||
/// Sets in `style` the OpenType features a `Txt2` style dictionary turns on ([`TXT2_FEATURES`]
|
||||
/// and the Stylistic Sets mask). A feature the style already sets keeps its value. A flag that is
|
||||
/// off changes nothing, except Contextual Alternates: shapers apply `calt` by default, Photoshop
|
||||
/// only when it is on (its default is off), so off is written as `calt` 0.
|
||||
fn add_txt2_features(style: &mut CharStyle, txt2_style: &E) {
|
||||
let mut set = |tag: String, value: u16| {
|
||||
if !style.features.iter().any(|f| f.tag == tag) {
|
||||
style.features.push(photocraft_doc::text::FontFeature { tag, value });
|
||||
}
|
||||
};
|
||||
for (key, tag) in TXT2_FEATURES {
|
||||
match txt2_style.get(key).and_then(E::as_bool) {
|
||||
Some(true) => set(tag.to_string(), 1),
|
||||
Some(false) if tag == "calt" => set(tag.to_string(), 0),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// A mask beyond the 20 sets is not Photoshop's: ignore it.
|
||||
let sets = txt2_style.get(TXT2_STYLISTIC_SETS).and_then(E::as_i64).filter(|m| (0..1 << 20).contains(m)).unwrap_or(0);
|
||||
for n in 0..20 {
|
||||
if sets & (1 << n) != 0 {
|
||||
set(format!("ss{:02}", n + 1), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a [`TextLayer`] (model, text and transform; no cache, no `psd_raw`) from `TySh` data.
|
||||
pub fn text_layer_from_tysh(data: &[u8], dpi: f32) -> Option<TextLayer> {
|
||||
let t = parse_tysh(data)?;
|
||||
|
||||
@@ -72,7 +72,7 @@ fn draw(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only_c
|
||||
let offsets: &[(f64, f64)] =
|
||||
if bold { &[(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (0.7, 0.7), (-0.7, -0.7), (0.7, -0.7), (-0.7, 0.7)] } else { &[(0.0, 0.0)] };
|
||||
for &(ox, oy) in offsets {
|
||||
let local = Xform([1.0, 0.0, 0.0, 1.0, ox * r, oy * r]).mul(&glyph);
|
||||
let local = glyph.mul(&Xform([1.0, 0.0, 0.0, 1.0, ox * r, oy * r]));
|
||||
let settings = DrawSettings::unhinted(Size::new(face.size_px), LocationRef::new(&coords));
|
||||
match warp {
|
||||
Some(w) => {
|
||||
|
||||
@@ -381,6 +381,41 @@ fn styles_change_pixels() {
|
||||
assert!(hrect.width() as f32 > prect.width() as f32 * 1.7);
|
||||
}
|
||||
|
||||
/// #3705: Faux bold dilation must scale with horizontal and vertical glyph scaling.
|
||||
#[test]
|
||||
fn faux_bold_scales_with_glyph_scaling() {
|
||||
let mut e = TextEngine::new();
|
||||
let base = CharStyle { size_pt: 40.0, ..Default::default() };
|
||||
let ink = |e: &mut TextEngine, s: CharStyle| {
|
||||
let (_, r) = e.render(&TextLayer { transform: Affine::translate(5.0, 50.0), ..styled("Hi", s) }, 72.0, PixelFormat::RGBA8);
|
||||
(alpha_sum(&r.surface, r.rect), r.rect)
|
||||
};
|
||||
let (_plain, prect) = ink(&mut e, base.clone());
|
||||
let (_bold, brect) = ink(&mut e, CharStyle { faux_bold: true, ..base.clone() });
|
||||
let unscaled_extra_w = brect.width() - prect.width();
|
||||
let unscaled_extra_h = brect.height() - prect.height();
|
||||
|
||||
// With 2x horizontal scale, the horizontal dilation scales with the glyph:
|
||||
let hscaled = CharStyle { size_pt: 40.0, horizontal_scale: 2.0, ..Default::default() };
|
||||
let (_, phrect) = ink(&mut e, hscaled.clone());
|
||||
let (_, bhrect) = ink(&mut e, CharStyle { faux_bold: true, ..hscaled });
|
||||
let hscaled_extra_w = bhrect.width() - phrect.width();
|
||||
assert!(
|
||||
hscaled_extra_w >= unscaled_extra_w * 2 - 1 && hscaled_extra_w <= unscaled_extra_w * 2 + 1,
|
||||
"hscaled extra width {hscaled_extra_w} vs unscaled {unscaled_extra_w}"
|
||||
);
|
||||
|
||||
// With 2x vertical scale, the vertical dilation scales with the glyph:
|
||||
let vscaled = CharStyle { size_pt: 40.0, vertical_scale: 2.0, ..Default::default() };
|
||||
let (_, pvrect) = ink(&mut e, vscaled.clone());
|
||||
let (_, bvrect) = ink(&mut e, CharStyle { faux_bold: true, ..vscaled });
|
||||
let vscaled_extra_h = bvrect.height() - pvrect.height();
|
||||
assert!(
|
||||
vscaled_extra_h >= unscaled_extra_h * 2 - 1 && vscaled_extra_h <= unscaled_extra_h * 2 + 1,
|
||||
"vscaled extra height {vscaled_extra_h} vs unscaled {unscaled_extra_h}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multicolor_runs() {
|
||||
let mut e = TextEngine::new();
|
||||
@@ -647,6 +682,11 @@ fn warp_bends_rendered_text_and_outlines() {
|
||||
/// `Txt2` as Photoshop writes it (a bare `/key value` sequence; text objects at `/1 /1`, style
|
||||
/// runs at `/0 /6 /0`, auto-kern mode at `/11`), for the layer text `text`.
|
||||
fn txt2_with_modes(text: &str, modes: &[(usize, i64)]) -> Vec<u8> {
|
||||
txt2_with_styles(text, &modes.iter().map(|(len, m)| (*len, format!("/11 {m}"))).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// [`txt2_with_modes`] with each style run's keys given as EngineData text (`"/11 1 /85 2"`).
|
||||
fn txt2_with_styles(text: &str, styles: &[(usize, String)]) -> Vec<u8> {
|
||||
let mut v = b"\n\n/98 << /0 14 >> /0 << >> /1 << /1 [ << /0 << /0 (\xfe\xff".to_vec();
|
||||
for u in format!("{text}\r").encode_utf16() {
|
||||
let b = u.to_be_bytes();
|
||||
@@ -658,8 +698,8 @@ fn txt2_with_modes(text: &str, modes: &[(usize, i64)]) -> Vec<u8> {
|
||||
}
|
||||
}
|
||||
v.extend_from_slice(b") /6 << /0 [ ");
|
||||
for (len, m) in modes {
|
||||
v.extend_from_slice(format!("<< /0 << /0 << /0 (\u{fe}\u{ff}) /6 << /0 0 /11 {m} >> >> >> /1 {len} >> ").as_bytes());
|
||||
for (len, keys) in styles {
|
||||
v.extend_from_slice(format!("<< /0 << /0 << /0 (\u{fe}\u{ff}) /6 << /0 0 {keys} >> >> >> /1 {len} >> ").as_bytes());
|
||||
}
|
||||
v.extend_from_slice(b"] >> >> >> ] >>");
|
||||
v
|
||||
@@ -706,6 +746,55 @@ fn txt2_carries_optical_kerning() {
|
||||
assert!(l.char_runs().iter().all(|r| r.style.kerning == Kerning::Optical));
|
||||
}
|
||||
|
||||
/// #3617: Photoshop keeps Stylistic Sets, Contextual Alternates, Swash and the other OpenType
|
||||
/// settings besides (discretionary) ligatures only in `Txt2`. Import reads them, so the layout
|
||||
/// our engine draws when the type is edited keeps Photoshop's glyphs instead of falling back to
|
||||
/// the default ones.
|
||||
#[test]
|
||||
fn txt2_carries_opentype_features() {
|
||||
let feats = |l: &TextLayer| l.char_runs().iter().map(|r| r.style.features.iter().map(|f| (f.tag.clone(), f.value)).collect::<Vec<_>>()).collect::<Vec<_>>();
|
||||
let f = |tag: &str, value: u16| (tag.to_string(), value);
|
||||
// "Il->36" plus the engine's closing break: Stylistic Set 2 (mask 2), Contextual Alternates
|
||||
// and Swash on "Il"; Contextual Alternates off (Photoshop's default), Stylistic Set 1 and
|
||||
// Fractions on the rest.
|
||||
let text = "Il->36";
|
||||
let plain = styled(text, CharStyle { font_family: "Inter".into(), ..Default::default() });
|
||||
let tysh = with_text_index(&crate::psd::build_tysh(&plain, 72.0, None), 0);
|
||||
let styles = [(2, "/11 1 /18 true /19 false /20 true /25 true /85 2".to_string()), (5, "/11 1 /20 false /23 true /85 1".to_string())];
|
||||
let txt2 = crate::psd::parse_txt2(&txt2_with_styles(text, &styles)).unwrap();
|
||||
let mut back = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap();
|
||||
assert_eq!(feats(&back), vec![Vec::<(String, u16)>::new()], "EngineData alone doesn't have them");
|
||||
crate::psd::apply_txt2(&mut back, &tysh, &txt2);
|
||||
assert_eq!(feats(&back), vec![vec![f("calt", 1), f("swsh", 1), f("ss02", 1)], vec![f("calt", 0), f("frac", 1), f("ss01", 1)]]);
|
||||
assert_eq!(back.char_runs().iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 4]);
|
||||
// What editing shows (our layout) has Photoshop's glyphs: Inter's `ss02` draws another I and
|
||||
// l, `ss01` another 3 and 6, and `->` stays two glyphs without `calt` (with it, an arrow).
|
||||
let mut e = TextEngine::new();
|
||||
let ids = |e: &mut TextEngine, t: &TextLayer| e.layout(t, 72.0).glyphs.iter().map(|g| g.id).collect::<Vec<_>>();
|
||||
let with = |len: usize, tags: &[(&str, u16)]| TextRun {
|
||||
len,
|
||||
style: CharStyle {
|
||||
features: tags.iter().map(|(tag, value)| FontFeature { tag: (*tag).into(), value: *value }).collect(),
|
||||
..back.char_runs()[0].style.clone()
|
||||
},
|
||||
};
|
||||
let mut expected = back.clone();
|
||||
expected.runs = vec![with(2, &[("ss02", 1)]), with(4, &[("calt", 0), ("ss01", 1)])];
|
||||
let shown = ids(&mut e, &back);
|
||||
assert_eq!(shown, ids(&mut e, &expected));
|
||||
let defaults = ids(&mut e, &crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap());
|
||||
assert_eq!((shown.len(), defaults.len()), (6, 5), "`->` is two glyphs, as in Photoshop, not an arrow");
|
||||
assert!(shown.first() != defaults.first() && shown.last() != defaults.last(), "{shown:?} vs {defaults:?}");
|
||||
// A feature the style already sets (from EngineData, read first) keeps its value; masks and
|
||||
// flags of the wrong type, masks beyond the 20 sets and unknown keys change nothing.
|
||||
let mut t = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap();
|
||||
t.runs = vec![TextRun { len: text.len(), style: CharStyle { features: vec![FontFeature { tag: "ss01".into(), value: 0 }], ..Default::default() } }];
|
||||
let odd =
|
||||
[(1, "/85 1".to_string()), (1, "/85 (x) /20 (x) /25 (true)".to_string()), (1, "/85 -1".to_string()), (4, "/85 99999999999 /999 true".to_string())];
|
||||
crate::psd::apply_txt2(&mut t, &tysh, &crate::psd::parse_txt2(&txt2_with_styles(text, &odd)).unwrap());
|
||||
assert_eq!(feats(&t), vec![vec![f("ss01", 0)]]);
|
||||
}
|
||||
|
||||
/// A `Txt2` written by [`crate::psd::build_txt2`] (what PSD export writes for the type layers)
|
||||
/// restores every auto-kern mode on import (#1348: a new Optical layer used to reopen as
|
||||
/// Metrics, because EngineData's `AutoKerning true` covers both).
|
||||
|
||||
@@ -395,14 +395,9 @@ fn pattern_swatch(ui: &mut egui::Ui, tx: &paint::Texture) {
|
||||
_ => paint::tile::PatternImage { width: 1, height: 1, data: vec![0.5] },
|
||||
},
|
||||
};
|
||||
let (br, ct) = (tx.brightness.clamp(-1.0, 1.0), tx.contrast.clamp(-1.0, 1.0));
|
||||
let px: Vec<u8> = (0..n * n)
|
||||
.flat_map(|i| {
|
||||
let v = img.sample_wrap((i % n) as f32, (i / n) as f32);
|
||||
let mut x = ((v - 0.5) * (1.0 + ct) + 0.5 + br).clamp(0.0, 1.0);
|
||||
if tx.invert {
|
||||
x = 1.0 - x;
|
||||
}
|
||||
let x = tx.level(img.sample_wrap((i % n) as f32, (i / n) as f32));
|
||||
let g = (x * 255.0).round() as u8;
|
||||
[g, g, g, 255]
|
||||
})
|
||||
|
||||
@@ -2089,7 +2089,7 @@ const STUDIO_TAB_GAP: f32 = 4.0;
|
||||
fn pro_tab_title(app: &PhotocraftApp, i: usize) -> String {
|
||||
let Some(st) = app.session.documents().get(i) else { return String::new() };
|
||||
let zoom = app.ui.views.get(i).map_or(100.0, |v| v.zoom * 100.0);
|
||||
let active_layer = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| !(l.name == "Background" && l.locks.transparency));
|
||||
let active_layer = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| !st.doc.is_background(l.id));
|
||||
let mask = app.session.active_index() == Some(i) && app.ui.mask_target && active_layer.is_some_and(|l| l.mask.is_some());
|
||||
let model = if mask { tl!("Layer Mask").to_string() } else { mode_label(&st.doc).to_string() };
|
||||
let layer = active_layer.map(|l| format!("{}, ", l.name)).unwrap_or_default();
|
||||
|
||||
@@ -3,15 +3,16 @@
|
||||
//! Rulers & Grids toggles. Every edit dispatches an engine or view command, so the panel stays thin.
|
||||
|
||||
use egui::{Align2, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2};
|
||||
use photocraft_doc::{ColorMode, Document, Layer, LayerContent, LayerId, SampleType};
|
||||
use photocraft_doc::{ColorMode, Document, Layer, LayerId, SampleType};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::theme::Tokens;
|
||||
use crate::{PhotocraftApp, icons, widgets};
|
||||
|
||||
/// Photoshop's Background layer: the locked, opaque raster layer at the bottom of the stack.
|
||||
/// Photoshop's Background layer: the locked, opaque raster layer at the bottom of the stack,
|
||||
/// whatever its (localized) name ([`Document::background`]).
|
||||
pub fn is_background(doc: &Document, l: &Layer) -> bool {
|
||||
l.name == "Background" && l.locks.transparency && matches!(l.content, LayerContent::Raster(_)) && doc.layers.first().is_some_and(|b| b.id == l.id)
|
||||
doc.is_background(l.id)
|
||||
}
|
||||
|
||||
/// Does the Properties panel show the Document view? (No layer selected, or the Background layer.)
|
||||
|
||||
@@ -295,8 +295,20 @@ pub fn end_rename(ctx: &egui::Context, commit: bool) -> Option<(String, Value)>
|
||||
if commit { r.commit_action() } else { None }
|
||||
}
|
||||
|
||||
/// Where Tab or ⇧Tab sends a rename: the layer it left and whether the next one is above.
|
||||
fn next_rename_id() -> egui::Id {
|
||||
egui::Id::new("layer-rename-next")
|
||||
}
|
||||
|
||||
/// The rename that Tab (`up` false) or ⇧Tab (`up` true) just left on `layer`, for the Layers panel
|
||||
/// to continue on the layer below or above, as Photoshop does. Taken once.
|
||||
pub fn take_next_rename(ctx: &egui::Context) -> Option<(u64, bool)> {
|
||||
ctx.data_mut(|d| d.remove_temp::<(u64, bool)>(next_rename_id()))
|
||||
}
|
||||
|
||||
/// Draw the rename field of `layer` in `rect` when it is the one being renamed, and handle its
|
||||
/// keys and focus. Returns the rename command when it was committed this frame.
|
||||
/// keys and focus. Returns the rename command when it was committed this frame. Tab and ⇧Tab
|
||||
/// commit too and ask for the next rename ([`take_next_rename`]).
|
||||
pub fn rename_field(ui: &mut egui::Ui, layer: u64, rect: Rect) -> Option<(String, Value)> {
|
||||
let ctx = ui.ctx().clone();
|
||||
let mut r = rename(&ctx).filter(|r| r.layer == layer)?;
|
||||
@@ -316,6 +328,10 @@ pub fn rename_field(ui: &mut egui::Ui, layer: u64, rect: Rect) -> Option<(String
|
||||
return None;
|
||||
}
|
||||
let (enter, tab, esc) = ctx.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Tab), i.key_pressed(egui::Key::Escape)));
|
||||
if tab {
|
||||
let up = ctx.input(|i| i.modifiers.shift);
|
||||
ctx.data_mut(|d| d.insert_temp(next_rename_id(), (layer, up)));
|
||||
}
|
||||
if esc {
|
||||
store(&ctx, None);
|
||||
None
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! #314: renaming a layer in place works like Photoshop. A click anywhere else, Enter or Tab
|
||||
//! commits; Esc cancels; only one rename is open at a time, and starting another (double-click,
|
||||
//! the context menu or Layer › Rename Layer) commits the first.
|
||||
//! the context menu or Layer › Rename Layer) commits the first. Tab then renames the layer below,
|
||||
//! ⇧Tab the layer above.
|
||||
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
@@ -127,7 +128,8 @@ fn enter_and_tab_commit_and_escape_cancels() {
|
||||
start(&mut h, b);
|
||||
type_text(&mut h, "By Tab");
|
||||
key(&mut h, Key::Tab);
|
||||
assert_eq!((name(&h, b), renaming(&h.ctx)), ("By Tab".into(), None));
|
||||
assert_eq!((name(&h, b), renaming(&h.ctx)), ("By Tab".into(), Some(a)), "Tab commits and renames the layer below");
|
||||
key(&mut h, Key::Escape);
|
||||
|
||||
start(&mut h, c);
|
||||
type_text(&mut h, "Never");
|
||||
@@ -143,6 +145,28 @@ fn enter_and_tab_commit_and_escape_cancels() {
|
||||
assert_eq!(name(&h, c), "Gamma");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_tab_renames_the_layer_above_and_tab_at_the_bottom_ends() {
|
||||
let (mut h, [a, b, c]) = harness(1.0);
|
||||
start(&mut h, b);
|
||||
type_text(&mut h, "Middle");
|
||||
h.event(Event::ModifiersChanged(Modifiers::SHIFT));
|
||||
h.event(Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT });
|
||||
h.event(Event::Key { key: Key::Tab, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::SHIFT });
|
||||
h.run_steps(1);
|
||||
h.event(Event::ModifiersChanged(Modifiers::NONE));
|
||||
h.run_steps(2);
|
||||
assert_eq!((name(&h, b), renaming(&h.ctx)), ("Middle".into(), Some(c)), "⇧Tab renames the layer above");
|
||||
// Typing replaces the next layer's name too, as the whole name starts selected.
|
||||
type_text(&mut h, "Top");
|
||||
key(&mut h, Key::Enter);
|
||||
assert_eq!((name(&h, c), renaming(&h.ctx)), ("Top".into(), None));
|
||||
// Tab from the lowest layer ends the rename: the Background below isn't renamed in place.
|
||||
start(&mut h, a);
|
||||
key(&mut h, Key::Tab);
|
||||
assert_eq!(renaming(&h.ctx), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starting_another_rename_commits_the_first_and_only_one_is_open() {
|
||||
for ppp in [1.0, 2.0] {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Photoshop's layer and selection keys reach their commands: ⌘, toggles visibility, ⌘\ targets
|
||||
//! the mask, / toggles Lock Transparent Pixels, ⌘⌥2 loads luminosity, ⌘⌥⌫ fills from history.
|
||||
|
||||
use egui::{Key, Modifiers};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
|
||||
fn app() -> PhotocraftApp {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 20, "height": 10})).unwrap();
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
fn press(app: &mut PhotocraftApp, key: Key, modifiers: Modifiers) {
|
||||
let ctx = egui::Context::default();
|
||||
let raw = egui::RawInput {
|
||||
events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }],
|
||||
..Default::default()
|
||||
};
|
||||
ctx.begin_pass(raw);
|
||||
crate::shortcuts::handle(app, &ctx);
|
||||
ctx.end_pass().textures_delta.clear();
|
||||
}
|
||||
|
||||
fn active(app: &PhotocraftApp) -> &photocraft_doc::Layer {
|
||||
let st = app.session.active().unwrap();
|
||||
st.doc.layer(st.active_layer.unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_comma_toggles_the_layers_visibility() {
|
||||
let mut app = app();
|
||||
press(&mut app, Key::Comma, Modifiers::COMMAND);
|
||||
assert!(!active(&app).visible);
|
||||
press(&mut app, Key::Comma, Modifiers::COMMAND);
|
||||
assert!(active(&app).visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slash_toggles_lock_transparent_pixels() {
|
||||
let mut app = app();
|
||||
press(&mut app, Key::Slash, Modifiers::NONE);
|
||||
assert!(active(&app).locks.transparency);
|
||||
press(&mut app, Key::Slash, Modifiers::NONE);
|
||||
assert!(!active(&app).locks.transparency);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_backslash_targets_the_layer_mask() {
|
||||
let mut app = app();
|
||||
app.run("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
app.run("channel.target.composite", json!({})).unwrap();
|
||||
press(&mut app, Key::Backslash, Modifiers::COMMAND);
|
||||
assert_eq!(app.session.active().unwrap().channel_view.target, photocraft_engine::channel_cmds::ChannelTarget::LayerMask);
|
||||
assert!(app.ui.mask_target && app.layer_mask_targeted(), "the Layers panel targets the mask too");
|
||||
// Ctrl+2 goes back to the layer's pixels, in the Layers panel and for the tools.
|
||||
press(&mut app, Key::Num2, Modifiers::COMMAND);
|
||||
assert_eq!(app.session.active().unwrap().channel_view.target, photocraft_engine::channel_cmds::ChannelTarget::Composite);
|
||||
assert!(!app.ui.mask_target && !app.layer_mask_targeted());
|
||||
// The same after targeting the mask by its thumbnail (the panel's own flag).
|
||||
app.ui.mask_target = true;
|
||||
app.sync_mask_targets();
|
||||
press(&mut app, Key::Num2, Modifiers::COMMAND);
|
||||
assert!(!app.ui.mask_target && !app.layer_mask_targeted());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_alt_2_loads_luminosity() {
|
||||
let mut app = app();
|
||||
press(&mut app, Key::Num2, Modifiers::COMMAND | Modifiers::ALT);
|
||||
assert!(app.session.active().unwrap().doc.selection.is_some(), "the white image's luminosity selects it all");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_alt_backspace_fills_from_history() {
|
||||
// The Background exists in the oldest state, so its pixels come back from there.
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 20, "height": 10})).unwrap();
|
||||
app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap();
|
||||
app.run("edit.fillForeground", json!({})).unwrap();
|
||||
assert_eq!(active(&app).surface().unwrap().pixel(3, 3)[1], 0.0, "red");
|
||||
press(&mut app, Key::Backspace, Modifiers::COMMAND | Modifiers::ALT);
|
||||
assert_eq!(active(&app).surface().unwrap().pixel(3, 3)[1], 1.0, "white again");
|
||||
}
|
||||
|
||||
/// ⌥-click a layer's thumbnail: select it and fit its content on screen.
|
||||
#[test]
|
||||
fn alt_click_on_a_layer_thumbnail_fits_the_layer() {
|
||||
use egui::{Event, PointerButton, pos2, vec2};
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let small = s.execute("layer.new.layer", json!({"name": "Small"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("select.rect", json!({"x": 300, "y": 200, "width": 20, "height": 10})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "black"})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Top"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(move |cc| {
|
||||
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
|
||||
PhotocraftApp::new(s, crate::Services::default())
|
||||
});
|
||||
let ctx = h.ctx.clone();
|
||||
let (r, _) = crate::control::ControlRequest::new("ui.set", json!({"dock": {"collapsed": ["color", "properties", "history", "navigator"]}}));
|
||||
crate::control::handle(h.state_mut(), &ctx, &r);
|
||||
h.run_steps(8);
|
||||
let before = h.state().ui.views[0].clone();
|
||||
let row = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == small).unwrap().row;
|
||||
let at = pos2(row.left() + 46.0, row.center().y);
|
||||
h.hover_at(at);
|
||||
h.event(Event::ModifiersChanged(Modifiers::ALT));
|
||||
h.run_steps(1);
|
||||
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT });
|
||||
h.run_steps(1);
|
||||
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT });
|
||||
h.run_steps(1);
|
||||
h.event(Event::ModifiersChanged(Modifiers::NONE));
|
||||
h.run_steps(3);
|
||||
let app = h.state();
|
||||
assert_eq!(app.session.active().unwrap().active_layer, Some(photocraft_doc::LayerId(small)));
|
||||
let v = &app.ui.views[0];
|
||||
assert_eq!(v.center, [310.0, 205.0], "centred on the layer's content");
|
||||
assert!(v.zoom > before.zoom * 4.0, "zoomed in on 20 × 10 px: {} -> {}", before.zoom, v.zoom);
|
||||
}
|
||||
@@ -890,6 +890,16 @@ impl PhotocraftApp {
|
||||
if gate.is_some() {
|
||||
self.session.authorize = None;
|
||||
}
|
||||
// An explicit channel target (⌘2, ⌘\, ⌘3…) decides what the Layers panel targets too:
|
||||
// ⌘2 after the mask was targeted goes back to the layer's pixels.
|
||||
if result.is_ok() && id.starts_with("channel.target") {
|
||||
if let Some(t) = self.session.active().map(|st| st.channel_view.target) {
|
||||
use photocraft_engine::channel_cmds::ChannelTarget;
|
||||
self.ui.mask_target = t == ChannelTarget::LayerMask;
|
||||
self.ui.vector_mask_target = t == ChannelTarget::VectorMask;
|
||||
}
|
||||
self.sync_mask_targets();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
@@ -1715,6 +1725,8 @@ impl eframe::App for PhotocraftApp {
|
||||
brush_picker::persist(self, &ctx);
|
||||
// Tool options are remembered between launches the same way (#2814).
|
||||
tool_memory::persist(self, &ctx);
|
||||
// So are View › Extras, Show and Snap To (#3762).
|
||||
view_cmds::persist(self, &ctx);
|
||||
self.automation_input = false;
|
||||
shape_stroke_ui::finish_frame(self, &ctx);
|
||||
native_menu::sync(self, &ctx);
|
||||
@@ -2266,6 +2278,8 @@ mod pen_variants_tests;
|
||||
#[cfg(test)]
|
||||
mod color_replacement_tests;
|
||||
#[cfg(test)]
|
||||
mod layer_shortcut_tests;
|
||||
#[cfg(test)]
|
||||
mod pencil_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -2254,6 +2254,16 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let below = Rect::from_min_max(pos2(last_rect.left(), last_rect.bottom()), pos2(last_rect.right(), ui.clip_rect().bottom()));
|
||||
layer_drop_zone(app, &ctx, ui, below, (last, last_rect), "below", &mut actions);
|
||||
}
|
||||
// Tab / ⇧Tab in a rename: rename the layer below / above next, as in Photoshop. The
|
||||
// Background isn't renamed in place (double-clicking it converts it), so it ends there.
|
||||
if let Some((from, up)) = crate::layer_row_ui::take_next_rename(ui.ctx())
|
||||
&& let Some(at) = drawn.iter().position(|(id, _)| id.0 == from)
|
||||
&& let Some(&(next, _)) = if up { at.checked_sub(1).and_then(|i| drawn.get(i)) } else { drawn.get(at + 1) }
|
||||
&& let Some(l) = doc.layer(next).filter(|l| !crate::doc_props_ui::is_background(&doc, l))
|
||||
&& let Some(done) = crate::layer_row_ui::start_rename(ui.ctx(), next.0, &l.name)
|
||||
{
|
||||
actions.push(done);
|
||||
}
|
||||
// ⌥-click the line between two layers: clip / release the upper one (#967).
|
||||
crate::clip_line_ui::show(ui, &doc, &mut actions);
|
||||
// A rename whose row is gone (deleted, filtered out, inside a closed group) ends,
|
||||
@@ -2689,7 +2699,7 @@ fn layer_row(
|
||||
let name_color = if l.visible { t.text } else { t.text_faint };
|
||||
let font = if selected && !t.pro { theme::medium(13.0) } else { egui::FontId::proportional(if t.pro { 12.0 } else { 13.0 }) };
|
||||
// Photoshop before 2026 set the Background layer's name in italics; 2026 sets it upright.
|
||||
let italic = !t.pro && l.name == "Background" && l.locks.transparency;
|
||||
let italic = !t.pro && doc.is_background(l.id);
|
||||
// Photoshop rows show only the name; the kind sub-label is a Studio-theme addition.
|
||||
let is_pixel = t.pro || matches!(l.content, LayerContent::Raster(_));
|
||||
let name_rect = crate::layer_row_ui::truncated(&painter, &l.name, font, name_color, italic, name_right - x).map(|galley| {
|
||||
@@ -2754,6 +2764,11 @@ fn layer_row(
|
||||
} else if on_thumb || !row.primary {
|
||||
actions.push(("ui.maskTarget".into(), json!(false)));
|
||||
}
|
||||
// ⌥-click the layer thumbnail: fit the layer on screen, as Photoshop does.
|
||||
let m = ui.input(|i| i.modifiers);
|
||||
if on_thumb && m.alt && !m.shift && !m.command {
|
||||
actions.push(("view.fitLayersOnScreen".into(), Value::Null));
|
||||
}
|
||||
}
|
||||
// Double-click: the name renames in place (over the row's full height, not just the glyphs:
|
||||
// #651); the Background, which can't be renamed while it's locked, becomes a normal layer; an
|
||||
|
||||
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user