Merge main into feat/layer-color-labels-1283

This commit is contained in:
Shayan Horbank committed 2026-10-08 21:33:17 +02:00
commit d7758d3412
85 files changed
+2111 -154

No files matched your search

+1
View File
@@ -9,3 +9,4 @@ target/
/temp
/book/output
/craft-fonts
*.log
+1 -1
View File
@@ -1,6 +1,6 @@
# AGENTS.md: guide for AI agents and contributors
PhotoCraft is an open-source, native, Photoshop-comparable image editor written in **Rust only** (no JavaScript or TypeScript). **No Tauri, Electron or webview shells:** the desktop app is native egui/eframe on wgpu, and the web build is the same Rust compiled to WebAssembly (trunk + wasm-bindgen). Never add Tauri (or any webview/JS UI framework) as a dependency, build step or packaging target. The product name is always written **PhotoCraft** (`{Function}Craft` in PascalCase, like its siblings ArtCraft, ArtCraftX, DesignCraft, VectorCraft, EffectCraft, FilmCraft, LightCraft, PdfCraft) in user-facing text: UI, window titles, About, installers, release names, docs prose. Machine names stay lowercase: crates (`photocraft-*`), binaries, file names, ids (`ai.storyteller.photocraft`). Standards and learnings shared across the crafting apps live in `../craftrules` (read its `README.md`). Contribute reusable learnings there, never code; repos don't share code. The goal is 1:1 Photoshop parity (same menus, shortcuts, behaviour and file fidelity) with better performance, and every feature drivable by agents. Read this file first, then `docs/`.
PhotoCraft is an open-source, native, Photoshop-comparable image editor written in **Rust only** (no JavaScript or TypeScript). **No Tauri, Electron or webview shells:** the desktop app is native egui/eframe on wgpu, and the web build is the same Rust compiled to WebAssembly (trunk + wasm-bindgen). Never add Tauri (or any webview/JS UI framework) as a dependency, build step or packaging target. The product name is always written **PhotoCraft** (`{Function}Craft` in PascalCase, like its siblings ArtCraft, ArtCraftX, DesignCraft, VectorCraft, EffectCraft, FilmCraft, LightCraft, PdfCraft) in user-facing text: UI, window titles, About, installers, release names, docs prose. Machine names stay lowercase: crates (`photocraft-*`), binaries, file names, ids (`ai.storyteller.photocraft`). Standards and learnings shared across the crafting apps live in `../craftrules` (read its `README.md`; the repository is not public — outside contributors should ask a maintainer for the standards relevant to their change). Contribute reusable learnings there, never code; repos don't share code. The goal is 1:1 Photoshop parity (same menus, shortcuts, behaviour and file fidelity) with better performance, and every feature drivable by agents. Read this file first, then `docs/`.
## 1. Orientation (5 minutes)
Generated
+28 -28
View File
@@ -3458,7 +3458,7 @@ dependencies = [
[[package]]
name = "photocraft"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"arboard",
"eframe",
@@ -3492,7 +3492,7 @@ dependencies = [
[[package]]
name = "photocraft-algo"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -3504,7 +3504,7 @@ dependencies = [
[[package]]
name = "photocraft-automation"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"base64",
"cap-std",
@@ -3526,7 +3526,7 @@ dependencies = [
[[package]]
name = "photocraft-cli"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"photocraft-automation",
"photocraft-codecs",
@@ -3539,7 +3539,7 @@ dependencies = [
[[package]]
name = "photocraft-cms"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"moxcms",
"rayon",
@@ -3547,7 +3547,7 @@ dependencies = [
[[package]]
name = "photocraft-codecs"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"exr",
"flate2",
@@ -3567,7 +3567,7 @@ dependencies = [
[[package]]
name = "photocraft-color"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"photocraft-cms",
"serde",
@@ -3575,7 +3575,7 @@ dependencies = [
[[package]]
name = "photocraft-compose"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"criterion",
"photocraft-color",
@@ -3590,7 +3590,7 @@ dependencies = [
[[package]]
name = "photocraft-doc"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -3601,7 +3601,7 @@ dependencies = [
[[package]]
name = "photocraft-engine"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"blake3",
"flate2",
@@ -3631,7 +3631,7 @@ dependencies = [
[[package]]
name = "photocraft-format"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"blake3",
"flate2",
@@ -3649,14 +3649,14 @@ dependencies = [
[[package]]
name = "photocraft-geom"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"serde",
]
[[package]]
name = "photocraft-gpu"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"half",
"log",
@@ -3673,14 +3673,14 @@ dependencies = [
[[package]]
name = "photocraft-heif"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"heic-rs",
]
[[package]]
name = "photocraft-io"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"blake3",
"photocraft-algo",
@@ -3704,14 +3704,14 @@ dependencies = [
[[package]]
name = "photocraft-ops"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"photocraft-doc",
]
[[package]]
name = "photocraft-paint"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -3722,7 +3722,7 @@ dependencies = [
[[package]]
name = "photocraft-plugins"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -3737,7 +3737,7 @@ dependencies = [
[[package]]
name = "photocraft-psd"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"flate2",
"photocraft-psd",
@@ -3748,7 +3748,7 @@ dependencies = [
[[package]]
name = "photocraft-raster"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -3758,7 +3758,7 @@ dependencies = [
[[package]]
name = "photocraft-raw"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"photocraft-raw",
"png 0.18.1",
@@ -3767,7 +3767,7 @@ dependencies = [
[[package]]
name = "photocraft-tablet"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"block2 0.6.2",
"objc2 0.6.4",
@@ -3779,7 +3779,7 @@ dependencies = [
[[package]]
name = "photocraft-testkit"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"memory-stats",
"photocraft-color",
@@ -3790,7 +3790,7 @@ dependencies = [
[[package]]
name = "photocraft-text"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"flate2",
"parley",
@@ -3804,7 +3804,7 @@ dependencies = [
[[package]]
name = "photocraft-ui-egui"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"base64",
"eframe",
@@ -3838,7 +3838,7 @@ dependencies = [
[[package]]
name = "photocraft-vector"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"photocraft-color",
"photocraft-doc",
@@ -3849,7 +3849,7 @@ dependencies = [
[[package]]
name = "photocraft-web"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"eframe",
"egui",
@@ -6415,7 +6415,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xtask"
version = "0.4.1"
version = "0.5.0"
dependencies = [
"serde",
"serde_json",
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"]
[workspace.package]
version = "0.4.1"
version = "0.5.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
+102 -8
View File
@@ -348,19 +348,83 @@ fn average_samples(src: &Image, out: Rect, ctx: &Ctx, mut offsets: impl FnMut(f3
res
}
pub(crate) fn motion(src: &Image, out: Rect, ctx: &Ctx, angle: f32, distance: f32) -> Vec<f32> {
/// Sample offsets of a motion blur of `distance` at `angle`, relative to the pixel centre.
fn motion_offsets(angle: f32, distance: f32) -> Vec<(f32, f32)> {
let d = distance.abs();
if d < 0.5 {
return src.crop(out);
}
let (s, c) = angle.to_radians().sin_cos();
let steps = d.ceil() as i32;
average_samples(src, out, ctx, |x, y, pts| {
for i in 0..=steps {
(0..=steps)
.map(|i| {
let t = i as f32 / steps as f32 - 0.5;
pts.push((x + c * d * t, y - s * d * t));
(c * d * t, -s * d * t)
})
.collect()
}
/// Motion blur: the mean of bilinear samples along a line centred on the pixel. The offsets are the
/// same for every pixel, so their bilinear taps are merged once into a fixed kernel, which is
/// applied tap by tap to whole rows of a premultiplied window (the same premultiplied mean the
/// per-sample loop takes, summed in another order).
pub(crate) fn motion(src: &Image, out: Rect, ctx: &Ctx, angle: f32, distance: f32) -> Vec<f32> {
if distance.abs() < 0.5 {
return src.crop(out);
}
let offs = motion_offsets(angle, distance);
let k = 1.0 / offs.len() as f32;
// Merged taps (dx, dy, weight), in the order first seen.
let mut taps: Vec<(i32, i32, f32)> = Vec::new();
let mut slot = std::collections::HashMap::new();
for &(ox, oy) in &offs {
let (x0, y0) = (ox.floor(), oy.floor());
let (ax, ay) = (ox - x0, oy - y0);
let (x0, y0) = (x0 as i32, y0 as i32);
for (dx, dy, w) in [(0, 0, (1.0 - ax) * (1.0 - ay)), (1, 0, ax * (1.0 - ay)), (0, 1, (1.0 - ax) * ay), (1, 1, ax * ay)] {
if w <= 0.0 {
continue;
}
let i = *slot.entry((x0 + dx, y0 + dy)).or_insert_with(|| {
taps.push((x0 + dx, y0 + dy, 0.0));
taps.len() - 1
});
taps[i].2 += w * k;
}
})
}
let reach = taps.iter().map(|t| t.0.abs().max(t.1.abs())).max().unwrap_or(0);
let n = src.ch;
let win = out.inflate(reach);
let ww = win.width() as usize;
// Premultiplied window; outside the source reads as transparent, as the sampler does.
let mut pw = vec![0.0f32; ww * win.height() as usize * n];
for y in win.y0..win.y1 {
for x in win.x0..win.x1 {
let i = ((y - win.y0) as usize * ww + (x - win.x0) as usize) * n;
let a = if ctx.alpha { src.get(x, y, n - 1) } else { 1.0 };
for c in 0..n {
let v = src.get(x, y, c);
pw[i + c] = if ctx.alpha && c < n - 1 { v * a } else { v };
}
}
}
let (ow, oh) = (out.width() as usize, out.height() as usize);
let mut res = vec![0.0f32; ow * oh * n];
let r = reach as usize;
for (oy, row) in res.chunks_exact_mut(ow * n).enumerate() {
for &(dx, dy, w) in &taps {
let start = ((oy + r).wrapping_add_signed(dy as isize) * ww + r.wrapping_add_signed(dx as isize)) * n;
for (o, v) in row.iter_mut().zip(&pw[start..start + ow * n]) {
*o += w * v;
}
}
if ctx.alpha {
for px in row.chunks_exact_mut(n) {
let a = px[n - 1];
for v in px.iter_mut().take(n - 1) {
*v = if a > 1e-7 { *v / a } else { 0.0 };
}
}
}
}
res
}
pub(crate) fn radial(src: &Image, out: Rect, ctx: &Ctx, amount: f32, method: RadialMethod, center: (f32, f32)) -> Vec<f32> {
@@ -702,4 +766,34 @@ mod tests {
img.data[i] = 0.5 / 255.0;
assert!(surface_8bit(&img, out, &ctx, 4, 0.1, 26).is_none());
}
#[test]
fn motion_kernel_matches_the_per_pixel_samples() {
// Noisy RGBA with some transparent pixels; the output reaches the source edge.
let src_rect = Rect::new(-30, -30, 50, 40);
let mut img = Image::new(src_rect, 4);
let mut s = 0x1b87_3593u32;
for px in img.data.as_chunks_mut::<4>().0 {
for v in px.iter_mut() {
s ^= s << 13;
s ^= s >> 17;
s ^= s << 5;
*v = (s % 1000) as f32 / 999.0;
}
if s.is_multiple_of(5) {
px[3] = 0.0;
}
}
let out = Rect::new(-12, -6, 30, 22);
for alpha in [true, false] {
let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha };
for (angle, distance) in [(0.0, 1.0), (0.0, 9.0), (30.0, 7.0), (90.0, 12.0), (-45.0, 20.0), (137.0, 33.5), (200.0, 40.0)] {
let fast = motion(&img, out, &ctx, angle, distance);
let offs = motion_offsets(angle, distance);
let slow = average_samples(&img, out, &ctx, |x, y, pts| pts.extend(offs.iter().map(|&(dx, dy)| (x + dx, y + dy))));
let err = slow.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(err < 1e-5, "alpha {alpha} angle {angle} distance {distance}: max error {err}");
}
}
}
}
+1 -1
View File
@@ -51,7 +51,7 @@ pub fn quick_select(sampler: &dyn Sampler, canvas: Rect, points: &[(f32, f32)],
x1 = x1.max(x + r);
y1 = y1.max(y + r);
}
let bbox = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32 + 1, y1.ceil() as i32 + 1).intersect(&canvas);
let bbox = Rect::new(x0.floor() as i32, y0.floor() as i32, (x1.ceil() as i32).saturating_add(1), (y1.ceil() as i32).saturating_add(1)).intersect(&canvas);
if bbox.is_empty() {
return None;
}
+11
View File
@@ -304,6 +304,17 @@ fn two_regions(w: usize, h: usize) -> RgbImage {
})
}
#[test]
fn quick_select_with_points_far_off_canvas_selects_nothing() {
// A cast saturates to i32::MAX; adding one to it once overflowed.
let img = two_regions(140, 100);
let s = ImageSampler { img: &img, origin: (0, 0) };
let canvas = Rect::new(0, 0, 140, 100);
for p in [(3e9, 0.0), (0.0, 3e9), (f32::MAX, f32::MAX)] {
assert!(quick::quick_select(&s, canvas, &[p], 8.0, quick::WORK_PX).is_none(), "{p:?}");
}
}
#[test]
fn quick_select_grows_without_leaking() {
let img = two_regions(140, 100);
+1 -1
View File
@@ -289,7 +289,7 @@ pub fn clone_stroke(scene: &Scene, surf: &mut Surface, source: [f64; 2], points:
let (x, y) = hd.apply(u, v);
bb = [bb[0].min(x), bb[1].min(y), bb[2].max(x), bb[3].max(y)];
}
let area = Rect::new(bb[0].floor() as i32, bb[1].floor() as i32, bb[2].ceil() as i32 + 1, bb[3].ceil() as i32 + 1);
let area = Rect::new(bb[0].floor() as i32, bb[1].floor() as i32, (bb[2].ceil() as i32).saturating_add(1), (bb[3].ceil() as i32).saturating_add(1));
if area.is_empty() || area.width() > 4096 || area.height() > 4096 {
continue;
}
+14 -2
View File
@@ -6,7 +6,7 @@
use photocraft_color::SampleType;
use photocraft_color::convert::{D50, SRGB_TO_XYZ_D50, XYZ_D50_TO_SRGB, mat3_mul, rgb_to_gray, srgb_to_linear};
use photocraft_doc::Adjustment;
use photocraft_doc::adjust::{CurvePoint, HueRange, LevelsChannel, ToneSpace};
use photocraft_doc::adjust::{CurvePoint, HueRange, LevelsChannel, ToneSpace, lut3d_len};
use crate::Buffer;
@@ -203,7 +203,7 @@ pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth
}
}),
Adjustment::SelectiveColor { relative, adjustments } => map_rgb(buf, |c| selective_color(c, *relative, adjustments)),
Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if *size >= 2 && table.len() >= (*size as usize).pow(3) * 3 => {
Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if lut3d_len(*size).is_some_and(|len| table.len() >= len) => {
let (n, w, x0, y0) = (*size as usize, buf.rect.width().max(1) as usize, buf.rect.x0, buf.rect.y0);
for (i, p) in buf.px.iter_mut().enumerate() {
if p[3] <= 0.0 {
@@ -740,6 +740,18 @@ mod tone_tests {
Buffer { rect, px }
}
#[test]
fn color_lookup_with_an_overflowing_stored_size_is_the_identity() {
// A stored document's size is untrusted: (2²²)³ × 3 overflows, which once wrapped past
// the table-length guard and indexed out of bounds.
for size in [1 << 22, u32::MAX] {
let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false };
let mut b = ramp();
apply(&a, &mut b);
assert_eq!(b.px, ramp().px, "size {size}");
}
}
#[test]
fn identity_tone_in_every_space_is_identity() {
for space in [ToneSpace::Rgb, ToneSpace::Cmyk, ToneSpace::Lab] {
+19
View File
@@ -17,6 +17,15 @@ pub fn is_identity_curve(points: &[CurvePoint]) -> bool {
}
}
/// Number of values in the table of a `size`³ Color Lookup (`size³ × 3`). `None` for a size
/// below 2 or one whose table length overflows: a stored document's size is untrusted.
pub fn lut3d_len(size: u32) -> Option<usize> {
if size < 2 {
return None;
}
usize::try_from(size).ok()?.checked_pow(3)?.checked_mul(3)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LevelsChannel {
pub in_black: f32,
@@ -293,4 +302,14 @@ mod tests {
let g: Adjustment = serde_json::from_str(r#"{"GradientMap":{"stops":[],"reverse":true}}"#).unwrap();
assert!(matches!(g, Adjustment::GradientMap { dither: false, .. }));
}
#[test]
fn lut3d_len_rejects_tiny_and_overflowing_sizes() {
assert_eq!(lut3d_len(0), None);
assert_eq!(lut3d_len(1), None);
assert_eq!(lut3d_len(2), Some(24));
assert_eq!(lut3d_len(33), Some(33 * 33 * 33 * 3));
assert_eq!(lut3d_len(1 << 22), None, "(2²²)³ overflows a 64-bit length");
assert_eq!(lut3d_len(u32::MAX), None);
}
}
+17
View File
@@ -985,6 +985,23 @@ impl Document {
(1..=names.len() + 1).map(|n| format!("{base} {n}")).find(|n| !names.contains(n.as_str())).unwrap_or_else(|| base.to_string())
}
/// Name for a copy of a layer named `name`, unique in the document: "Layer 1 copy", then
/// "Layer 1 copy 2", "Layer 1 copy 3"… A name that already ends in "copy" (or "copy N") is
/// numbered from its root rather than growing another "copy".
pub fn copy_name(&self, name: &str) -> String {
let root = match name.rsplit_once(" copy") {
Some((root, rest)) if rest.is_empty() || rest.strip_prefix(' ').is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) => root,
_ => name,
};
let names: std::collections::HashSet<&str> = self.walk().into_iter().map(|(_, _, l)| l.name.as_str()).collect();
let first = format!("{root} copy");
if !names.contains(first.as_str()) {
return first;
}
// At most `names.len() + 1` candidates are needed, so the search always succeeds.
(2..=names.len() + 2).map(|n| format!("{root} copy {n}")).find(|n| !names.contains(n.as_str())).unwrap_or(first)
}
/// Top-most layer id, useful as the default active layer.
pub fn top_layer(&self) -> Option<LayerId> {
self.layers.last().map(|l| l.id)
+36 -2
View File
@@ -68,24 +68,37 @@ pub struct Timeline {
impl Timeline {
pub fn new(duration: usize, fps: f32) -> Self {
let d = duration.max(1);
Timeline { fps: if fps > 0.0 { fps } else { 30.0 }, duration: d, current: 0, work_start: 0, work_end: d }
Timeline { fps: valid_fps(fps), duration: d, current: 0, work_start: 0, work_end: d }
}
/// Keep every index inside `0..duration` and the work area non-empty.
pub fn clamp(&mut self) {
self.duration = self.duration.max(1);
self.fps = if self.fps > 0.0 { self.fps } else { 30.0 };
self.fps = valid_fps(self.fps);
self.current = self.current.min(self.duration - 1);
self.work_start = self.work_start.min(self.duration - 1);
self.work_end = self.work_end.clamp(self.work_start + 1, self.duration);
}
/// Move the playhead `delta` frames, stopping at the first and last frame. Saturating, so it's
/// safe on any stored timeline, even one loaded with `duration` 0 or `usize::MAX` (#1009).
pub fn step(&mut self, delta: i64) {
let n = usize::try_from(delta.unsigned_abs()).unwrap_or(usize::MAX);
let moved = if delta < 0 { self.current.saturating_sub(n) } else { self.current.saturating_add(n) };
self.current = moved.min(self.duration.saturating_sub(1));
}
/// Playhead time in seconds.
pub fn time(&self) -> f32 {
self.current as f32 / self.fps.max(1e-3)
}
}
/// A usable frame rate: positive and finite, else the 30 fps default.
fn valid_fps(fps: f32) -> f32 {
if fps.is_finite() && fps > 0.0 { fps } else { 30.0 }
}
#[cfg(test)]
mod tests {
use super::*;
@@ -104,6 +117,27 @@ mod tests {
assert!((t.time() - 23.0 / 24.0).abs() < 1e-6);
}
/// #1009: stepping never panics or leaves the timeline, whatever was stored.
#[test]
fn step_saturates_at_both_ends() {
let mut t = Timeline::new(3, 24.0);
t.step(-1);
assert_eq!(t.current, 0);
t.step(1);
t.step(i64::MAX);
assert_eq!(t.current, 2);
t.step(i64::MIN);
assert_eq!(t.current, 0);
for duration in [0, usize::MAX] {
let mut t = Timeline { fps: f32::INFINITY, duration, current: usize::MAX, work_start: 0, work_end: 0 };
t.step(1);
assert_eq!(t.current, duration.saturating_sub(1));
t.clamp();
assert_eq!(t.fps, 30.0);
assert!(t.current < t.duration);
}
}
#[test]
fn round_trips() {
let t = Timeline::new(48, 25.0);
+13 -2
View File
@@ -1021,6 +1021,9 @@ fn nice_length(d: &Document) -> f64 {
[5.0, 2.0, 1.0].into_iter().map(|m| m * e).find(|v| *v <= target).unwrap_or(e)
}
/// The shortest image a scale bar fits: four times its 2 px minimum height (#932).
const MIN_SCALE_MARKER_HEIGHT: f64 = 8.0;
fn place_scale_marker(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "image.analysis.placeScaleMarker";
let d = doc(s)?;
@@ -1034,6 +1037,11 @@ fn place_scale_marker(s: &mut Session, p: &Value) -> Result<Value> {
if px < 1.0 || px > w {
return Err(bad(CMD, format!("a {length} {} bar is {px:.1} px; it must fit the {w} px wide image", sc.units)));
}
// The bar is at least 2 px tall and at most a quarter of the image, so a shorter image has no
// room for it (and would invert the height clamp below, which panics) (#932).
if h < MIN_SCALE_MARKER_HEIGHT {
return Err(bad(CMD, format!("the image is {h} px tall; a scale marker needs at least {MIN_SCALE_MARKER_HEIGHT} px")));
}
let font_size = p.get("fontSize").and_then(Value::as_f64).unwrap_or(12.0).clamp(1.0, 1000.0);
let font = p.get("font").and_then(Value::as_str).map(str::to_string);
let show_text = p.get("displayText").and_then(Value::as_bool).unwrap_or(true);
@@ -1051,8 +1059,11 @@ fn place_scale_marker(s: &mut Session, p: &Value) -> Result<Value> {
let margin = (w.min(h) * 0.03).round().max(2.0);
let bar_h = (font_size / 4.0).round().clamp(2.0, h / 4.0);
let text_h = if show_text { font_size * 1.25 } else { 0.0 };
let bar_y = if text_top { h - margin - bar_h } else { h - margin - bar_h - text_h };
let bar = Rect::new(margin as i32, bar_y.round() as i32, (margin + px).round() as i32, (bar_y + bar_h).round() as i32);
// Keep the bar on the canvas when the text under it doesn't fit; the label is clipped instead (#932).
let bar_y = if text_top { h - margin - bar_h } else { h - margin - bar_h - text_h }.max(0.0);
// Likewise pull a bar nearly as wide as the image in from the right edge (#932).
let bar_x = margin.min(w - px);
let bar = Rect::new(bar_x.round() as i32, bar_y.round() as i32, (bar_x + px).round() as i32, (bar_y + bar_h).round() as i32);
let label = format!("{} {}", trim_num(length), sc.units);
compound(s, "Place Scale Marker", |s| {
let fmt = doc(s)?.pixel_format();
+38
View File
@@ -276,6 +276,44 @@ fn place_scale_marker_builds_one_group_in_one_step() {
assert!(d(&s).layers.iter().all(|l| l.name != "Measurement Scale Marker"));
}
#[test]
fn place_scale_marker_on_a_short_document_errors_without_panicking() {
// A document under 8 px tall inverted the bar-height clamp and panicked (#932). Call `run`
// directly too: dispatch would catch the panic and hide it behind a generic error.
for (w, h, p) in [
(100, 4, json!({})),
(100, 1, json!({})),
(100, 7, json!({"displayText": false, "textPosition": "top"})),
(300_000, 3, json!({"fontSize": 1000})),
(2, 7, json!({"length": 1})),
(7, 7, json!({"length": 7, "fontSize": 1})),
] {
for h in [h, 1, 2, 3, 5, 6] {
let mut s = session(w, h, 8);
let before = s.active().unwrap().history.past_len();
let e = place_scale_marker(&mut s, &p).unwrap_err().to_string();
assert!(e.contains("tall"), "{w}x{h}: {e}");
let e = s.execute("image.analysis.placeScaleMarker", p.clone()).unwrap_err().to_string();
assert!(!e.contains("internal error"), "{w}x{h}: {e}");
assert_eq!(s.active().unwrap().history.past_len(), before, "{w}x{h}: nothing added");
assert!(d(&s).layers.iter().all(|l| l.name != "Measurement Scale Marker"));
}
}
// Control: 8 px is the shortest that fits, and tall, narrow or roomy documents still get a
// marker that lies on the canvas.
for (w, h, p) in [(100, 8, json!({})), (100, 100, json!({})), (20, 4000, json!({})), (2, 8, json!({"length": 2}))] {
let mut s = session(w, h, 8);
let r = place_scale_marker(&mut s, &p).unwrap();
let b: Vec<i64> = r["barRect"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect();
assert!(0 <= b[0] && b[0] < b[2] && b[2] <= i64::from(w), "{w}x{h}: bar on the canvas: {r}");
assert!(0 <= b[1] && b[1] < b[3] && b[3] <= i64::from(h), "{w}x{h}: bar on the canvas: {r}");
assert_eq!(s.active().unwrap().history.past_len(), 1);
let doc = d(&s);
let bar = doc.layers.last().unwrap().children().unwrap().iter().find(|l| l.name == "Scale Bar").unwrap();
assert_eq!(f64::from(bar.surface().unwrap().content_bounds().width()), r["pixels"].as_f64().unwrap(), "{w}x{h}");
}
}
#[test]
fn analysis_info_and_cmyk_document() {
let mut s = Session::new();
+1 -1
View File
@@ -457,7 +457,7 @@ fn build() -> Vec<CommandSpec> {
// 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 mut dup = src.duplicate();
dup.name = format!("{} copy", dup.name);
dup.name = doc.copy_name(&dup.name);
if from_background {
dup.locks = Default::default();
}
+1 -1
View File
@@ -203,7 +203,7 @@ fn layer_via(s: &mut Session, cut: bool) -> Result<Value> {
let nid = s.edit("Layer Via Copy", |doc, active| {
let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
let mut dup = src.duplicate();
dup.name = format!("{} copy", src.name);
dup.name = doc.copy_name(&src.name);
dup.locks = Default::default();
let nid = doc.insert_above(Some(id), dup);
*active = Some(nid);
+12 -3
View File
@@ -322,8 +322,17 @@ fn rect_param(p: &Value, key: &str, cmd: &str) -> Result<Rect> {
}
fn content_aware_fill(s: &mut Session, p: &Value) -> Result<Value> {
content_aware_fill_as(s, p, "edit.contentAwareFill", "Content-Aware Fill")
}
/// Delete and Fill Selection (#1286): Photoshop's one-click removal from the selection-tool
/// context menu. Content-Aware Fill with its default settings into the layer, no dialog.
fn delete_and_fill(s: &mut Session, _: &Value) -> Result<Value> {
content_aware_fill_as(s, &json!({}), "edit.deleteAndFillSelection", "Delete and Fill Selection")
}
fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &'static str) -> Result<Value> {
use photocraft_algo::content_aware::{FillOptions, color_level, fill_with, rotation_level};
let cmd = "edit.contentAwareFill";
let id = pixel_layer(s).map_err(EngineError::Other)?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let doc = st.doc.clone();
@@ -365,7 +374,6 @@ fn content_aware_fill(s: &mut Session, p: &Value) -> Result<Value> {
let fmt = surf.format();
let n = fmt.channels();
let (w, h) = (window.width() as usize, window.height() as usize);
let label = "Content-Aware Fill";
// A background job when started with `Session::start` (#210): reading the window and the
// PatchMatch fill run on a worker against the document snapshot, cancellable per row band.
crate::jobs::run(
@@ -449,7 +457,7 @@ fn apply_content_aware_fill(
}
"duplicate" => {
let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate();
dup.name = format!("{} copy", dup.name);
dup.name = doc.copy_name(&dup.name);
let nid = doc.insert_above(Some(id), dup);
*active = Some(nid);
nid
@@ -957,6 +965,7 @@ pub fn specs() -> Vec<CommandSpec> {
can_caf,
content_aware_fill
),
spec!("edit.deleteAndFillSelection", "Delete and Fill Selection", [], None, "{}", can_caf, delete_and_fill),
spec!(
"edit.contentAwareScale",
"Content-Aware Scale",
+24
View File
@@ -135,6 +135,30 @@ fn content_aware_fill_removes_object_at_all_depths() {
}
}
#[test]
fn delete_and_fill_selection_removes_the_object_in_one_step() {
// #1286: Content-Aware Fill's defaults, no dialog, one history step named for the command.
for depth in [8, 16, 32] {
let mut s = blob_session(depth);
let base = s.active().unwrap().active_layer.unwrap();
assert!(s.is_enabled("edit.deleteAndFillSelection"));
let r = s.execute("edit.deleteAndFillSelection", json!({})).unwrap();
assert_eq!(r["layer"].as_u64(), Some(base.0), "fills the layer itself");
assert!(r["filled"].as_u64().unwrap() > 100);
let v = px(&s, 30, 20);
assert!(!(v[0] > 0.9 && v[1] < 0.1), "depth {depth}: red left: {v:?}");
assert_eq!(s.active().unwrap().history.undo_label(), Some("Delete and Fill Selection"));
s.undo();
assert_eq!(px(&s, 30, 20)[1], 0.0, "undo restores the blob");
}
// Parameters are ignored, never a crash; nothing selected greys it out and refuses.
let mut s = blob_session(8);
assert!(s.execute("edit.deleteAndFillSelection", json!({"output": 7, "sampling": [1]})).is_ok());
s.execute("select.deselect", json!({})).unwrap();
assert!(!s.is_enabled("edit.deleteAndFillSelection"));
assert!(s.execute("edit.deleteAndFillSelection", json!({})).is_err());
}
#[test]
fn content_aware_fill_outputs_and_sampling() {
let mut s = blob_session(8);
+26 -2
View File
@@ -351,9 +351,15 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// The most recent filter command in the session journal.
/// The most recent filter command in the session journal, retargeted at the active layer: dialogs
/// such as the Filter Gallery record the layer they ran on, and Last Filter applies to the
/// current layer, as in Photoshop (#1270).
fn last_filter(s: &Session) -> Option<(String, Value)> {
s.journal.iter().rev().find(|(id, _)| params_for(id, &Value::Null).is_some() && id.starts_with("filter.")).cloned()
let (id, mut params) = s.journal.iter().rev().find(|(id, _)| params_for(id, &Value::Null).is_some() && id.starts_with("filter.")).cloned()?;
if let Value::Object(m) = &mut params {
m.remove("layer");
}
Some((id, params))
}
#[cfg(test)]
@@ -528,6 +534,24 @@ mod tests {
assert_eq!(active_pixels(&s2), twice);
}
#[test]
fn last_filter_applies_to_the_active_layer() {
let mut s = session();
paint_pattern(&mut s);
let first = s.active().unwrap().active_layer.unwrap();
// Dialogs (Filter Gallery, Camera Raw…) record the layer they ran on.
s.execute("filter.other.offset", json!({"horizontal": 3, "layer": first.0})).unwrap();
let first_once = active_pixels(&s);
s.execute("layer.new.layer", json!({})).unwrap();
paint_pattern(&mut s);
let before = active_pixels(&s);
s.execute("filter.lastFilter", json!({})).unwrap();
assert_ne!(active_pixels(&s), before, "the active layer is filtered");
let d = s.active().unwrap();
let l = d.doc.layer(first).unwrap();
assert_eq!(l.surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 48, 32)), first_once, "the first layer is left alone");
}
#[test]
fn params_map_to_algorithm_units() {
assert_eq!(params_for("filter.blur.gaussianBlur", &json!({"radius": 4.5})), Some(FilterParams::GaussianBlur { radius: 4.5 }));
+18 -1
View File
@@ -222,8 +222,25 @@ pub fn apply_set(layer: &Layer, f: &Fill, canvas: Rect, p: &Value, fg: [f32; 4],
}
if from.is_some() || to.is_some() || (style_changed && !explicit_geometry) {
let cur = if from.is_some() || to.is_some() { gf::handles(*style, *angle, *scale, *offset, frame) } else { old_handles };
let (a, s, o) = gf::from_handles(*style, from.unwrap_or(cur.0), to.unwrap_or(cur.1), frame, *angle);
let (f0, t0) = (from.unwrap_or(cur.0), to.unwrap_or(cur.1));
let (a, s, o) = gf::from_handles(*style, f0, t0, frame, *angle);
(*angle, *scale, *offset) = (a, clamp_scale(s), o);
// Past the scale range the dragged handle stops; the other one stays where it is (#1243).
// (Linear centres on the midpoint, so a clamped scale would otherwise move both ends.)
let anchor = match (from, to) {
(Some(_), None) => Some((t0, false)),
(None, Some(_)) => Some((f0, true)),
_ => None,
};
if let Some((pin, is_start)) = anchor
&& *scale != s
{
let (f1, t1) = gf::handles(*style, *angle, *scale, *offset, frame);
let at = if is_start { f1 } else { t1 };
let (dx, dy) = (pin[0] - at[0], pin[1] - at[1]);
let (w, h) = (frame.width().max(1) as f32, frame.height().max(1) as f32);
*offset = (offset.0 + dx / w, offset.1 + dy / h);
}
}
if let Some(v) = p.get("stops") {
let arr = v.as_array().ok_or_else(|| bad(CMD, "`stops` is [[location, colour], …]"))?;
@@ -297,3 +297,29 @@ fn commands_fail_gracefully() {
let g = s.execute(SET, json!({"scale": 1})).unwrap();
assert!((g["scale"].as_f64().unwrap() - 10.0).abs() < 1e-3, "{g}");
}
/// Dragging one handle past the scale range stops it; the other handle stays put (#1243).
#[test]
fn a_clamped_handle_drag_leaves_the_other_handle_alone() {
let pt = |g: &Value, k: &str| [g[k][0].as_f64().unwrap(), g[k][1].as_f64().unwrap()];
let close = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1e-2 && (a[1] - b[1]).abs() < 1e-2;
for style in STYLES {
for (from, to, short, short_start) in [([14.0, 16.0], [34.0, 16.0], [15.0, 16.0], [33.0, 16.0]), ([24.0, 6.0], [24.0, 26.0], [24.0, 7.0], [24.0, 25.0])]
{
let mut s = session(8, "white");
s.execute(CREATE, json!({"from": from, "to": to, "style": style})).unwrap();
// End dragged almost onto the start: far below 10 %.
let g = s.execute(SET, json!({"to": short})).unwrap();
assert!((g["scale"].as_f64().unwrap() - 10.0).abs() < 1e-3, "{style}: {g}");
assert!(close(pt(&g, "from"), from), "{style}: start moved to {:?}", pt(&g, "from"));
// The end stops on the line towards the pointer.
let e = pt(&g, "to");
assert!((e[0] - from[0]) * (short[0] - from[0]) >= 0.0 && (e[1] - from[1]) * (short[1] - from[1]) >= 0.0, "{style}: {e:?}");
// And the same for the start handle.
let mut s = session(8, "white");
s.execute(CREATE, json!({"from": from, "to": to, "style": style})).unwrap();
let g = s.execute(SET, json!({"from": short_start})).unwrap();
assert!(close(pt(&g, "to"), to), "{style}: end moved: {g}");
}
}
}
+82 -11
View File
@@ -155,10 +155,29 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "width": nw, "height": nh }))
}
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
/// Moves every surface, channel, selection and guide by `(dx, dy)`.
fn translate_doc(doc: &mut Document, dx: i32, dy: i32) {
///
/// Fails, before moving anything, when some pixels would land outside the i32 coordinate
/// range: the surface copy saturates its target rectangle there, which no longer matches
/// the pixel data and panics (#959).
fn translate_doc(doc: &mut Document, cmd: &str, dx: i32, dy: i32) -> Result<()> {
if dx == 0 && dy == 0 {
return;
return Ok(());
}
let fits = |r: Rect| {
r.is_empty() || (r.x0.checked_add(dx).is_some() && r.x1.checked_add(dx).is_some() && r.y0.checked_add(dy).is_some() && r.y1.checked_add(dy).is_some())
};
let mut ok = true;
for_each_surface(&mut doc.layers, true, &mut |surf, _| ok = ok && fits(surf.content_bounds()));
ok = ok
&& doc.channels.iter().chain(doc.quick_mask.as_ref()).all(|ch| fits(ch.surface.content_bounds()))
&& doc.selection.as_ref().is_none_or(|sel| fits(sel.content_bounds()));
if !ok {
return Err(bad(cmd, format!("moving the document by ({dx}, {dy}) would push its pixels outside the 32-bit coordinate range")));
}
for_each_surface(&mut doc.layers, true, &mut |surf, _| *surf = translate_surface(surf, dx, dy));
for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
@@ -170,16 +189,22 @@ fn translate_doc(doc: &mut Document, dx: i32, dy: i32) {
// Type, shapes, smart objects, vector masks, paths, guides, slices, notes… (caches above
// are already translated exactly, so nothing needs re-rendering for the move itself).
crate::canvas_geom::transform_geometry(doc, &photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy)));
Ok(())
}
/// Crops the document to `r` (in current document coordinates).
fn crop_doc(doc: &mut Document, r: Rect, delete_pixels: bool) {
fn crop_doc(doc: &mut Document, cmd: &str, r: Rect, delete_pixels: bool) -> Result<()> {
// The origin moves to (0, 0); `-i32::MIN` has no i32 value (#959).
let (Some(dx), Some(dy)) = (r.x0.checked_neg(), r.y0.checked_neg()) else {
return Err(bad(cmd, format!("the crop origin ({}, {}) can't be moved to (0, 0) within the 32-bit coordinate range", r.x0, r.y0)));
};
if delete_pixels {
for_each_surface(&mut doc.layers, false, &mut |surf, _| *surf = crop_surface(surf, r));
}
translate_doc(doc, -r.x0, -r.y0);
translate_doc(doc, cmd, dx, dy)?;
doc.size = Size::new(r.width(), r.height());
crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes);
Ok(())
}
fn anchor_factors(a: &str) -> (f64, f64) {
@@ -229,7 +254,7 @@ fn canvas_size(s: &mut Session, p: &Value) -> Result<Value> {
let dy = ((nh as f64 - oh) * ay).round() as i32;
let ext = extension_color(s, p);
s.edit("Canvas Size", |doc, _| {
translate_doc(doc, dx, dy);
translate_doc(doc, "image.canvasSize", dx, dy)?;
doc.size = Size::new(nw, nh);
crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes);
let canvas = doc.bounds();
@@ -266,7 +291,14 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
crate::commands::int_i32("image.crop", p, "width")?,
crate::commands::int_i32("image.crop", p, "height")?,
) {
(Some(x), Some(y), Some(w), Some(h)) if w > 0 && h > 0 => Some(Rect::new(x, y, x.saturating_add(w), y.saturating_add(h))),
(Some(x), Some(y), Some(w), Some(h)) if w > 0 && h > 0 => {
// A far edge past i32::MAX used to saturate, silently cropping less than asked (#959).
let end = |o: i32, len: i32, ko: &str, kl: &str| {
o.checked_add(len)
.ok_or_else(|| bad("image.crop", format!("`{ko}` + `{kl}` = {} is outside the 32-bit coordinate range", i64::from(o) + i64::from(len))))
};
Some(Rect::new(x, y, end(x, w, "x", "width")?, end(y, h, "y", "height")?))
}
_ => None,
};
// An explicit rectangle (the Crop tool) may extend past the canvas; a selection crop is clamped.
@@ -277,7 +309,7 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Other("nothing to crop: pass x/y/width/height or make a selection".into()));
}
s.edit("Crop", |doc, _| {
crop_doc(doc, r, delete);
crop_doc(doc, "image.crop", r, delete)?;
doc.selection = None;
Ok(())
})?;
@@ -317,10 +349,7 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
if side("right") { b.x1 } else { canvas.x1 },
if side("bottom") { b.y1 } else { canvas.y1 },
);
s.edit("Trim", |doc, _| {
crop_doc(doc, r, true);
Ok(())
})?;
s.edit("Trim", |doc, _| crop_doc(doc, "image.trim", r, true))?;
Ok(json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }))
}
@@ -457,6 +486,48 @@ mod tests {
s.execute("image.crop", json!({"x": -10, "y": -10, "width": 1000, "height": 1000})).unwrap();
}
/// A crop whose translation to the origin can't be represented in i32 is rejected before
/// anything changes (#959): `-i32::MIN` overflowed the negation in `crop_doc`, `x + width`
/// past i32::MAX silently shortened the crop, and an origin one past i32::MIN moved the
/// layer pixels beyond i32::MAX (a length-mismatch panic while translating surfaces).
#[test]
fn crop_rejects_origins_that_cannot_move_to_zero() {
const MIN: i64 = i32::MIN as i64;
const MAX: i64 = i32::MAX as i64;
let cases = [
json!({"x": MIN, "y": 0, "width": 1, "height": 1}),
json!({"x": 0, "y": MIN, "width": 1, "height": 1}),
json!({"x": MIN, "y": MIN, "width": 1, "height": 1}),
json!({"x": MIN, "y": 0, "width": 1, "height": 1, "deleteCroppedPixels": false}),
json!({"x": MAX - 5, "y": 0, "width": 10, "height": 1}),
json!({"x": 0, "y": MAX - 5, "width": 1, "height": 10}),
json!({"x": MIN + 1, "y": 0, "width": 1, "height": 1, "deleteCroppedPixels": false}),
json!({"x": 0, "y": MIN + 1, "width": 1, "height": 1, "deleteCroppedPixels": false}),
];
for p in cases {
let mut s = session();
let before = s.active().unwrap().doc.clone();
let (rev, steps) = (s.active().unwrap().revision, s.active().unwrap().history.entries().len());
let err = s.execute("image.crop", p.clone()).unwrap_err();
assert!(matches!(err, EngineError::BadParams { .. }), "{p}: {err}");
assert!(err.to_string().contains("32-bit"), "{p}: {err}");
let st = s.active().unwrap();
assert!(std::sync::Arc::ptr_eq(&st.doc, &before), "{p}: document changed");
assert_eq!(st.doc.size, Size::new(40, 20), "{p}");
assert_eq!(st.doc.layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 20, 15), "{p}");
assert_eq!((st.revision, st.history.entries().len()), (rev, steps), "{p}: history step recorded");
}
// Control: a legal negative origin past the canvas still crops (and extends) the canvas.
let mut s = session();
s.execute("image.crop", json!({"x": -10, "y": -5, "width": 60, "height": 30})).unwrap();
assert_eq!(doc(&s).size, Size::new(60, 30));
assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 10), vec![1.0, 0.0, 0.0, 1.0]);
// A far-off crop that deletes the (non-overlapping) pixels has nothing left to move.
let mut s = session();
s.execute("image.crop", json!({"x": MIN + 1, "y": 0, "width": 1, "height": 1})).unwrap();
assert_eq!(doc(&s).size, Size::new(1, 1));
}
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 40, "height": 20})).unwrap();
+52 -3
View File
@@ -535,8 +535,12 @@ fn link_layers(s: &mut Session) -> Result<Value> {
let linked = s.edit("Link Layers", |doc, _| {
let groups: Vec<Option<u64>> = sel.iter().map(|id| doc.layer(*id).and_then(|l| l.link_group)).collect();
// Already one link group (or a single linked layer): unlink, like Photoshop's toggle.
let unlink = groups[0].is_some() && groups.iter().all(|g| *g == groups[0]);
let next = doc.walk().iter().filter_map(|(_, _, l)| l.link_group).max().unwrap_or(0) + 1;
let first = groups.first().copied().flatten();
let unlink = first.is_some() && groups.iter().all(|g| *g == first);
// A fresh id: one past the largest, or (a stored document already uses u64::MAX) the
// smallest unused one, never an existing group that would join unrelated layers.
let used: std::collections::HashSet<u64> = doc.walk().iter().filter_map(|(_, _, l)| l.link_group).collect();
let next = used.iter().max().map_or(Some(1), |m| m.checked_add(1)).or_else(|| (1..=u64::MAX).find(|g| !used.contains(g))).unwrap_or(1);
for id in &sel {
let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
l.link_group = if unlink { None } else { Some(next) };
@@ -721,7 +725,7 @@ pub fn duplicate_selected(s: &mut Session) -> Result<Value> {
let mut new_active = None;
for id in top_level(doc, &sel) {
let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate();
dup.name = format!("{} copy", dup.name);
dup.name = doc.copy_name(&dup.name);
let nid = doc.insert_above(Some(id), dup);
if Some(id) == old_active {
new_active = Some(nid);
@@ -829,6 +833,29 @@ pub fn specs() -> Vec<CommandSpec> {
mod tests {
use super::*;
#[test]
fn duplicates_are_numbered_not_stacked() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 20, "height": 20})).unwrap();
s.execute("layer.new.layer", json!({"name": "Layer 1"})).unwrap();
let name = |s: &Session| {
let st = s.active().unwrap();
st.doc.layer(st.active_layer.unwrap()).unwrap().name.clone()
};
s.execute("layer.duplicate", json!({})).unwrap();
assert_eq!(name(&s), "Layer 1 copy");
// Duplicating the copy (the active layer) numbers it rather than adding "copy" again.
s.execute("layer.duplicate", json!({})).unwrap();
assert_eq!(name(&s), "Layer 1 copy 2");
s.execute("layer.duplicate", json!({})).unwrap();
assert_eq!(name(&s), "Layer 1 copy 3");
let doc = &s.active().unwrap().doc;
assert_eq!(doc.copy_name("Layer 1"), "Layer 1 copy 4");
// Names that merely contain "copy" keep it.
assert_eq!(doc.copy_name("Copywriting"), "Copywriting copy");
assert_eq!(doc.copy_name("A copyedit"), "A copyedit copy");
}
fn session(depth: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth})).unwrap();
@@ -1290,6 +1317,28 @@ mod tests {
s.execute("layer.translate", json!({"dx": -200_000, "dy": 200_000})).unwrap();
}
#[test]
fn link_layers_never_reuses_a_group_when_the_largest_id_is_u64_max() {
let mut s = session(8);
let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10));
let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30));
let c = rect_layer(&mut s, Rect::new(50, 50, 60, 60));
let d = rect_layer(&mut s, Rect::new(70, 70, 80, 80));
// A stored document can carry any id; `max + 1` once overflowed here.
let st = s.active_mut().unwrap();
for id in [c, d] {
std::sync::Arc::make_mut(&mut st.doc).layer_mut(id).unwrap().link_group = Some(u64::MAX);
}
select_all(&mut s, &[a, b]);
assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true);
let g = doc(&s).layer(a).unwrap().link_group;
assert_eq!(g, Some(1));
assert_eq!(doc(&s).layer(b).unwrap().link_group, g);
for id in [c, d] {
assert_eq!(doc(&s).layer(id).unwrap().link_group, Some(u64::MAX), "the existing group is untouched");
}
}
#[test]
fn linked_layers_move_together_and_undo() {
for depth in [8, 16, 32] {
+6 -1
View File
@@ -364,6 +364,9 @@ pub struct Export {
pub quick_export_format: QuickExportFormat,
pub quick_export_location: ExportLocation,
pub jpeg_quality: u32,
/// Keep the existing lossless Quick Export default until the user opts into lossy WebP.
pub webp_lossless: bool,
pub webp_quality: u32,
pub metadata: ExportMetadata,
pub convert_to_srgb: bool,
}
@@ -374,6 +377,8 @@ impl Default for Export {
quick_export_format: QuickExportFormat::Png,
quick_export_location: ExportLocation::Ask,
jpeg_quality: 85,
webp_lossless: true,
webp_quality: 85,
metadata: ExportMetadata::Copyright,
convert_to_srgb: true,
}
@@ -905,7 +910,7 @@ pub fn range(path: &str) -> Option<(f64, f64)> {
Some(match path {
"fileHandling.autosaveMinutes" => (1.0, 240.0),
"fileHandling.recentFileCount" => (0.0, 100.0),
"export.jpegQuality" => (1.0, 100.0),
"export.jpegQuality" | "export.webpQuality" => (1.0, 100.0),
"performance.memoryUsageMb" => (256.0, 1_048_576.0),
"performance.historyStates" => (1.0, 1000.0),
"performance.cacheLevels" => (1.0, 8.0),
+134 -10
View File
@@ -235,15 +235,33 @@ fn modify(s: &mut Session, p: &Value, op: &str) -> Result<Value> {
return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: format!("radius must be a number in 0..{max}") });
}
let r = r.max(0.0);
// Photoshop's "Apply effect at canvas bounds": when on, the canvas edge is a selection edge
// (Select All then Contract shrinks from the edges); when off, the selection is taken to
// continue past the canvas. Border has no such option: its band always follows the canvas edge,
// or a Select All would border to nothing.
let at_bounds = op == "border" || b(p, "applyAtCanvasBounds", false);
let (area, m) = current_mask(&s.active().ok_or(EngineError::NoDocument)?.doc);
let (w, h) = (area.width() as usize, area.height() as usize);
let out = match op {
"expand" => sel::expand(&m, w, h, r),
"contract" => sel::contract(&m, w, h, r),
"border" => sel::border(&m, w, h, r),
"smooth" => sel::smooth(&m, w, h, r),
_ => sel::feather(&m, w, h, r),
// Feather reaches 3σ = 1.5 r; the others reach r. A margin past that keeps the canvas edge out of
// reach. A selection clear of the canvas edge needs none: both readings agree there.
let reach = if op == "feather" { r * 1.5 } else { r };
let pad = if touches_edge(&m, w, h) { reach.ceil() as usize + 2 } else { 0 };
let grown = |n: usize| pad.checked_mul(2).and_then(|p| n.checked_add(p));
let (Some(pw), Some(ph)) = (grown(w), grown(h)) else {
return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: "the selection is too large to modify".into() });
};
if pw.checked_mul(ph).is_none_or(|n| n > MAX_MODIFY_PIXELS) {
return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: "the selection is too large to modify".into() });
}
let padded = pad_mask(&m, w, h, pad, at_bounds);
let out = match op {
"expand" => sel::expand(&padded, pw, ph, r),
"contract" => sel::contract(&padded, pw, ph, r),
"border" => sel::border(&padded, pw, ph, r),
"smooth" => sel::smooth(&padded, pw, ph, r),
_ => sel::feather(&padded, pw, ph, r),
};
let out = crop_mask(&out, pw, pad, w, h);
let label = match op {
"expand" => "Expand Selection",
"contract" => "Contract Selection",
@@ -254,6 +272,47 @@ fn modify(s: &mut Session, p: &Value, op: &str) -> Result<Value> {
set_selection(s, label, area, out, SelectionMode::Replace)
}
/// The largest padded mask Modify works on (a 300000 × 300000 canvas is 9e10 pixels; this caps a
/// padded copy at ~4 GB of f32, beyond which the edit is refused rather than aborting on allocation).
const MAX_MODIFY_PIXELS: usize = 1 << 30;
/// Whether any pixel on the outermost rows or columns of `m` (`w`×`h`) is selected.
fn touches_edge(m: &[f32], w: usize, h: usize) -> bool {
let sel = |x: usize, y: usize| m.get(y * w + x).is_some_and(|v| *v > 0.0);
(0..w).any(|x| sel(x, 0) || sel(x, h.saturating_sub(1))) || (0..h).any(|y| sel(0, y) || sel(w.saturating_sub(1), y))
}
/// `m` (`w`×`h`) with a `pad`-pixel margin: unselected when `outside_empty`, else the nearest
/// edge pixel repeated (the selection continues past the canvas).
fn pad_mask(m: &[f32], w: usize, h: usize, pad: usize, outside_empty: bool) -> Vec<f32> {
let pw = w + 2 * pad;
let mut out = vec![0.0f32; pw * (h + 2 * pad)];
if w == 0 || h == 0 {
return out;
}
for (py, row) in out.chunks_exact_mut(pw).enumerate() {
let inside_y = (pad..pad + h).contains(&py);
if outside_empty && !inside_y {
continue;
}
let y = py.saturating_sub(pad).min(h - 1);
for (px, v) in row.iter_mut().enumerate() {
let inside_x = (pad..pad + w).contains(&px);
if outside_empty && !inside_x {
continue;
}
let x = px.saturating_sub(pad).min(w - 1);
*v = m.get(y * w + x).copied().unwrap_or(0.0);
}
}
out
}
/// The `w`×`h` centre of a mask padded by `pad_mask`.
fn crop_mask(m: &[f32], pw: usize, pad: usize, w: usize, h: usize) -> Vec<f32> {
m.chunks_exact(pw).skip(pad).take(h).flat_map(|row| row.iter().skip(pad).take(w).copied()).collect()
}
/// Grow (contiguous) / Similar (anywhere): pixels whose colour lies within
/// the selected pixels' colour range widened by the tolerance.
fn grow_similar(s: &mut Session, p: &Value, contiguous: bool) -> Result<Value> {
@@ -351,10 +410,28 @@ pub fn specs() -> Vec<CommandSpec> {
color_range
),
spec!("select.modify.border", "Border…", ["Select", "Modify"], r##"{"radius":1..200=1}"##, has_selection, |s, p| modify(s, p, "border")),
spec!("select.modify.smooth", "Smooth…", ["Select", "Modify"], r##"{"radius":1..500=1}"##, has_selection, |s, p| modify(s, p, "smooth")),
spec!("select.modify.expand", "Expand…", ["Select", "Modify"], r##"{"radius":1..500=1}"##, has_selection, |s, p| modify(s, p, "expand")),
spec!("select.modify.contract", "Contract…", ["Select", "Modify"], r##"{"radius":1..500=1}"##, has_selection, |s, p| modify(s, p, "contract")),
spec!("select.modify.feather", "Feather…", ["Select", "Modify"], r##"{"radius":0.1..1000=1}"##, has_selection, |s, p| modify(s, p, "feather")),
spec!("select.modify.smooth", "Smooth…", ["Select", "Modify"], r##"{"radius":1..500=1,"applyAtCanvasBounds":bool=false}"##, has_selection, |s, p| {
modify(s, p, "smooth")
}),
spec!("select.modify.expand", "Expand…", ["Select", "Modify"], r##"{"radius":1..500=1,"applyAtCanvasBounds":bool=false}"##, has_selection, |s, p| {
modify(s, p, "expand")
}),
spec!(
"select.modify.contract",
"Contract…",
["Select", "Modify"],
r##"{"radius":1..500=1,"applyAtCanvasBounds":bool=false}"##,
has_selection,
|s, p| modify(s, p, "contract")
),
spec!(
"select.modify.feather",
"Feather…",
["Select", "Modify"],
r##"{"radius":0.1..1000=1,"applyAtCanvasBounds":bool=false}"##,
has_selection,
|s, p| modify(s, p, "feather")
),
spec!("select.grow", "Grow", ["Select"], r##"{"tolerance":0..255=32,"sampleAllLayers":bool=false}"##, has_selection, |s, p| grow_similar(s, p, true)),
spec!("select.similar", "Similar", ["Select"], r##"{"tolerance":0..255=32,"sampleAllLayers":bool=false}"##, has_selection, |s, p| grow_similar(
s, p, false
@@ -541,6 +618,53 @@ mod tests {
assert!(s.active().unwrap().doc.selection.is_some());
}
#[test]
fn modify_select_all_honours_canvas_bounds() {
let all = || {
let mut s = Session::new();
s.execute("file.new", json!({"width": 40, "height": 30})).unwrap();
s.execute("select.all", json!({})).unwrap();
s
};
// Off (Photoshop's default): the selection continues past the canvas, so the edges stay.
for op in ["contract", "smooth", "expand", "feather"] {
let mut s = all();
s.execute(&format!("select.modify.{op}"), json!({"radius": 4})).unwrap();
assert_eq!(coverage(&s, 0, 15), 1.0, "{op}");
assert_eq!(coverage(&s, 20, 0), 1.0, "{op}");
}
// On: the canvas edge is a selection edge (#1277).
let mut s = all();
s.execute("select.modify.contract", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap();
assert_eq!(coverage(&s, 2, 15), 0.0);
assert_eq!(coverage(&s, 20, 28), 0.0);
assert_eq!(coverage(&s, 20, 15), 1.0);
let mut s = all();
s.execute("select.modify.feather", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap();
let e = coverage(&s, 0, 15);
assert!(e > 0.2 && e < 0.8, "{e}");
assert_eq!(coverage(&s, 20, 15), 1.0);
let mut s = all();
s.execute("select.modify.smooth", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap();
assert!(coverage(&s, 0, 0) < 1.0);
// Border always follows the canvas edge: a band inside it, not an empty selection.
let mut s = all();
s.execute("select.modify.border", json!({"radius": 4})).unwrap();
assert!(coverage(&s, 0, 15) > 0.0);
assert_eq!(coverage(&s, 20, 15), 0.0);
}
#[test]
fn modify_away_from_the_canvas_edge_ignores_canvas_bounds() {
for at in [false, true] {
let mut s = session();
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();
s.execute("select.modify.contract", json!({"radius": 4, "applyAtCanvasBounds": at})).unwrap();
assert_eq!(coverage(&s, 11, 15), 0.0);
assert_eq!(coverage(&s, 15, 15), 1.0);
}
}
#[test]
fn geometry_params_that_would_wrap_are_rejected() {
let mut s = session();
+7 -6
View File
@@ -88,7 +88,7 @@ fn layer_slice_rect(doc: &Document, s: &Slice) -> Option<Rect> {
let l = doc.layer(s.layer?)?;
let b = layer_bounds(l);
let [t, le, bo, r] = s.outsets;
Some(if b.is_empty() { b } else { Rect::new(b.x0 - le, b.y0 - t, b.x1 + r, b.y1 + bo) })
Some(if b.is_empty() { b } else { Rect::new(b.x0.saturating_sub(le), b.y0.saturating_sub(t), b.x1.saturating_add(r), b.y1.saturating_add(bo)) })
}
/// Re-fits layer-based slices of the active document to their layers; drops slices whose layer
@@ -390,7 +390,7 @@ fn divide(s: &mut Session, p: &Value) -> Result<Value> {
Target::Auto(r) => r,
Target::Stored(id) => s.active().and_then(|d| d.doc.slices.get(id)).map(|sl| sl.rect).ok_or_else(|| bad(cmd, "no such slice"))?,
};
if (r.width() as i32) < across || (r.height() as i32) < down {
if r.width() < across as u32 || r.height() < down as u32 {
return Err(bad(cmd, "the slice is too small to divide that many times"));
}
let n = (down * across) as usize;
@@ -405,10 +405,11 @@ fn divide(s: &mut Session, p: &Value) -> Result<Value> {
let mut next_id = doc.slices.next_id();
for j in 0..down {
for i in 0..across {
let x0 = r.x0 + (r.width() as i32 * i) / across;
let x1 = r.x0 + (r.width() as i32 * (i + 1)) / across;
let y0 = r.y0 + (r.height() as i32 * j) / down;
let y1 = r.y0 + (r.height() as i32 * (j + 1)) / down;
// Products can exceed i32 even when every interpolated edge fits the rect.
let x = |k: i32| (i64::from(r.x0) + i64::from(r.width()) * i64::from(k) / i64::from(across)) as i32;
let y = |k: i32| (i64::from(r.y0) + i64::from(r.height()) * i64::from(k) / i64::from(down)) as i32;
let (x0, x1) = (x(i), x(i + 1));
let (y0, y1) = (y(j), y(j + 1));
let nid = if ids.is_empty() {
id
} else {
+67
View File
@@ -84,6 +84,50 @@ fn promote_auto_slice_and_divide() {
assert!(s.execute("slice.divide", json!({"slice": id})).is_err());
}
#[test]
fn divide_wide_slice_preserves_exact_edges_and_history() {
for depth in [8, 16, 32] {
for rect in
[Rect::new(-2_000_000_000, -1_000_000_000, 2_000_000_000, 1_000_000_000), Rect::new(-1_000_000_000, -1_000_000_000, 1_000_000_000, 1_000_000_000)]
{
let mut s = session(depth);
s.edit("loaded wide slice", |doc, _| {
doc.slices.list.push(Slice { id: 1, rect, name: "wide".into(), ..Default::default() });
Ok(())
})
.unwrap();
let before = doc(&s).slices.clone();
let past = s.active().unwrap().history.past_len();
let result = s.execute("slice.divide", json!({"slice": 1, "horizontal": 3, "vertical": 3})).unwrap();
assert_eq!(result["count"], 9);
assert_eq!(s.active().unwrap().history.past_len(), past + 1);
let parts = &doc(&s).slices.list;
assert_eq!(parts.len(), 9);
assert_eq!(parts[0].name, "wide");
for row in parts.as_chunks::<3>().0 {
assert_eq!(row[0].rect.x0, rect.x0);
assert_eq!(row[2].rect.x1, rect.x1);
assert_eq!(row.iter().map(|s| u64::from(s.rect.width())).sum::<u64>(), u64::from(rect.width()));
for pair in row.windows(2) {
assert_eq!(pair[0].rect.x1, pair[1].rect.x0);
assert_eq!(pair[0].rect.y0, pair[1].rect.y0);
assert_eq!(pair[0].rect.y1, pair[1].rect.y1);
}
}
assert_eq!(parts[0].rect.y0, rect.y0);
assert_eq!(parts[8].rect.y1, rect.y1);
for i in 0..6 {
assert_eq!(parts[i].rect.y1, parts[i + 3].rect.y0);
}
let divided = doc(&s).slices.clone();
assert!(s.undo());
assert_eq!(doc(&s).slices, before);
assert!(s.redo());
assert_eq!(doc(&s).slices, divided);
}
}
}
#[test]
fn slices_from_guides_and_clear() {
let mut s = session(8);
@@ -152,6 +196,29 @@ fn layer_based_slice_follows_the_layer_and_its_effects() {
}
}
#[test]
fn layer_slice_outsets_saturate_when_a_layer_moves_near_coordinate_limits() {
for offset in [i32::MIN + 100, i32::MAX - 100] {
let mut s = session(8);
let layer = add_square(&mut s, Rect::new(10, 10, 30, 20));
let slice = s.execute("layer.newLayerBasedSlice", json!({})).unwrap()["slice"].as_u64().unwrap() as u32;
s.execute("slice.set", json!({"slice": slice, "outsets": [10_000, 10_000, 10_000, 10_000]})).unwrap();
let before = doc(&s).slices.clone();
s.execute("layer.translate", json!({"layer": layer.0, "dx": offset, "dy": offset})).unwrap();
let moved = doc(&s).slices.get(slice).unwrap().rect;
let content = layer_bounds(doc(&s).layer(layer).unwrap());
assert_eq!(moved, content.inflate(10_000));
assert!(moved.contains_rect(&content));
s.execute("slice.list", json!({})).unwrap();
assert_eq!(doc(&s).slices.get(slice).unwrap().rect, moved);
assert!(s.undo());
assert_eq!(doc(&s).slices, before);
assert!(s.redo());
s.execute("slice.list", json!({})).unwrap();
assert_eq!(doc(&s).slices.get(slice).unwrap().rect, moved);
}
}
#[test]
fn slices_round_trip_through_psd_and_pcraft() {
let mut s = session(8);
+1 -1
View File
@@ -591,7 +591,7 @@ fn via_copy(s: &mut Session, p: &Value) -> Result<Value> {
s.edit("New Smart Object via Copy", |doc, active| {
let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
let mut copy = src.duplicate();
copy.name = format!("{} copy", src.name);
copy.name = doc.copy_name(&src.name);
if let LayerContent::Smart(sm) = &mut copy.content {
// Independent contents: resolve to embedded bytes and drop the shared PSD uuid.
if let Some((file_name, bytes)) = source_bytes(&doc.metadata, &sm.source) {
+1 -1
View File
@@ -191,7 +191,7 @@ fn refine_edge(s: &mut Session, p: &Value) -> Result<Value> {
let src = src_layer
.surface()
.ok_or_else(|| EngineError::Other(format!("the active layer is a {} layer without pixels", src_layer.content.kind_name())))?;
let name = format!("{} copy", src_layer.name);
let name = d.doc.copy_name(&src_layer.name);
let empty = Region { bbox: Rect::EMPTY, mask: Vec::new() };
let reg = region.as_ref().unwrap_or(&empty);
let pixels = if decontaminate { matting::decontaminate(src, reg, params.radius, amount) } else { src.clone() };
+11
View File
@@ -22,6 +22,17 @@ fn document_pixel_at_the_coordinate_limits() {
assert!(matches!(e, EngineError::BadParams { .. }), "{e}");
}
#[test]
fn file_new_at_the_size_limit_does_not_fill_every_tile() {
// A 300000² white background used to fill ~360 GB of tiles before returning (#705).
for background in ["white", "black", "backgroundColor", "#336699"] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 300_000, "height": 300_000, "background": background})).unwrap();
assert_eq!(px(&mut s, 299_999, 299_999)[3], 1.0, "{background}");
assert_eq!(px(&mut s, 0, 0)[3], 1.0, "{background}");
}
}
#[test]
fn command_ids_are_unique_and_documented() {
let mut seen = std::collections::HashSet::new();
+139 -7
View File
@@ -10,6 +10,12 @@ use serde_json::{Value, json};
use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};
/// Longest timeline, in frames: every frame becomes a surface in a new video layer and a file in
/// Render Video, so `duration` is capped well before it can exhaust memory or overflow (#1009).
const MAX_DURATION: usize = 1_000_000;
/// Highest frame rate; larger values only come from mistakes and become `inf` as `f32` (#1009).
const MAX_FPS: f32 = 1000.0;
fn has_doc(s: &Session) -> std::result::Result<(), String> {
s.active().map(|_| ()).ok_or_else(|| "no document".into())
}
@@ -36,9 +42,33 @@ fn with_timeline(s: &mut Session, f: impl FnOnce(&mut Option<Timeline>)) -> Resu
info(s)
}
fn bad(cmd: &str, msg: String) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg }
}
/// The optional `duration` param, rejected unless it's a whole number in `1..=MAX_DURATION`.
/// Before #1009 any `u64` was kept and stepping panicked on it.
fn duration_param(cmd: &str, p: &Value) -> Result<Option<usize>> {
let Some(v) = p.get("duration").filter(|v| !v.is_null()) else { return Ok(None) };
v.as_u64()
.and_then(|d| usize::try_from(d).ok())
.filter(|d| (1..=MAX_DURATION).contains(d))
.map(Some)
.ok_or_else(|| bad(cmd, format!("`duration` must be a whole number of frames from 1 to {MAX_DURATION}, got {v}")))
}
/// The optional `fps` param, rejected unless it's a finite number in `(0, MAX_FPS]` (#1009).
fn fps_param(cmd: &str, p: &Value) -> Result<Option<f32>> {
let Some(v) = p.get("fps").filter(|v| !v.is_null()) else { return Ok(None) };
v.as_f64()
.filter(|f| f.is_finite() && *f > 0.0 && *f <= f64::from(MAX_FPS))
.map(|f| Some(f as f32))
.ok_or_else(|| bad(cmd, format!("`fps` must be a number above 0 and at most {MAX_FPS}, got {v}")))
}
fn create(s: &mut Session, p: &Value) -> Result<Value> {
let duration = p.get("duration").and_then(Value::as_u64).unwrap_or(30) as usize;
let fps = p.get("fps").and_then(Value::as_f64).unwrap_or(30.0) as f32;
let duration = duration_param("timeline.create", p)?.unwrap_or(30);
let fps = fps_param("timeline.create", p)?.unwrap_or(30.0);
with_timeline(s, |t| *t = Some(Timeline::new(duration, fps)))
}
@@ -59,19 +89,21 @@ fn set_frame(s: &mut Session, p: &Value) -> Result<Value> {
fn step(s: &mut Session, delta: i64) -> Result<Value> {
with_timeline(s, |t| {
if let Some(t) = t {
t.current = (t.current as i64 + delta).clamp(0, t.duration as i64 - 1) as usize;
t.step(delta);
}
})
}
fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
let fps = fps_param("timeline.setProps", p)?;
let duration = duration_param("timeline.setProps", p)?;
with_timeline(s, |t| {
if let Some(t) = t {
if let Some(fps) = p.get("fps").and_then(Value::as_f64) {
t.fps = fps as f32;
if let Some(fps) = fps {
t.fps = fps;
}
if let Some(d) = p.get("duration").and_then(Value::as_u64) {
t.duration = d as usize;
if let Some(d) = duration {
t.duration = d;
}
if let Some(ws) = p.get("workStart").and_then(Value::as_u64) {
t.work_start = ws as usize;
@@ -127,6 +159,8 @@ mod tests {
s.execute("timeline.setFrame", json!({"frame": 10})).unwrap();
s.execute("timeline.nextFrame", json!({})).unwrap();
assert_eq!(s.execute("timeline.info", json!({})).unwrap()["timeline"]["current"], 11);
s.execute("timeline.previousFrame", json!({})).unwrap();
assert_eq!(s.execute("timeline.info", json!({})).unwrap()["timeline"]["current"], 10);
// Clamp beyond the end.
let r = s.execute("timeline.setFrame", json!({"frame": 999})).unwrap();
assert_eq!(r["timeline"]["current"], 23);
@@ -138,6 +172,104 @@ mod tests {
assert_eq!(s.execute("timeline.info", json!({})).unwrap()["timeline"], Value::Null);
}
/// The document's timeline, revision and history depth, to show a rejected command changed nothing.
fn snapshot(s: &Session) -> (Option<Timeline>, u64, usize) {
let st = s.active().unwrap();
(st.doc.timeline.clone(), st.revision, st.history.past_len())
}
fn current(s: &mut Session) -> Value {
s.execute("timeline.info", json!({})).unwrap()["timeline"]["current"].clone()
}
/// #1009: `timeline.create` kept any `duration` (even `u64::MAX`) and `fps`, and stepping then
/// panicked in `i64::clamp`. Bad values are now rejected before anything changes.
#[test]
fn create_rejects_out_of_range_params() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("timeline.create", json!({"duration": 24, "fps": 24.0})).unwrap();
s.execute("timeline.setFrame", json!({"frame": 5})).unwrap();
let before = snapshot(&s);
let too_long = MAX_DURATION as u64 + 1;
for p in [
json!({"duration": 0}),
json!({"duration": u64::MAX}),
json!({"duration": i64::MAX as u64 + 1}),
json!({"duration": too_long}),
json!({"duration": -1}),
json!({"duration": 2.5}),
json!({"duration": "24"}),
json!({"fps": 0.0}),
json!({"fps": -24.0}),
json!({"fps": MAX_FPS as f64 + 1.0}),
json!({"fps": 1e300}),
json!({"fps": "fast"}),
] {
let e = s.execute("timeline.create", p.clone()).expect_err(&format!("{p} must be rejected"));
assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e}");
assert_eq!(snapshot(&s), before, "{p}: nothing changes");
}
// The issue's repro: stepping still works on the surviving timeline.
s.execute("timeline.nextFrame", json!({})).unwrap();
assert_eq!(current(&mut s), 6);
s.execute("timeline.previousFrame", json!({})).unwrap();
assert_eq!(current(&mut s), 5);
// Control: the largest accepted values still create a timeline that steps at both ends.
let r = s.execute("timeline.create", json!({"duration": MAX_DURATION, "fps": MAX_FPS as f64})).unwrap();
assert_eq!(r["timeline"]["duration"], MAX_DURATION);
s.execute("timeline.previousFrame", json!({})).unwrap();
assert_eq!(current(&mut s), 0);
s.execute("timeline.setFrame", json!({"frame": MAX_DURATION})).unwrap();
s.execute("timeline.nextFrame", json!({})).unwrap();
assert_eq!(current(&mut s), MAX_DURATION - 1);
// Control: `null` means "use the default", as before.
let r = s.execute("timeline.create", json!({"duration": null, "fps": null})).unwrap();
assert_eq!((r["timeline"]["duration"].as_u64(), r["timeline"]["fps"].as_f64()), (Some(30), Some(30.0)));
}
/// #1009: `timeline.setProps` could store the same out-of-range `duration` and `fps`.
#[test]
fn set_props_rejects_out_of_range_params() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("timeline.create", json!({"duration": 24, "fps": 24.0})).unwrap();
let before = snapshot(&s);
for p in [json!({"duration": 0}), json!({"duration": u64::MAX}), json!({"fps": 0.0}), json!({"fps": -1.0}), json!({"fps": 30.0, "duration": 0})] {
let e = s.execute("timeline.setProps", p.clone()).expect_err(&format!("{p} must be rejected"));
assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e}");
assert_eq!(snapshot(&s), before, "{p}: nothing changes");
}
s.execute("timeline.nextFrame", json!({})).unwrap();
assert_eq!(current(&mut s), 1);
}
/// #1009: a timeline stored with `duration` 0 or `u64::MAX` (an old or hand-edited file) steps
/// without panicking and lands on a valid frame.
#[test]
fn step_is_safe_on_any_stored_timeline() {
for duration in [0, 1, usize::MAX] {
for current in [0, usize::MAX] {
for (cmd, delta) in [("timeline.nextFrame", 1i64), ("timeline.previousFrame", -1)] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
let st = s.active_mut().unwrap();
let mut doc = (*st.doc).clone();
doc.timeline = Some(Timeline { fps: f32::NAN, duration, current, work_start: usize::MAX, work_end: 0 });
st.doc = Arc::new(doc);
let r = s.execute(cmd, json!({})).unwrap_or_else(|e| panic!("{cmd} d={duration} c={current}: {e}"));
let t = &r["timeline"];
let d = t["duration"].as_u64().unwrap();
let c = t["current"].as_u64().unwrap();
assert!(d >= 1 && c < d, "{cmd} d={duration} c={current}: {t}");
if duration == usize::MAX && current == 0 {
assert_eq!(c, if delta > 0 { 1 } else { 0 });
}
}
}
}
}
#[test]
fn navigation_without_timeline_errors() {
let mut s = Session::new();
+4 -1
View File
@@ -164,13 +164,16 @@ fn apply_to_doc(doc: &mut Document, vars: &Variables, set: &DataSet) -> Result<(
}
}
(VarKind::TextReplacement, VarValue::Text(text)) => {
let snapshot = doc.clone();
if let Some(l) = doc.layer_mut(def.layer)
&& let LayerContent::Text(t) = &mut l.content
{
t.text = text.clone();
t.cache = None; // force re-render
t.runs.clear(); // re-flow as one run from the summary style
t.paragraphs.clear();
// The compositor draws a type layer from its cache: clearing it left the
// layer blank until some other edit re-rendered it (#990).
crate::type_cmds::refresh(&snapshot, t);
}
}
(VarKind::PixelReplacement { method, align, clip }, VarValue::Pixels(path)) => {
+22
View File
@@ -190,3 +190,25 @@ fn pixel_replacement_changes_the_layer() {
assert!(b > r, "replacement is blue-ish: {rgba:?}");
}
}
#[test]
fn applied_text_is_rendered_in_the_document_and_in_exports() {
// Applying a text value cleared the type layer's render cache and nothing rebuilt it, so the
// text vanished from the canvas and from every exported file (#990).
let mut s = Session::new();
s.execute("file.new", json!({"width": 200, "height": 60, "background": "white"})).unwrap();
let id = s.execute("type.create", json!({"x": 4, "y": 40, "text": "HELLO", "size": 32, "color": "#000000"})).unwrap()["layer"].clone();
let dark = |d: &Document| photocraft_compose::render(d, d.bounds()).px.iter().filter(|p| p[0] < 0.5).count();
assert!(dark(doc(&s)) > 0);
s.execute("image.variables.define", json!({"defs": [{"name": "headline", "layer": id, "type": "textReplacement"}]})).unwrap();
s.execute("image.variables.dataSets", json!({"dataSets": [{"name": "row1", "values": [{"variable": "headline", "kind": "text", "value": "BYE"}]}]}))
.unwrap();
let dir = tmp("text-export");
let out = s.execute("file.export.dataSetsAsFiles", json!({"dir": dir, "format": "png"})).unwrap();
let path = out["files"][0].as_str().unwrap();
let exported = photocraft_io::import(path, &std::fs::read(path).unwrap()).unwrap().document;
assert!(dark(&exported) > 0, "the exported row keeps its text");
s.execute("image.applyDataSet", json!({"name": "row1"})).unwrap();
assert!(dark(doc(&s)) > 0, "the applied text is drawn");
let _ = std::fs::remove_dir_all(&dir);
}
+8 -3
View File
@@ -840,6 +840,8 @@ fn export_preferences(s: &mut Session, p: &Value) -> Result<Value> {
("quickExportFormat", "export.quickExportFormat"),
("quickExportLocation", "export.quickExportLocation"),
("jpegQuality", "export.jpegQuality"),
("webpLossless", "export.webpLossless"),
("webpQuality", "export.webpQuality"),
("metadata", "export.metadata"),
("convertToSrgb", "export.convertToSrgb"),
] {
@@ -897,9 +899,12 @@ fn quick_export(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("format".into(), json!("gif"));
}
"webp" => {
// WebP has no legacy Save for Web optimiser: write it through the regular exporter.
// WebP uses the regular exporter. Its optional quality is in the Photoshop-style
// 0–12 save scale: invert that mapping so the codec receives the chosen 1–100.
// Keeping quality absent preserves the historical lossless Quick Export behavior.
let (wdoc, _, _) = web_document(&doc, &json!({}), &WebSettings { convert_to_srgb: prefs.convert_to_srgb, ..Default::default() })?;
let warnings = crate::file_cmds::save_doc(&wdoc, &path, None)?;
let quality = if prefs.webp_lossless { None } else { Some((f64::from(prefs.webp_quality.clamp(1, 100)) - 1.0) * 12.0 / 99.0) };
let warnings = crate::file_cmds::save_doc(&wdoc, &path, quality)?;
crate::automate_cmds::fire_event(s, "export");
return Ok(json!({"path": path, "format": fmt, "warnings": warnings}));
}
@@ -1211,7 +1216,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Preferences…",
&["File", "Export"],
None,
r##"{"quickExportFormat":"png|jpg|gif|webp"?,"quickExportLocation":"ask|sameFolder"?,"jpegQuality":1..100?,"metadata":"none|copyright|all"?,"convertToSrgb":bool?} → {values}"##,
r##"{"quickExportFormat":"png|jpg|gif|webp"?,"quickExportLocation":"ask|sameFolder"?,"jpegQuality":1..100?,"webpLossless":bool?,"webpQuality":1..100?,"metadata":"none|copyright|all"?,"convertToSrgb":bool?} → {values}"##,
|_| Ok(()),
export_preferences
),
+48
View File
@@ -153,6 +153,54 @@ fn export_preferences_drive_quick_export() {
s.execute("prefs.reset", json!({"path": "export"})).unwrap();
}
#[test]
fn webp_export_preferences_select_lossless_or_lossy_output() {
let dir = tmp("quick_webp_quality");
let mut s = session(8);
let defaults = s.prefs().export.clone();
assert!(defaults.webp_lossless, "existing Quick Export defaults to lossless WebP");
assert_eq!(defaults.webp_quality, 85);
// Simulate an older stored preference section without the newly added WebP keys.
let mut old = s.prefs().to_json();
old["export"].as_object_mut().unwrap().remove("webpLossless");
old["export"].as_object_mut().unwrap().remove("webpQuality");
let restored: crate::prefs::Preferences = serde_json::from_value(old).unwrap();
assert!(restored.export.webp_lossless);
assert_eq!(restored.export.webp_quality, 85);
let r = s.execute("file.export.exportPreferences", json!({"quickExportFormat": "webp", "webpLossless": true, "webpQuality": 40})).unwrap();
assert_eq!(r["values"]["webpLossless"], true);
assert_eq!(r["values"]["webpQuality"], 40);
let lossless_path = format!("{dir}/lossless.webp");
s.execute("file.export.quickExport", json!({"path": lossless_path})).unwrap();
let lossless = std::fs::read(&lossless_path).unwrap();
assert!(lossless.starts_with(b"RIFF") && &lossless[8..12] == b"WEBP");
assert!(lossless.windows(4).any(|w| w == b"VP8L"), "lossless WebP should use VP8L");
assert_eq!(decode(&lossless_path).dimensions(), (64, 48));
s.execute("file.export.exportPreferences", json!({"webpLossless": false})).unwrap();
let low_path = format!("{dir}/lossy40.webp");
s.execute("file.export.quickExport", json!({"path": low_path})).unwrap();
let low = std::fs::read(&low_path).unwrap();
assert!(low.windows(4).any(|w| w == b"VP8 "), "lossy WebP should contain a VP8 frame");
assert_eq!(decode(&low_path).dimensions(), (64, 48));
s.execute("file.export.exportPreferences", json!({"webpQuality": 90})).unwrap();
let high_path = format!("{dir}/lossy90.webp");
s.execute("file.export.quickExport", json!({"path": high_path})).unwrap();
let high = std::fs::read(&high_path).unwrap();
assert!(high.windows(4).any(|w| w == b"VP8 "));
assert_eq!(decode(&high_path).dimensions(), (64, 48));
assert_ne!(low, high, "changing WebP quality should change the encoded image");
let before = s.prefs().export.webp_quality;
for quality in [0, 101] {
assert!(s.execute("file.export.exportPreferences", json!({"webpQuality": quality})).is_err());
assert_eq!(s.prefs().export.webp_quality, before);
}
}
#[test]
fn generator_naming_grammar() {
let a = parse_asset_name("200% [email protected], 48x48 icons/bar.png8 + photo.jpg8", 72.0);
+14 -4
View File
@@ -15,7 +15,7 @@
use photocraft_color::BlendMode;
use photocraft_compose::adjust::{self, Transfer};
use photocraft_compose::effects::has_effects;
use photocraft_doc::adjust::ToneSpace;
use photocraft_doc::adjust::{ToneSpace, lut3d_len};
use photocraft_doc::{Adjustment, Document, Effect, Fill, FxPaint, GlobalLight, Glow, Gradient, Layer, LayerContent, LayerId, Pattern, StrokePosition};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
@@ -1537,11 +1537,12 @@ pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraf
}
(15, p, Some(vec![row]))
}
Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if *size >= 2 && table.len() >= (*size as usize).pow(3) * 3 => {
Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if lut3d_len(*size).is_some_and(|len| table.len() >= len) => {
// The flattened table (n³ RGB triplets) spans as many 4096-wide rows as it needs.
let n = *size as usize;
let len = n * n * n * 3;
let rows = table[..len]
let rows = lut3d_len(*size)
.and_then(|len| table.get(..len))
.unwrap_or_default()
.chunks(4096)
.map(|c| {
let mut row = [0.0f32; 4096];
@@ -1609,6 +1610,15 @@ mod tests {
use photocraft_color::{Color, ColorMode, SampleType};
use photocraft_geom::Size;
#[test]
fn color_lookup_with_an_overflowing_stored_size_uploads_no_table() {
for size in [1 << 22, u32::MAX] {
let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false };
let (kind, _, rows) = adjustment_program(&a, Transfer::Srgb, SampleType::U8);
assert_eq!((kind, rows.is_none()), (0, true), "size {size}");
}
}
#[test]
fn slots_are_recycled() {
let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE);
+3 -4
View File
@@ -605,10 +605,9 @@ pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec<u8>)> {
// A lookup without a usable table (none chosen yet, or a bad size) renders as the
// identity, so it is written as a 2³ identity cube rather than dropped.
let n = *size as usize;
let (file, dither) = match lut {
Some(table) if (2..=256).contains(&n) && table.len() >= n * n * n * 3 => {
(photocraft_cms::lutfile::LutFile { title: String::new(), size: n, data: table[..n * n * n * 3].to_vec() }, *dither)
}
let cube = lut.as_deref().zip(photocraft_doc::adjust::lut3d_len(*size)).and_then(|(table, len)| table.get(..len)).filter(|_| n <= 256);
let (file, dither) = match cube {
Some(cube) => (photocraft_cms::lutfile::LutFile { title: String::new(), size: n, data: cube.to_vec() }, *dither),
_ => (photocraft_cms::lutfile::LutFile { title: String::new(), ..photocraft_cms::lutfile::LutFile::identity(2) }, false),
};
let en =
+5 -1
View File
@@ -244,7 +244,11 @@ impl Ex {
fn encode(&self, id: i16, plane: &[u8], w: usize, h: usize) -> ChannelData {
let depth = psd_depth(self.fmt.sample);
ChannelData::encode(id, self.compression(), plane, w, h, depth, self.version)
// Photoshop writes empty layer/mask channels as just the raw compression code.
// A ZIP stream for a zero-sized channel makes readers try to decompress an
// invalid image extent (notably psd-tools for 32-bit adjustment layers).
let compression = if w == 0 || h == 0 { Compression::Raw } else { self.compression() };
ChannelData::encode(id, compression, plane, w, h, depth, self.version)
.or_else(|_| ChannelData::encode(id, Compression::Raw, plane, w, h, depth, self.version))
.unwrap_or(ChannelData { id, compression: Some(Compression::Raw), data: plane.to_vec() })
}
+6
View File
@@ -133,6 +133,12 @@ impl Ctx<'_> {
if ids.zip(&planes).any(|(id, p)| p.is_none() && rec.channel(id).is_some()) {
return Surface::new(self.fmt);
}
// Only decoded channel data justifies a buffer: the decoders bound their output by the
// bytes in the file, but a bare rectangle can declare 300000² pixels in a few bytes (#755).
if planes.iter().all(Option::is_none) {
self.warn(format!("layer \"{name}\": no channel data for its {w}x{h} bounds; treated as empty"));
return Surface::new(self.fmt);
}
let refs: Vec<Option<&[u8]>> = planes.iter().map(|p| p.as_deref()).collect();
let mut fill: Vec<Vec<u8>> = vec![zero_sample(s); self.cc];
fill.push(max_sample(s));
+44
View File
@@ -0,0 +1,44 @@
mod common;
use common::Features;
use photocraft_color::{ColorMode, SampleType};
use photocraft_io::{ExportOptions, export};
use photocraft_psd::{Compression, PsdFile};
#[test]
fn empty_layer_and_mask_channels_use_raw_without_a_payload() {
for mode in [ColorMode::Rgb, ColorMode::Grayscale] {
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
for ext in ["out.psd", "out.psb"] {
let mut doc = common::gen_doc(mode, depth, Features::ALL);
let mut masked = common::raster("Uniform mask", doc.pixel_format(), photocraft_geom::Rect::new(0, 0, 3, 3), 1, true);
masked.mask = Some(photocraft_doc::LayerMask {
surface: photocraft_raster::Surface::new(photocraft_color::PixelFormat::new(ColorMode::Grayscale, depth, false)),
enabled: true,
linked: true,
density: 1.0,
feather: 0.0,
});
doc.layers.push(masked);
let bytes = export(&doc, ext, &ExportOptions::default()).unwrap().bytes;
let file = PsdFile::from_bytes(&bytes).unwrap();
let mut empty = 0;
let mut empty_masks = 0;
for layer in file.layers() {
for channel in &layer.channels {
let rect = layer.channel_rect(channel.id);
if rect.width() == 0 || rect.height() == 0 {
empty += 1;
if channel.id == -2 {
empty_masks += 1;
}
assert_eq!(channel.compression, Some(Compression::Raw), "{mode:?} {depth:?} {ext}: {} channel {}", layer.name(), channel.id);
assert!(channel.data.is_empty());
}
}
}
assert!(empty > 0);
assert!(empty_masks > 0);
}
}
}
}
+13
View File
@@ -541,3 +541,16 @@ fn every_blend_mode_maps_both_ways() {
assert_eq!(photocraft_color::BlendMode::from_psd_key(k.key()), Some(m));
}
}
#[test]
fn layer_bounds_without_channel_data_allocate_nothing() {
// A record can declare a 300000x300000 rectangle in a few bytes. With no channel data to
// back it, import used to interleave a ~360 GB buffer and abort on the allocation (#755).
use photocraft_psd::LayerRecord;
let mut f = testgen::small(Version::Psd, Compression::Raw);
f.layers_mut().push(LayerRecord { rect: photocraft_psd::Rect::from_xywh(0, 0, 300_000, 300_000), name: b"huge".to_vec(), ..Default::default() });
let (d, warnings) = psd_to_document(&f);
let l = d.layers.last().unwrap();
assert!(matches!(&l.content, LayerContent::Raster(s) if s.tile_count() == 0));
assert!(warnings.iter().any(|w| w.contains("\"huge\"")), "{warnings:?}");
}
+61 -2
View File
@@ -214,11 +214,31 @@ impl LayerMask {
/// Whether `d` (a whole mask record with mask parameters) stores the real-mask fields before
/// the parameters, as Photoshop does. The spec's order wins when it reads as parameters
/// followed by padding alone (no real mask), the one layout the two orders can share.
/// followed by padding alone (no real mask), the one layout the two orders can share. When
/// both orders fit the record's length, Photoshop's is taken unless its reading is
/// implausible (a real-mask background that is neither 0 nor 255, or parameter flag bits
/// the spec does not define) while the spec's reading with a real mask is sound.
pub(crate) fn real_before_parameters(d: &[u8]) -> bool {
// Parameters at `pf_at`, then 0..=3 bytes of padding, and nothing else.
let fits =
|pf_at: usize| d.get(pf_at).is_some_and(|&pf| (pf_at + 1 + mask_parameter_bytes(pf)..=pf_at + 4 + mask_parameter_bytes(pf)).contains(&d.len()));
!fits(18) && fits(36)
if fits(18) {
return false;
}
let photoshop = fits(36);
if !photoshop {
return false;
}
let known_flags = |pf: u8| pf & 0xF0 == 0;
let real_background_ok = |at: usize| d.get(at + 1).is_some_and(|&bg| bg == 0 || bg == 255);
// Photoshop's reading: real-mask fields at 18, parameters at 36.
let photoshop_plausible = real_background_ok(18) && d.get(36).is_some_and(|&pf| known_flags(pf));
// The spec's reading: parameters at 18, then the 18 real-mask bytes, then padding.
let spec_plausible = d.get(18).is_some_and(|&pf| {
let real_at = 19 + mask_parameter_bytes(pf);
known_flags(pf) && (real_at + 18..=real_at + 21).contains(&d.len()) && real_background_ok(real_at)
});
photoshop_plausible || !spec_plausible
}
fn parse(d: &[u8]) -> Result<Self> {
@@ -845,6 +865,45 @@ mod tests {
assert_eq!(out, d);
}
/// A density-only record in the spec's order (#949): the parameter flags byte at 18 says one
/// value byte, so the spec's reading excludes the 38-byte length only if the real mask is
/// ignored, while byte 36 (inside the real rectangle's `right`) is 0 and makes Photoshop's
/// reading fit too. Photoshop's reading puts the density (64) where a 0-or-255 background
/// belongs, so the spec's order wins and the density survives.
#[test]
fn density_only_spec_layout_is_not_read_as_photoshop_order() {
for (density, right) in [(64u8, 1u32), (200, 1), (64, 300), (1, 7)] {
let mut d = Vec::new();
Rect::from_xywh(0, 0, 1, 1).write(&mut d);
d.extend([255, LayerMask::FLAG_PARAMETERS]);
d.extend([0b0001, density]);
d.extend([0, 0]);
Rect::from_xywh(0, 0, right, 1).write(&mut d);
let m = LayerMask::parse(&d).unwrap();
assert!(!m.real_first, "density {density}, right {right}: {m:?}");
assert_eq!(m.parameters.unwrap().user_density, Some(density));
assert_eq!(m.real, Some(RealMask { flags: 0, background: 0, rect: Rect::from_xywh(0, 0, right, 1) }));
assert!(m.trailing.is_empty());
let mut out = Vec::new();
m.write(&mut out);
assert_eq!(out, d);
}
// Photoshop's order with the same lengths still reads as Photoshop's order.
let mut d = Vec::new();
Rect::from_xywh(0, 0, 1, 1).write(&mut d);
d.extend([255, LayerMask::FLAG_PARAMETERS]);
d.extend([0, 255]);
Rect::from_xywh(0, 0, 1, 1).write(&mut d);
d.extend([0b0001, 64]);
let m = LayerMask::parse(&d).unwrap();
assert!(m.real_first, "{m:?}");
assert_eq!(m.parameters.unwrap().user_density, Some(64));
assert_eq!(m.real.map(|r| r.background), Some(255));
let mut out = Vec::new();
m.write(&mut out);
assert_eq!(out, d);
}
/// The spec's order (parameters, then real fields) still parses and stays byte-stable.
#[test]
fn real_mask_after_parameters_spec_layout() {
+27
View File
@@ -285,3 +285,30 @@ fn save_and_open() {
assert_eq!(g, f);
let _ = std::fs::remove_dir_all(&dir);
}
/// A density-only mask record written in the spec's order (parameters, then the real-mask
/// fields) used to be read back in Photoshop's order, which moved the density into the real
/// mask's background and dropped it from the parameters (#949). The model must survive the
/// round trip, not only the bytes.
#[test]
fn spec_order_density_only_mask_round_trips_as_a_model() {
let mut f = testgen::small(Version::Psd, Compression::Raw);
let layer = &mut f.layers_mut()[0];
layer.mask = MaskData::Mask(LayerMask {
rect: Rect::from_xywh(0, 0, 1, 1),
default_color: 255,
flags: LayerMask::FLAG_PARAMETERS,
parameters: Some(MaskParameters { flags: 1, user_density: Some(64), ..Default::default() }),
real: Some(RealMask { flags: 0, background: 0, rect: Rect::from_xywh(0, 0, 1, 1) }),
trailing: vec![],
real_first: false,
});
// The generated 2 x 2 mask channel is replaced by one that matches the 1 x 1 rectangle.
let mask_channel = layer.channels.iter_mut().find(|c| c.id == -2).expect("the generated layer has a mask channel");
*mask_channel = ChannelData::encode(-2, Compression::Raw, &[64], 1, 1, 8, Version::Psd).unwrap();
let b = f.to_bytes().unwrap();
let g = PsdFile::from_bytes(&b).unwrap();
assert_eq!(g, f, "model round trip");
assert_eq!(g.layers()[0].decode_channel(-2, 8, Version::Psd).unwrap(), vec![64]);
assert_eq!(g.to_bytes().unwrap(), b, "byte stability");
}
+27
View File
@@ -438,8 +438,17 @@ impl Surface {
let mut enc = vec![0u8; self.format.bytes_per_pixel()];
encode_pixel(&self.format, &px[..n], &mut enc);
let bpp = enc.len();
// Fully covered tiles share one Arc: a solid fill costs one tile however large `r` is,
// and copy-on-write splits a tile off when it is edited (#705).
let mut full: Option<Arc<Tile>> = None;
for tc in r.tiles() {
let tr = tc.rect().intersect(&r);
if tr == tc.rect() {
let fmt = self.format;
let t = full.get_or_insert_with(|| Arc::new(Tile::filled(&fmt, &enc)));
self.tiles.insert(tc, t.clone());
continue;
}
let t = self.tile_mut(tc);
for y in tr.y0..tr.y1 {
let ly = (y - tc.ty * TILE_SIZE) as usize;
@@ -681,6 +690,24 @@ mod tests {
}
}
#[test]
fn fill_rect_shares_covered_tiles_and_edits_stay_local() {
// A 300000² background used to materialize ~360 GB of tiles (#705).
let mut s = Surface::new(PixelFormat::RGBA8);
s.fill_rect(Rect::new(0, 0, 300_000, 300_000), &[1.0, 0.5, 0.0, 1.0]);
let t = |s: &Surface, x, y| s.tile(TileCoord::new(x, y)).unwrap().clone();
assert!(Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1000, 900)));
// 300000 is not a multiple of 256: the edge tile is partial and stays its own.
let edge = 300_000 / TILE_SIZE;
assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, edge, 0)));
assert_eq!(s.pixel(299_999, 299_999), vec![1.0, 128.0 / 255.0, 0.0, 1.0]);
assert_eq!(s.pixel(300_000, 0), vec![0.0; 4]);
s.write_pixel(5, 5, &[0.0, 0.0, 1.0, 1.0]);
assert_eq!(s.pixel(5, 5), vec![0.0, 0.0, 1.0, 1.0]);
assert_eq!(s.pixel(300, 5), vec![1.0, 128.0 / 255.0, 0.0, 1.0]);
assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1, 0)));
}
#[test]
fn empty_surface_reads_default() {
let s = Surface::new(PixelFormat::RGBA8);
+2
View File
@@ -594,6 +594,8 @@ pub(crate) fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E {
("Strikethrough".into(), E::Bool(s.strikethrough)),
("Ligatures".into(), E::Bool(s.ligatures)),
("DLigatures".into(), E::Bool(s.discretionary_ligatures)),
// Photopea lays out edited text without painting it unless its fill is enabled.
("FillFlag".into(), E::Bool(true)),
("FillColor".into(), E::Dict(vec![("Type".into(), E::Int(color_type)), ("Values".into(), E::Array(values))])),
];
dict.append(&mut opentype);
+69
View File
@@ -545,6 +545,75 @@ fn txt2_carries_optical_kerning() {
assert!(l.char_runs().iter().all(|r| r.style.kerning == Kerning::Optical));
}
/// Photopea needs an enabled fill, not just FillColor, to paint text after an edit. Inspect the
/// serialized TySh rather than our renderer, which does not consume the PSD fill flag.
#[test]
fn psd_text_fill_is_enabled_in_runs_and_new_default_styles() {
let mut t = point("AB", 100.0);
t.runs = vec![
TextRun { len: 1, style: CharStyle { color: Color::rgb(0.2, 0.4, 0.6), ..Default::default() } },
TextRun { len: 1, style: CharStyle { faux_bold: true, size_pt: 100.0, ..Default::default() } },
];
for shape in [TextShape::Point, TextShape::Box { x: 0.0, y: 0.0, width: 300.0, height: 200.0 }] {
t.shape = shape;
let tysh = crate::psd::parse_tysh(&crate::psd::build_tysh(&t, 72.0, None)).unwrap();
let data = crate::psd::engine_data(&tysh.text).unwrap();
let runs = data.path(&["EngineDict", "StyleRun", "RunArray"]).unwrap().as_array().unwrap();
assert_eq!(runs.len(), 2);
for run in runs {
assert_eq!(run.path(&["StyleSheet", "StyleSheetData", "FillFlag"]).and_then(crate::engine_data::Value::as_bool), Some(true));
}
for key in ["ResourceDict", "DocumentResources"] {
let sheets = data.path(&[key, "StyleSheetSet"]).unwrap().as_array().unwrap();
assert_eq!(sheets[0].path(&["StyleSheetData", "FillFlag"]).and_then(crate::engine_data::Value::as_bool), Some(true));
}
let back = crate::psd::text_layer_from_tysh(&crate::psd::write_tysh(&tysh), 72.0).unwrap();
assert_eq!(back.text, t.text);
assert_eq!(back.runs.len(), t.runs.len());
for (actual, expected) in back.runs.iter().zip(&t.runs) {
assert_eq!(actual.style.color, expected.style.color);
assert_eq!(actual.style.size_pt, expected.style.size_pt);
assert_eq!(actual.style.faux_bold, expected.style.faux_bold);
}
}
}
#[test]
fn psd_text_fill_is_enabled_after_editing_a_legacy_export() {
use crate::engine_data::Value as E;
// A legacy PhotoCraft export has a normal style and character runs without FillFlag.
let mut t = point("Before", 40.0);
let mut legacy = crate::psd::parse_tysh(&crate::psd::build_tysh(&t, 72.0, None)).unwrap();
fn remove_fill_flags(value: &mut E) {
match value {
E::Dict(items) => {
items.retain(|(key, _)| key != "FillFlag");
for (_, value) in items {
remove_fill_flags(value);
}
}
E::Array(items) => items.iter_mut().for_each(remove_fill_flags),
_ => {}
}
}
let mut data = crate::psd::engine_data(&legacy.text).unwrap();
remove_fill_flags(&mut data);
for (key, value) in &mut legacy.text.items {
if key.as_bytes() == b"EngineData" {
*value = photocraft_psd::descriptor::Value::RawData(crate::engine_data::write(&data));
}
}
t.psd_raw = Some(crate::psd::write_tysh(&legacy).into());
t.text = "After".into();
let tysh = crate::psd::parse_tysh(&crate::psd::build_tysh(&t, 72.0, None)).unwrap();
let data = crate::psd::engine_data(&tysh.text).unwrap();
let runs = data.path(&["EngineDict", "StyleRun", "RunArray"]).unwrap().as_array().unwrap();
assert!(!runs.is_empty());
for run in runs {
assert_eq!(run.path(&["StyleSheet", "StyleSheetData", "FillFlag"]).and_then(E::as_bool), Some(true));
}
}
/// EngineData pair fields: manual kerning and "no automatic kerning" round-trip exactly, in
/// Photoshop's form (see `psd::pair_runs`).
#[test]
+94
View File
@@ -0,0 +1,94 @@
//! Layers panel: hovering a mode in the open blend-mode list previews it on the active layer
//! (Photoshop's live blend-mode preview, #970). Hovering records nothing: leaving the list, or
//! closing it without a choice, shows the document again, and choosing a mode commits it through
//! `layer.setProps` (one history step). The canvas re-renders once per hovered mode, and only
//! where the layer's blending can change pixels.
use std::sync::Arc;
use photocraft_color::BlendMode;
use photocraft_doc::{DocId, Document, LayerId};
use photocraft_geom::Rect;
use crate::PhotocraftApp;
/// Preview keys (`canvas::display_doc`) are `BASE` plus a hash of the revision and the mode.
const BASE: u64 = 1 << 37;
/// A blend mode hovered for a layer of a document at a revision.
pub(crate) struct BlendPreview {
doc: DocId,
revision: u64,
layer: LayerId,
/// The mode under the pointer; `None` once it left the list (the rest stays for the
/// canvas's damage on its way back to the document).
mode: Option<BlendMode>,
/// The frame the list was last drawn in: a list no longer drawn previews nothing.
frame: u64,
/// Where the layer's blending can change pixels; `None` for anywhere.
area: Option<Rect>,
/// The document shown for `mode`, with its key.
shown: Option<(u64, Arc<Document>)>,
}
/// The Layers panel, each frame it draws `layer`'s blend-mode dropdown: the mode under the
/// pointer in its open list, if any.
pub(crate) fn hover(app: &mut PhotocraftApp, layer: LayerId, mode: Option<BlendMode>) {
let frame = app.frame;
let Some(st) = app.session.active() else { return };
let (doc, revision) = (st.doc.id, st.revision);
if let Some(p) = app.blend_preview.as_mut().filter(|p| p.doc == doc && p.revision == revision && p.layer == layer) {
p.frame = frame;
if mode.is_none() {
p.shown = None;
}
p.mode = mode;
return;
}
app.blend_preview = mode.and_then(|mode| {
let area = photocraft_compose::change_bounds(st.doc.layer(layer)?, st.doc.bounds());
Some(BlendPreview { doc, revision, layer, mode: Some(mode), frame, area, shown: None })
});
}
/// The document to show while a blend mode is hovered in document `idx` (`canvas::display_doc`).
pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Document>, u64)> {
let frame = app.frame;
let st = app.session.documents().get(idx)?;
let p = app.blend_preview.as_mut().filter(|p| p.doc == st.doc.id && p.revision == st.revision && p.frame + 1 >= frame)?;
let mode = p.mode?;
let key = preview_key(p.revision, p.layer, mode);
if let Some((k, shown)) = &p.shown
&& *k == key
{
return Some((shown.clone(), key));
}
let mut doc = (*st.doc).clone();
let l = doc.layer_mut(p.layer).filter(|l| l.blend != mode)?;
l.blend = mode;
// Duotone documents display through their inks.
let doc = Arc::new(photocraft_engine::mode_cmds::display_document(&doc).unwrap_or(doc));
p.shown = Some((key, doc.clone()));
Some((doc, key))
}
/// What changed between preview (or document) key `seen` and `now` of document `doc` at
/// `revision`: the hovered layer's area. `None` when either key is another kind of preview, or
/// the layer can change anything (the canvas then recomposites everything).
pub(crate) fn damage(app: &PhotocraftApp, doc: DocId, revision: u64, seen: u64, now: u64) -> Option<Rect> {
let p = app.blend_preview.as_ref().filter(|p| p.doc == doc && p.revision == revision)?;
let ours = |k: u64| k == 0 || is_preview_key(k);
(seen != now && ours(seen) && ours(now) && (is_preview_key(seen) || is_preview_key(now))).then_some(p.area)?
}
fn is_preview_key(key: u64) -> bool {
(BASE..BASE << 1).contains(&key)
}
fn preview_key(revision: u64, layer: LayerId, mode: BlendMode) -> u64 {
let h = mode.label().bytes().fold(revision.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ layer.0, |h, b| h.wrapping_mul(31).wrapping_add(u64::from(b)));
(h & (BASE - 1)) | BASE
}
#[cfg(test)]
mod tests;
+106
View File
@@ -0,0 +1,106 @@
//! #970: hovering a blend mode in the Layers panel previews it on the canvas; only a choice
//! records a history step.
use egui::accesskit::Role;
use egui::{PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use photocraft_color::BlendMode;
use photocraft_doc::LayerId;
use serde_json::json;
use super::{damage, display_doc, hover};
use crate::PhotocraftApp;
/// Background and a filled layer `top` (active).
fn session() -> (photocraft_engine::Session, LayerId) {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
let top = s.execute("layer.new.layer", json!({"name": "top"})).unwrap()["layer"].as_u64().unwrap();
s.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap();
s.execute("edit.fill", json!({"color": "#cc3366"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
(s, LayerId(top))
}
fn blend(app: &PhotocraftApp, id: LayerId) -> BlendMode {
app.session.active().unwrap().doc.layer(id).unwrap().blend
}
fn steps(app: &PhotocraftApp) -> usize {
app.session.active().unwrap().history.past_len()
}
#[test]
fn a_hovered_mode_shows_on_the_canvas_until_the_pointer_leaves() {
let (s, top) = session();
let mut app = PhotocraftApp::new(s, crate::Services::default());
let (undo, revision) = (steps(&app), app.session.active().unwrap().revision);
hover(&mut app, top, Some(BlendMode::Multiply));
let (shown, key) = display_doc(&mut app, 0).expect("previewed");
assert_eq!(shown.layer(top).unwrap().blend, BlendMode::Multiply);
let (again, same) = display_doc(&mut app, 0).unwrap();
assert!(std::sync::Arc::ptr_eq(&shown, &again) && key == same, "one document per hovered mode, not one per frame");
assert_eq!((blend(&app, top), steps(&app)), (BlendMode::Normal, undo), "hovering records nothing");
// From the document to the preview and between previews: only the layer's area redraws.
let doc = app.session.active().unwrap().doc.id;
assert_eq!(damage(&app, doc, revision, 0, key).map(|r| r.width()), Some(16));
hover(&mut app, top, Some(BlendMode::Screen));
let (_, screen) = display_doc(&mut app, 0).unwrap();
assert_ne!(screen, key);
assert!(damage(&app, doc, revision, key, screen).is_some());
// The current mode, or no mode, shows the document; and so does a list no longer drawn.
hover(&mut app, top, Some(BlendMode::Normal));
assert!(display_doc(&mut app, 0).is_none());
hover(&mut app, top, None);
assert!(display_doc(&mut app, 0).is_none());
assert!(damage(&app, doc, revision, screen, 0).is_some(), "back to the document: the layer's area");
hover(&mut app, top, Some(BlendMode::Multiply));
app.frame += 2;
assert!(display_doc(&mut app, 0).is_none(), "a stale hover previews nothing");
}
fn harness(session: photocraft_engine::Session) -> Harness<'static, PhotocraftApp> {
let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
PhotocraftApp::new(session, crate::Services::default())
});
h.run_steps(8);
h
}
fn click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2) {
h.hover_at(at);
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.run_steps(3);
}
fn previewed(h: &mut Harness<'_, PhotocraftApp>) -> Option<BlendMode> {
display_doc(h.state_mut(), 0).map(|(d, _)| d.layers.last().unwrap().blend)
}
#[test]
fn hovering_the_layers_panel_blend_list_previews_and_a_click_commits() {
let (s, top) = session();
let mut h = harness(s);
let undo = steps(h.state());
// The Layers panel's dropdown: the lowest one (the options bar and the title bar have some too).
let dropdown = h.query_all_by_role(Role::ComboBox).map(|n| n.rect()).max_by(|a, b| a.top().total_cmp(&b.top())).unwrap();
click(&mut h, dropdown.center());
let multiply = h.get_by_label("Multiply").rect().center();
h.hover_at(multiply);
h.run_steps(3);
assert_eq!(previewed(&mut h), Some(BlendMode::Multiply), "the hovered mode shows");
assert_eq!((blend(h.state(), top), steps(h.state())), (BlendMode::Normal, undo), "no edit while hovering");
h.hover_at(Pos2::new(400.0, 400.0));
h.run_steps(3);
assert_eq!(previewed(&mut h), None, "off the list: the document again");
let screen = h.get_by_label("Screen").rect().center();
click(&mut h, screen);
assert_eq!(blend(h.state(), top), BlendMode::Screen);
assert_eq!(steps(h.state()), undo + 1, "choosing records one step");
assert_eq!(previewed(&mut h), None);
}
+16 -1
View File
@@ -492,6 +492,10 @@ fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc<Document>
if let Some(shown) = crate::patch_preview::display_doc(app, idx) {
return shown;
}
// A blend mode hovered in the Layers panel.
if let Some(shown) = crate::blend_preview::display_doc(app, idx) {
return shown;
}
let st = &app.session.documents()[idx];
if let Some(l) = live_stroke(app, idx) {
return (l.stroke.doc.clone(), l.display_key());
@@ -694,6 +698,13 @@ fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), now: (u64, u6
{
return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) });
}
// Between hovered blend modes (and the document): where the layer's blending shows.
if seen.0 == now.0
&& let Some(st) = app.session.documents().get(idx)
&& let Some(r) = crate::blend_preview::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1)
{
return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) });
}
let l = live_stroke(app, idx).filter(|l| seen.0 == now.0 && l.display_key() == now.1)?;
let r = l.since(seen.1 ^ display_key)?;
Some(if r.is_empty() { r } else { r.inflate(effect_reach(&l.stroke.doc.layers)) })
@@ -1392,7 +1403,8 @@ fn start_screen(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.add_space(((card.width() - 2.0 * 190.0 - 12.0) / 2.0).max(0.0));
ui.spacing_mut().item_spacing.x = 12.0;
if crate::widgets::primary_button(ui, &new_label, 190.0).clicked() {
app.ui.open_dialog(crate::state::DialogKind::NewDocument, crate::state::UiState::new_document_fields());
let fields = app.new_document_fields();
app.ui.open_dialog(crate::state::DialogKind::NewDocument, fields);
}
if crate::widgets::secondary_button(ui, &open_label, 190.0).clicked() {
app.open_dialog_file();
@@ -1817,12 +1829,14 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
{
crate::canvas_tool_menu::open_transform(app, [p.x, p.y]);
}
let lasso_retracted = tool == Tool::Lasso && response.secondary_clicked() && crate::lasso_ui::undo_last_vertex(app);
if tool == Tool::Lasso {
crate::lasso_ui::canvas_input(app, &ctx, &xf, &response);
(buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false);
}
// Right-click with the Move tool, or ⌘/Ctrl+right-click: the layers under the pointer.
if response.secondary_clicked()
&& !lasso_retracted
&& !transforming
&& crate::layer_pick_ui::is_gesture(tool, mods)
&& let Some(p) = response.interact_pointer_pos()
@@ -1832,6 +1846,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
crate::layer_pick_ui::open(app, [p.x, p.y], d[0], d[1]);
}
if response.secondary_clicked()
&& !lasso_retracted
&& !transforming
&& !crate::layer_pick_ui::is_gesture(tool, mods)
&& let Some(p) = response.interact_pointer_pos()
+4 -2
View File
@@ -35,8 +35,8 @@ pub const TRANSFORM_MENU: &[Row] = &[
];
/// Photoshop's selection-tool context menu with an active selection, in its order. Its Generative
/// Fill and Delete and Fill Selection rows have no PhotoCraft command and are left out. Rows
/// stay visible and grey out exactly like their menu-bar twins.
/// Fill row has no PhotoCraft command and is left out. Rows stay visible and grey out exactly like
/// their menu-bar twins.
pub const SELECTION_MENU: &[Row] = &[
Some(("Deselect", "select.deselect")),
Some(("Select Inverse", "select.inverse")),
@@ -55,6 +55,7 @@ pub const SELECTION_MENU: &[Row] = &[
Some(("Distort", "edit.transform.distort")),
Some(("Perspective", "edit.transform.perspective")),
None,
Some(("Delete and Fill Selection", "edit.deleteAndFillSelection")),
Some(("Fill…", "edit.fill")),
Some(("Stroke…", "edit.stroke")),
Some(("Content-Aware Fill…", "edit.contentAwareFill")),
@@ -440,6 +441,7 @@ mod tests {
Some("Distort"),
Some("Perspective"),
None,
Some("Delete and Fill Selection"),
Some("Fill…"),
Some("Stroke…"),
Some("Content-Aware Fill…"),
+20 -2
View File
@@ -397,8 +397,10 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
None => err("no such dialog"),
},
"ui.window.open" => {
if let Some(d) = u("document") {
app.session.set_active(d as usize);
if let Some(d) = u("document")
&& !app.session.set_active(d as usize)
{
return err(format!("no document {d}"));
}
wrap(crate::menus::invoke(app, ctx, "window.newWindowForDocument", json!({})))
}
@@ -805,6 +807,22 @@ mod tests {
}
}
#[test]
fn ui_window_open_rejects_an_unknown_document_index() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
let ctx = egui::Context::default();
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
// An out-of-range index must error instead of silently switching the active document
// and opening the window for whatever is active now.
let before = app.session.active_index();
let r = call(&mut app, &ctx, "ui.window.open", json!({"document": 99}));
assert_eq!(r["ok"], false, "{r}");
assert!(r["error"].as_str().unwrap().contains("no document 99"), "{r}");
assert_eq!(app.session.active_index(), before, "the active document is untouched");
// A valid index still opens the window.
assert_eq!(call(&mut app, &ctx, "ui.window.open", json!({"document": 0}))["ok"], true);
}
#[test]
fn ui_set_brush_size_dispatches_a_journaled_brush_command() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+5 -1
View File
@@ -324,7 +324,11 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
app.filter_preview = None;
let cmd = d.fields.get("__command").and_then(|v| v.as_str().map(str::to_string)).ok_or("dialog has no command")?;
let (cmd, params) = crate::smart_ui::confirm_command(&d.fields, cmd, crate::filter_dialog::params_of(&d.fields));
app.run(&cmd, params)
let result = app.run(&cmd, params.clone());
if result.is_ok() && cmd == "view.newGuideLayout" {
app.ui.view.guide_layout = params;
}
result
}
DialogKind::LayerStyle => crate::layer_style::confirm(app, &d.fields),
DialogKind::About | DialogKind::Error => Ok(Value::Null),
+41 -3
View File
@@ -19,8 +19,8 @@ pub fn open(app: &mut PhotocraftApp) -> Result<u64, String> {
f.insert("__export".into(), json!(true));
f.insert("__label".into(), json!("Export As"));
f.insert("format".into(), json!("png"));
f.insert("quality".into(), json!(85));
f.insert("lossless".into(), json!(false));
f.insert("quality".into(), json!(app.session.prefs().export.jpeg_quality));
f.insert("lossless".into(), json!(app.session.prefs().export.webp_lossless));
f.insert("transparency".into(), json!(true));
f.insert("scale".into(), json!(100));
f.insert("metadata".into(), json!("none"));
@@ -92,6 +92,22 @@ fn export_document(doc: &Document, f: &Map<String, Value>, max_side: Option<u32>
s.active().map(|d| (*d.doc).clone()).ok_or_else(|| "export failed".into())
}
/// Export As already supports lossy WebP; reuse the Quick Export defaults when
/// choosing that format so both flows expose the same quality and lossless options.
fn set_format_defaults(f: &mut Map<String, Value>, fmt: &str, prefs: &photocraft_engine::prefs::Export) {
f.insert("format".into(), json!(fmt));
match fmt {
"jpg" => {
f.insert("quality".into(), json!(prefs.jpeg_quality));
}
"webp" => {
f.insert("quality".into(), json!(prefs.webp_quality));
f.insert("lossless".into(), json!(prefs.webp_lossless));
}
_ => {}
}
}
fn s_fmt(f: &Map<String, Value>) -> String {
let v = s(f, "format");
if v.is_empty() { "png".into() } else { v }
@@ -137,7 +153,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
let mut fmt = s_fmt(f);
let opts: Vec<(String, &str)> = FORMATS.iter().map(|(k, l)| (k.to_string(), *l)).collect();
if crate::widgets::dropdown(ui, "export-format", &mut fmt, &opts, 130.0) {
f.insert("format".into(), json!(fmt));
set_format_defaults(f, &fmt, &app.session.prefs().export);
}
});
let fmt = s_fmt(f);
@@ -287,6 +303,28 @@ mod tests {
assert_eq!(settings(&f).jpeg_quality, Some(85));
}
#[test]
fn switching_export_formats_uses_independent_quality_preferences() {
let prefs = photocraft_engine::prefs::Export { jpeg_quality: 43, webp_quality: 72, webp_lossless: false, ..Default::default() };
let mut fields = Map::new();
set_format_defaults(&mut fields, "webp", &prefs);
assert_eq!(fields["quality"], 72);
assert_eq!(fields["lossless"], false);
let s = settings(&fields);
assert!(!s.webp_lossless);
assert_eq!(s.webp_quality, Some(72));
assert_eq!(s.jpeg_quality, None);
set_format_defaults(&mut fields, "jpg", &prefs);
assert_eq!(fields["quality"], 43);
assert_eq!(settings(&fields).jpeg_quality, Some(43));
assert_eq!(settings(&fields).webp_quality, None);
set_format_defaults(&mut fields, "webp", &photocraft_engine::prefs::Export::default());
assert!(settings(&fields).webp_lossless, "default WebP Quick Export mode is lossless");
assert_eq!(settings(&fields).webp_quality, None);
}
#[test]
fn webp_settings_follow_the_lossless_switch() {
let mut f = Map::new();
+2
View File
@@ -107,6 +107,7 @@
Fill… Vyplnit…
Stroke… Tah…
Content-Aware Fill… Výplň s ohledem na obsah…
Delete and Fill Selection Odstranit a vyplnit výběr
Content-Aware Scale Změna velikosti s ohledem na obsah
Puppet Warp Loutková deformace
Perspective Warp Perspektivní deformace
@@ -2139,3 +2140,4 @@ cameraRaw Color Barvy
Indigo Indigová
Fuchsia Fuchsiová
Violet Fialová
Apply At Canvas Bounds Použít efekt na hranicích plátna
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -103,6 +103,7 @@
Fill… Füllen…
Stroke… Nachziehen…
Content-Aware Fill… Inhaltsbasiert füllen…
Delete and Fill Selection Auswahl löschen und füllen
Content-Aware Scale Inhaltsbasiert skalieren
Puppet Warp Marionetten-Verkrümmung
Perspective Warp Perspektivisch verkrümmen
@@ -2179,3 +2180,4 @@ layerLabel No Color Keine Farbe
Indigo Indigo
Fuchsia Fuchsia
Violet Violett
Apply At Canvas Bounds Effekt an Arbeitsflächenbegrenzungen anwenden
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -99,6 +99,7 @@
Fill… Rellenar…
Stroke… Contornear…
Content-Aware Fill… Relleno de contenido…
Delete and Fill Selection Eliminar y rellenar selección
Content-Aware Scale Escalado de contenido
Puppet Warp Deformación de clavos
Perspective Warp Deformación en perspectiva
@@ -2210,3 +2211,4 @@ cameraRaw Amount Cantidad
Indigo Índigo
Fuchsia Fucsia
Violet Violeta
Apply At Canvas Bounds Aplicar efecto en los límites del lienzo
Can't render this file because it contains an unexpected character in line 4 and column 47.
+2
View File
@@ -105,6 +105,7 @@
Fill… Remplir…
Stroke… Contourner…
Content-Aware Fill… Remplissage d'après le contenu…
Delete and Fill Selection Supprimer et remplir la sélection
Content-Aware Scale Mise à l'échelle d'après le contenu
Puppet Warp Déformation par épingles
Perspective Warp Déformation de la perspective
@@ -2570,3 +2571,4 @@ cameraRaw Blending Fusion
Indigo Indigo
Fuchsia Fuchsia
Violet Violet
Apply At Canvas Bounds Appliquer l’effet aux limites de la zone de travail
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -98,6 +98,7 @@
Fill… Isi…
Stroke… Stroke…
Content-Aware Fill… Isi Content-Aware…
Delete and Fill Selection Hapus dan Isi Seleksi
Content-Aware Scale Skala Content-Aware
Puppet Warp Puppet Warp
Perspective Warp Perspective Warp
@@ -2557,3 +2558,4 @@ cameraRaw Blending Pembauran
Indigo Nila
Fuchsia Fuksia
Violet Ungu
Apply At Canvas Bounds Terapkan efek di batas kanvas
Can't render this file because it contains an unexpected character in line 4 and column 47.
+2
View File
@@ -99,6 +99,7 @@
Fill… Riempi…
Stroke… Traccia…
Content-Aware Fill… Riempimento in base al contenuto…
Delete and Fill Selection Elimina e riempi selezione
Content-Aware Scale Scala in base al contenuto
Puppet Warp Altera marionetta
Perspective Warp Altera prospettiva
@@ -2212,3 +2213,4 @@ cameraRaw Amount Quantità
Indigo Indaco
Fuchsia Fucsia
Violet Viola
Apply At Canvas Bounds Applica effetto ai limiti dell’area di lavoro
1 # Italian (it) catalog. Columns, separated by a TAB: context <TAB> source <TAB> translation
99
100
101
102
103
104
105
2213
2214
2215
2216
+2
View File
@@ -103,6 +103,7 @@
Fill… 塗りつぶし…
Stroke… 境界線を描く…
Content-Aware Fill… コンテンツに応じた塗りつぶし…
Delete and Fill Selection 選択範囲を削除して塗りつぶし
Content-Aware Scale コンテンツに応じた拡大・縮小
Puppet Warp パペットワープ
Perspective Warp 遠近法ワープ
@@ -2122,3 +2123,4 @@ cameraRaw Color カラー
Indigo インディゴ
Fuchsia フクシア
Violet 紫
Apply At Canvas Bounds カンバスの境界に効果を適用
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -95,6 +95,7 @@
Fill… 채우기…
Stroke… 획…
Content-Aware Fill… 내용 인식 채우기…
Delete and Fill Selection 선택 영역 삭제 및 채우기
Content-Aware Scale 내용 인식 비율
Puppet Warp 퍼펫 뒤틀기
Perspective Warp 원근 뒤틀기
@@ -2722,3 +2723,4 @@ cameraRaw Color 색상
Seafoam 바다 거품색
Indigo 남색
Fuchsia 자홍색
Apply At Canvas Bounds 캔버스 경계에 효과 적용
1 # Korean (ko) catalog. UTF-8: context<TAB>English source<TAB>translation.
95
96
97
98
99
100
101
2723
2724
2725
2726
+5 -3
View File
@@ -102,6 +102,7 @@
Fill… Preencher…
Stroke… Traçado…
Content-Aware Fill… Preenchimento sensível ao conteúdo…
Delete and Fill Selection Excluir e preencher seleção
Content-Aware Scale Escala sensível ao conteúdo
Puppet Warp Distorção de marionete
Perspective Warp Distorção de perspectiva
@@ -467,7 +468,7 @@
Filter Gallery… Galeria de filtros…
Adaptive Wide Angle… Grande angular adaptável…
Camera Raw Filter… Filtro Camera Raw…
Liquify… Dissolver…
Liquify… Liquefazer…
Vanishing Point… Ponto de fuga…
Blur Desfoque
Blur Gallery Galeria de desfoque
@@ -526,7 +527,7 @@
Unsharp Mask… Máscara de nitidez…
High Pass… Passa-alta…
Stylize Estilização
Diffuse… Difusão…
Diffuse… Difundir…
Emboss… Entalhe…
Extrude… Extrusão…
Find Edges Indicação de arestas
@@ -1099,7 +1100,7 @@
Linear Gradient Degradê linear
Link layers Vincular camadas
Link width and height Vincular largura e altura
Liquify is not open Dissolver não está aberto
Liquify is not open Liquefazer não está aberto
Load Carregar
Load 3D LUT… Carregar LUT 3D…
Load Photoshop brushes (.abr) Carregar pincéis do Photoshop (.abr)
@@ -2577,3 +2578,4 @@ cameraRaw Whites Brancos
Indigo Índigo
Fuchsia Fúcsia
Violet Violeta
Apply At Canvas Bounds Aplicar efeito nos limites da tela
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -82,6 +82,7 @@
Fill… Выполнить заливку…
Stroke… Обвести…
Content-Aware Fill… Заливка с учётом содержимого…
Delete and Fill Selection Удалить и заполнить выделение
Define Brush Preset… Определить кисть…
Define Pattern… Определить паттерн…
Define Custom Shape… Определить свою фигуру…
@@ -2413,3 +2414,4 @@ cameraRaw Roughness Неровность
Indigo Индиго
Fuchsia Фуксия
Violet Фиолетовый
Apply At Canvas Bounds Применить эффект на границах холста
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -99,6 +99,7 @@
Fill… 填充…
Stroke… 描边…
Content-Aware Fill… 内容识别填充…
Delete and Fill Selection 删除并填充选区
Content-Aware Scale 内容识别缩放
Puppet Warp 操控变形
Perspective Warp 透视变形
@@ -2147,3 +2148,4 @@ cameraRaw Blending 混合
Indigo 靛蓝色
Fuchsia 紫红色
Violet 紫罗兰色
Apply At Canvas Bounds 应用画布边界的效果
1 # Simplified Chinese (zh-hans) catalog. UTF-8, TAB-separated columns:
99
100
101
102
103
104
105
2148
2149
2150
2151
+2
View File
@@ -107,6 +107,7 @@
Fill… 填滿…
Stroke… 筆畫…
Content-Aware Fill… 內容感知填滿…
Delete and Fill Selection 刪除並填滿選取範圍
Content-Aware Scale 內容感知縮放
Puppet Warp 操控彎曲
Perspective Warp 透視彎曲
@@ -2116,3 +2117,4 @@ cameraRaw Blending 混合
Indigo 靛藍色
Fuchsia 紫紅色
Violet 紫羅蘭色
Apply At Canvas Bounds 套用效果至版面邊界
Can't render this file because it contains an unexpected character in line 6 and column 47.
+23
View File
@@ -20,6 +20,29 @@ pub fn active(app: &PhotocraftApp) -> bool {
app.drag.as_ref().is_some_and(|d| d.tool == Tool::Lasso && d.lasso.is_some())
}
/// Between polygonal clicks, Backspace/right-click retracts the last fixed vertex.
/// Do not affect a freehand stroke whose primary button is still held.
pub fn waiting_for_vertex(app: &PhotocraftApp) -> bool {
app.ui.tool == Tool::Lasso
&& app
.drag
.as_ref()
.is_some_and(|d| d.tool == Tool::Lasso && d.lasso.as_ref().is_some_and(|l| !l.down && l.document == app.session.active().map(|st| st.doc.id)))
}
pub fn undo_last_vertex(app: &mut PhotocraftApp) -> bool {
cancel_stale(app);
if !waiting_for_vertex(app) {
return false;
}
if app.drag.as_ref().is_some_and(|d| d.points.len() <= 1) {
app.drag = None;
} else if let Some(d) = app.drag.as_mut() {
d.points.pop();
}
true
}
/// A lasso drag that moves the selection (started inside it, `canvas::selection_drag_kind`):
/// the canvas's own selection-move path handles it, this module only feeds it the events.
fn moving_selection(app: &PhotocraftApp) -> bool {
+51
View File
@@ -199,3 +199,54 @@ fn a_drag_inside_the_selection_moves_it() {
assert!(h.state().drag.is_none());
assert_eq!(bounds(h.state()), Some(photocraft_geom::Rect::new(110, 105, 160, 145)));
}
#[test]
fn retracting_polygonal_vertices_keeps_the_document_unchanged() {
let mut app = app();
begin(&mut app, Modifiers::NONE);
event(&mut app, "up", 120.0, 50.0, Modifiers::ALT);
assert!(waiting_for_vertex(&app));
let layer = app.session.active().unwrap().active_layer.unwrap();
assert_eq!(app.drag.as_ref().unwrap().points.len(), 3);
assert!(undo_last_vertex(&mut app));
assert_eq!(app.drag.as_ref().unwrap().points.len(), 2);
assert!(undo_last_vertex(&mut app));
assert_eq!(app.drag.as_ref().unwrap().points.len(), 1);
assert!(undo_last_vertex(&mut app));
assert!(!active(&app));
assert!(!undo_last_vertex(&mut app));
let st = app.session.active().unwrap();
assert!(st.doc.layer(layer).is_some());
assert!(st.doc.selection.is_none());
}
#[test]
fn real_canvas_backspace_and_right_click_retract_polygonal_points() {
let mut h = harness();
mouse(&mut h, "down", 50.0, 50.0, Modifiers::NONE);
mouse(&mut h, "move", 120.0, 50.0, Modifiers::NONE);
mouse(&mut h, "up", 120.0, 50.0, Modifiers::ALT);
mouse(&mut h, "down", 180.0, 100.0, Modifiers::ALT);
mouse(&mut h, "up", 180.0, 100.0, Modifiers::ALT);
assert_eq!(h.state().drag.as_ref().unwrap().points.len(), 3);
let layer = h.state().session.active().unwrap().active_layer.unwrap();
h.event(Event::Key { key: egui::Key::Backspace, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::ALT });
h.run_steps(2);
assert_eq!(h.state().drag.as_ref().unwrap().points.len(), 2);
assert!(h.state().session.active().unwrap().doc.layer(layer).is_some());
let state = h.state();
let view = &state.ui.views[0];
let xf = ViewXform { rect: crate::rulers::content_rect(state, state.last_canvas_rect), zoom: view.zoom, center: view.center, flip: false };
let pos = xf.to_screen(155.0, 100.0);
h.event(Event::PointerMoved(pos));
h.event(Event::PointerButton { pos, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::ALT });
h.run_steps(1);
h.event(Event::PointerButton { pos, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::ALT });
h.run_steps(2);
assert_eq!(h.state().drag.as_ref().unwrap().points.len(), 1);
assert!(h.state().ui.canvas_tool_menu.is_none());
assert!(h.state().session.active().unwrap().doc.layer(layer).is_some());
assert!(h.state().session.active().unwrap().doc.selection.is_none());
}
+16
View File
@@ -21,6 +21,7 @@ pub mod adjust_preview;
pub mod adjust_ui;
pub mod analysis_ui;
pub mod artboard_ui;
pub(crate) mod blend_preview;
mod brand;
pub mod brush_panel;
pub mod brush_picker;
@@ -311,6 +312,8 @@ pub struct PhotocraftApp {
trail: Option<stroke_trail::Trail>,
/// Move tool drag shown live (`move_ui`).
pub(crate) move_preview: Option<move_ui::MovePreview>,
/// A blend mode hovered in the Layers panel, shown live (`blend_preview`).
pub(crate) blend_preview: Option<blend_preview::BlendPreview>,
/// Patch Tool drag: the healed document at the pointer (`patch_preview`).
pub(crate) patch_preview: Option<patch_preview::PatchPreview>,
/// The pixels a Magnetic Lasso border follows (`magnetic_lasso_ui`).
@@ -469,6 +472,7 @@ impl PhotocraftApp {
live_stroke: None,
trail: None,
move_preview: None,
blend_preview: None,
patch_preview: None,
magnetic: Default::default(),
secondary_erase: false,
@@ -1426,6 +1430,18 @@ impl PhotocraftApp {
}
}
/// File › New's fields: the defaults, plus the Clipboard preset (the clipboard image's size,
/// selected) when the clipboard holds an image. Opening the dialog is an explicit request, so
/// the OS clipboard is read here, as for a paste.
pub(crate) fn new_document_fields(&mut self) -> serde_json::Map<String, serde_json::Value> {
let mut f = crate::state::UiState::new_document_fields();
self.import_os_clipboard();
if let Some(c) = self.session.clipboard.as_ref().filter(|c| !c.bounds.is_empty()) {
crate::new_doc_ui::set_clipboard(&mut f, c.bounds.width(), c.bounds.height());
}
f
}
/// If the OS clipboard holds an image that isn't the one we put there, make it the session
/// clipboard (so ⌘V pastes screenshots and images copied in other apps, like Photoshop).
/// Returns true when a new external image was imported.
+58 -6
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::state::{DialogKind, UiState};
use crate::state::DialogKind;
/// Top-level menus in Photoshop order.
pub const TOP_MENUS: [&str; 10] = ["File", "Edit", "Image", "Layer", "Type", "Select", "Filter", "View", "Window", "Help"];
@@ -215,7 +215,8 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
Ok(Value::Null)
}
"file.new" if params.as_object().is_none_or(|o| o.is_empty()) => {
let d = app.ui.open_dialog(DialogKind::NewDocument, UiState::new_document_fields());
let fields = app.new_document_fields();
let d = app.ui.open_dialog(DialogKind::NewDocument, fields);
Ok(json!({"dialog": d}))
}
"file.open" => {
@@ -614,6 +615,17 @@ fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
})
}
/// Translate the fixed command label and substitute the currently configured export format.
/// Reuse the existing translated PNG sentence, so dynamic formats work in every UI language.
fn translated_menu_label(lang: crate::i18n::Lang, item: &MenuItem) -> String {
if item.id == "file.export.quickExportAsPng"
&& let Some(fmt) = item.label.strip_prefix("Quick Export as ")
{
return crate::i18n::tr_id(lang, &item.id, "Quick Export as PNG").replace("PNG", fmt);
}
crate::i18n::tr_id(lang, &item.id, &item.label).to_string()
}
/// Menu tree entry for rendering and for `ui.inspect`.
#[derive(Clone, Debug, serde::Serialize)]
pub struct MenuItem {
@@ -701,6 +713,23 @@ pub fn menu_items(app: &PhotocraftApp) -> Vec<MenuItem> {
}
}
crate::plugin_ui::insert_menu_items(app, &mut items);
// The File quick-export command uses the format selected in Export Preferences.
// On the web it intentionally downloads PNG until the quick-export service supports
// the other formats; the Layer quick-export command also always produces PNG.
if let Some(item) = items.iter_mut().find(|i| i.id == "file.export.quickExportAsPng") {
use photocraft_engine::prefs::QuickExportFormat;
let format = if cfg!(target_arch = "wasm32") {
"PNG"
} else {
match app.session.prefs().export.quick_export_format {
QuickExportFormat::Png => "PNG",
QuickExportFormat::Jpg => "JPG",
QuickExportFormat::Gif => "GIF",
QuickExportFormat::Webp => "WebP",
}
};
item.label = format!("Quick Export as {format}");
}
// File › Open Recent: a dynamic submenu of recently opened files (inserted after "Open As…").
if let Some(after) = items.iter().position(|i| i.id == "file.openAs") {
let rp: Vec<String> = vec!["File".into(), "Open Recent".into()];
@@ -938,7 +967,7 @@ pub fn search_items<'a>(items: &'a [MenuItem], query: &str, lang: crate::i18n::L
let rank = |it: &MenuItem| {
let english = search_rank(&q, &it.label, &it.path);
let path: Vec<String> = it.path.iter().map(|p| crate::i18n::tr(lang, p).to_string()).collect();
let local = search_rank(&q, crate::i18n::tr_id(lang, &it.id, &it.label), &path);
let local = search_rank(&q, &translated_menu_label(lang, it), &path);
english.into_iter().chain(local).min()
};
let mut hits: Vec<(u8, usize, &MenuItem)> =
@@ -978,8 +1007,8 @@ fn help_search(ui: &mut egui::Ui, items: &[MenuItem], clicked: &mut Option<Strin
ui.weak(crate::i18n::tr(lang, "No matching commands"));
}
for it in results {
let mut trail: Vec<&str> = it.path.iter().map(|p| crate::i18n::tr(lang, p)).collect();
trail.push(crate::i18n::tr_id(lang, &it.id, &it.label));
let mut trail: Vec<String> = it.path.iter().map(|p| crate::i18n::tr(lang, p).to_string()).collect();
trail.push(translated_menu_label(lang, it));
let mut b = egui::Button::new(trail.join(" › "));
if let Some(sc) = &it.shortcut {
b = b.shortcut_text(crate::shortcuts::pretty(sc));
@@ -1038,7 +1067,7 @@ fn render_level_rows(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, click
}
continue;
}
let mut text = crate::i18n::tr_id(lang, &it.id, &it.label).to_string();
let mut text = translated_menu_label(lang, it);
if let Some(c) = it.checked {
text = format!("{} {}", if c { "✔" } else { " " }, text);
}
@@ -1461,3 +1490,26 @@ mod open_recent_tests {
let _ = std::fs::remove_file(&path);
}
}
#[cfg(test)]
mod quick_export_label_tests {
use super::*;
#[test]
fn file_quick_export_menu_reflects_selected_format_without_renaming_layer_export() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
for (value, expected) in [("png", "PNG"), ("jpg", "JPG"), ("gif", "GIF"), ("webp", "WebP")] {
app.run("prefs.set", json!({"values": {"export.quickExportFormat": value}})).unwrap();
let items = menu_items(&app);
let quick: Vec<_> = items.iter().filter(|i| i.id == "file.export.quickExportAsPng").collect();
assert_eq!(quick.len(), 1, "the catalogue and UI command must not create duplicate items");
let shown_format = if cfg!(target_arch = "wasm32") { "PNG" } else { expected };
assert_eq!(quick[0].label, format!("Quick Export as {shown_format}"));
let id = crate::i18n::Lang::from_code("id").unwrap();
let localized = translated_menu_label(id, quick[0]);
assert_eq!(localized, format!("Ekspor Cepat ke {shown_format}"));
let layer = items.iter().find(|i| i.id == "layer.quickExportAsPng").unwrap();
assert_eq!(layer.label, "Quick Export as PNG", "layer export always creates PNG");
}
}
}
@@ -125,3 +125,29 @@ fn shift_click_adds_the_layer_under_the_pointer() {
assert!(st.is_layer_selected(a) && st.is_layer_selected(b));
assert_eq!(bounds(&app, a), Rect::new(8, 8, 24, 24));
}
#[test]
fn every_theme_shows_the_auto_select_toggle() {
// #1275: the Studio themes' options bar had only a hint for the Move tool, so Auto-Select
// could not be turned off there.
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
for theme in [crate::theme::ThemeKind::ProMedium, crate::theme::ThemeKind::Studio] {
let (app, _, _) = app();
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 60.0)).build_ui_state(
|ui, app: &mut PhotocraftApp| {
if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
crate::panels::options_bar(app, ui);
},
app,
);
PhotocraftApp::setup_context(&h.ctx, theme);
h.run_steps(4);
assert!(h.state().ui.tool_options.move_auto_select);
h.get_by_label("Auto-Select:").click();
h.run_steps(2);
assert!(!h.state().ui.tool_options.move_auto_select, "{theme:?}: the toggle turns Auto-Select off");
}
}
+59
View File
@@ -101,6 +101,26 @@ pub fn px_value(px: f32) -> Value {
json!(if px.is_finite() { px.round().clamp(1.0, 300_000.0) as u32 } else { 1 })
}
/// Name of the preset that takes the clipboard image's size.
pub const CLIPBOARD: &str = "Clipboard";
/// Offer the Clipboard preset (`w` × `h` px, at 72 ppi) first under the Recent presets, and
/// select it.
pub fn set_clipboard(f: &mut Map<String, Value>, w: u32, h: u32) {
if w == 0 || h == 0 {
return;
}
f.insert("__clipboard".into(), json!([w, h]));
apply_preset(f, &(CLIPBOARD, w, h, 72.0));
}
/// The clipboard image's size, when the dialog offers the Clipboard preset.
fn clipboard_preset(f: &Map<String, Value>) -> Option<Preset> {
let size = f.get("__clipboard")?.as_array()?;
let dim = |i: usize| size.get(i)?.as_u64().and_then(|v| u32::try_from(v).ok()).filter(|v| *v > 0);
Some((CLIPBOARD, dim(0)?, dim(1)?, 72.0))
}
/// Apply a preset to the dialog fields.
pub fn apply_preset(f: &mut Map<String, Value>, p: &Preset) {
f.insert("width".into(), json!(p.1));
@@ -173,6 +193,8 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
widgets::hairline(ui);
ui.add_space(8.0);
let presets = CATEGORIES.iter().find(|c| c.0 == cat).map_or(CATEGORIES[0].1, |c| c.1);
// The clipboard image's size comes first among the Recent presets.
let presets: Vec<Preset> = clipboard_preset(f).filter(|_| cat == CATEGORIES[0].0).into_iter().chain(presets.iter().copied()).collect();
let chosen = get_s(f, "__preset", "");
ui.horizontal_top(|ui| {
// Left: preset grid.
@@ -360,6 +382,25 @@ mod tests {
}
}
#[test]
fn clipboard_preset_comes_first_and_is_selected() {
// Nothing on the clipboard: the dialog opens as before.
let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
let f = app.new_document_fields();
assert_eq!(f, crate::state::UiState::new_document_fields());
assert!(clipboard_preset(&f).is_none());
// Pixels copied in the app: the Clipboard preset takes their size, at 72 ppi, selected.
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
app.run("select.rect", json!({"x": 10, "y": 20, "width": 123, "height": 45})).unwrap();
app.run("edit.copy", json!({})).unwrap();
let f = app.new_document_fields();
assert_eq!(clipboard_preset(&f), Some((CLIPBOARD, 123, 45, 72.0)));
assert_eq!((f["width"].as_u64(), f["height"].as_u64(), f["__preset"].as_str()), (Some(123), Some(45), Some(CLIPBOARD)));
let p = command_params(&f);
assert!(p.get("__clipboard").is_none(), "file.new never sees the dialog's keys");
assert_eq!((p["width"].as_u64(), p["height"].as_u64(), p["resolution"].as_f64()), (Some(123), Some(45), Some(72.0)));
}
#[test]
fn preset_sets_size_resolution_and_create_params_drop_ui_keys() {
let mut f = crate::state::UiState::new_document_fields();
@@ -472,6 +513,24 @@ mod tests {
assert_eq!(created(&h), (512, 512, 72.0));
}
#[test]
fn the_clipboard_card_is_first_and_creates_the_clipboard_size() {
let mut h = harness();
let mut f = fields(&h);
super::super::set_clipboard(&mut f, 640, 360);
set_fields(&mut h, f);
// Recent lists the Clipboard card first: three presets instead of two.
assert!(h.query_by_label_contains("BLANK DOCUMENT PRESETS (3)").is_some());
let heading = h.get_by_label_contains("BLANK DOCUMENT PRESETS").rect();
// Pick the second card, then the first (Clipboard) again.
click_at(&mut h, heading.left_bottom() + egui::vec2(80.0 + 172.0, 60.0));
assert_eq!(fields(&h).get("__preset").and_then(|v| v.as_str()), Some("Default Photoshop Size"));
click_at(&mut h, heading.left_bottom() + egui::vec2(80.0, 60.0));
assert_eq!(fields(&h).get("__preset").and_then(|v| v.as_str()), Some(super::super::CLIPBOARD));
enter(&mut h);
assert_eq!(created(&h), (640, 360, 72.0));
}
#[test]
fn clicking_a_preset_card_after_typing_sets_its_size() {
let mut h = harness();
+9 -2
View File
@@ -841,7 +841,11 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
crate::shortcuts::pretty("Shift+Alt")
),
),
Tool::Move => hint(ui, tl!("Drag to move the active layer")),
Tool::Move => {
// The Studio themes keep Photoshop's Auto-Select toggle too (#1275).
widgets::checkbox(ui, &mut app.ui.tool_options.move_auto_select, tl!("Auto-Select:"));
hint(ui, tl!("Drag to move the active layer"));
}
Tool::Eyedropper => hint(
ui,
&crate::i18n::fmt(
@@ -1415,9 +1419,12 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let opacity_label = if t.pro { tl!("Opacity:") } else { tl!("Opacity") };
let right = (body_text_width(ui, opacity_label) + 66.0 + 2.0 * ui.spacing().item_spacing.x + 16.0).max(150.0);
let w = ui.available_width() - right;
if widgets::dropdown(ui, "blend", &mut m, &blend_options(l.is_group()), w.max(100.0)) {
let (chosen, hovered) = widgets::dropdown_hovered(ui, "blend", &mut m, &blend_options(l.is_group()), w.max(100.0));
if chosen {
actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "blend": m.label()})));
}
// Hovering a mode previews it on the canvas (#970).
crate::blend_preview::hover(app, l.id, hovered.filter(|_| !chosen));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let mut o = l.opacity * 100.0;
if widgets::value_field(ui, &mut o, 0.0..=100.0, "%", 66.0).changed() {
+45 -1
View File
@@ -756,6 +756,13 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
}
fn humanize(key: &str) -> String {
// These controls appear only for WebP, so reuse the existing translated labels.
if key == "webpLossless" {
return "Lossless".into();
}
if key == "webpQuality" {
return "Quality".into();
}
let mut s = String::new();
for (i, ch) in key.chars().enumerate() {
if i == 0 {
@@ -940,6 +947,17 @@ fn has_visible_fields(values: &Value, section: &str) -> bool {
values.get(section).and_then(Value::as_object).is_some_and(|o| o.keys().any(|k| !prefs::is_hidden(&format!("{section}.{k}"))))
}
/// JPEG and WebP have independent settings; unrelated format controls stay out of view.
fn export_field_visible(obj: &Map<String, Value>, key: &str) -> bool {
let format = obj.get("quickExportFormat").and_then(Value::as_str).unwrap_or("png");
match key {
"jpegQuality" => format == "jpg",
"webpLossless" => format == "webp",
"webpQuality" => format == "webp" && obj.get("webpLossless").and_then(Value::as_bool) != Some(true),
_ => true,
}
}
/// Generic editor for a section's fields: checkboxes, dropdowns for choices, colour swatches,
/// number fields with the preference's range, text fields.
fn section_fields(ui: &mut egui::Ui, section: &str, obj: &mut Map<String, Value>, order: &[String], lang: crate::i18n::Lang) {
@@ -954,7 +972,10 @@ fn section_fields(ui: &mut egui::Ui, section: &str, obj: &mut Map<String, Value>
let path = format!("{section}.{k}");
// Settings nothing reads yet stay out of the dialog (issue #204); their stored values
// pass through untouched.
if prefs::is_hidden(&path) || (section == "performance" && matches!(k.as_str(), "useGpu" | "gpuBackend" | "renderingMode")) {
if prefs::is_hidden(&path)
|| (section == "performance" && matches!(k.as_str(), "useGpu" | "gpuBackend" | "renderingMode"))
|| (section == "export" && !export_field_visible(obj, &k))
{
continue;
}
let v = obj.get(&k).cloned().unwrap_or(Value::Null);
@@ -1431,6 +1452,29 @@ mod tests {
assert_eq!(*h.state(), [0x80, 0x80, 0x80]);
}
#[test]
fn quick_export_controls_match_selected_format() {
let mut obj = serde_json::to_value(photocraft_engine::prefs::Export::default()).unwrap().as_object().unwrap().clone();
assert!(!export_field_visible(&obj, "jpegQuality"));
assert!(!export_field_visible(&obj, "webpLossless"));
assert!(!export_field_visible(&obj, "webpQuality"));
obj.insert("quickExportFormat".into(), json!("jpg"));
assert!(export_field_visible(&obj, "jpegQuality"));
assert!(!export_field_visible(&obj, "webpLossless"));
assert!(!export_field_visible(&obj, "webpQuality"));
obj.insert("quickExportFormat".into(), json!("webp"));
assert!(!export_field_visible(&obj, "jpegQuality"));
assert!(export_field_visible(&obj, "webpLossless"));
assert!(!export_field_visible(&obj, "webpQuality"), "lossless WebP does not have a quality setting");
obj.insert("webpLossless".into(), json!(false));
assert!(export_field_visible(&obj, "webpQuality"));
assert_eq!(humanize("webpLossless"), "Lossless");
assert_eq!(humanize("webpQuality"), "Quality");
}
#[test]
fn rendering_mode_display_respects_explicit_mode_and_legacy_disable() {
let legacy = serde_json::json!({"useGpu": false, "gpuBackend": "auto"});
+42 -1
View File
@@ -124,7 +124,9 @@ pub fn draw_guides(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform,
/// Existing guide under a document point (within 4 screen px).
pub fn guide_at(app: &PhotocraftApp, x: f64, y: f64) -> Option<(bool, usize)> {
if !app.ui.extras.guides || app.ui.extras.lock_guides {
// Hidden canvas guides are not interactive: the Move tool must reach the layer below.
// Keep hit testing consistent with the visibility gate in canvas::draw.
if !app.ui.extras.guides || !app.ui.view.shows(app.ui.view.show.canvas_guides) || app.ui.extras.lock_guides {
return None;
}
let doc = &app.session.active()?.doc;
@@ -269,6 +271,45 @@ mod tests {
assert_eq!(tick_step(0.25), 500.0);
}
#[test]
fn hidden_guides_are_not_hit_tested() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap();
app.sync_views();
app.session.execute("view.newGuide", json!({"orientation": "vertical", "position": 50})).unwrap();
app.session.execute("view.newGuide", json!({"orientation": "horizontal", "position": 25})).unwrap();
let positions = app.session.active().unwrap().doc.guides.clone();
// Visible, unlocked guides remain interactive in either orientation.
assert_eq!(guide_at(&app, 50.0, 10.0), Some((true, 0)));
assert_eq!(guide_at(&app, 10.0, 25.0), Some((false, 0)));
// All ways to hide the canvas guides must also disable hit testing.
app.ui.extras.guides = false;
assert_eq!(guide_at(&app, 50.0, 10.0), None);
assert_eq!(guide_at(&app, 10.0, 25.0), None);
app.ui.extras.guides = true;
app.ui.view.show.canvas_guides = false;
assert_eq!(guide_at(&app, 50.0, 10.0), None);
assert_eq!(guide_at(&app, 10.0, 25.0), None);
app.ui.view.show.canvas_guides = true;
app.ui.view.extras = false;
assert_eq!(guide_at(&app, 50.0, 10.0), None);
assert_eq!(guide_at(&app, 10.0, 25.0), None);
app.ui.view.extras = true;
// Hiding/showing must not change the stored guide positions.
assert_eq!(app.session.active().unwrap().doc.guides, positions);
assert_eq!(guide_at(&app, 50.0, 10.0), Some((true, 0)));
assert_eq!(guide_at(&app, 10.0, 25.0), Some((false, 0)));
app.ui.extras.lock_guides = true;
assert_eq!(guide_at(&app, 50.0, 10.0), None);
assert_eq!(guide_at(&app, 10.0, 25.0), None);
}
#[test]
fn guide_drags_create_move_and_delete() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+9
View File
@@ -296,6 +296,15 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
if crate::magnetic_lasso_ui::keys(app, ctx) {
return;
}
// While placing polygonal lasso vertices, Backspace/Delete retracts the last point;
// it must win over the regular Edit › Clear shortcut, which edits document pixels.
if crate::lasso_ui::waiting_for_vertex(app) {
let mods = ctx.input(|i| i.modifiers);
if !mods.command && !mods.ctrl && !mods.shift && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)) {
crate::lasso_ui::undo_last_vertex(app);
return;
}
}
// Inline type editing eats text and navigation keys; ⌘-shortcuts still reach the menus.
let editing = crate::type_tool::handle_keys(app, ctx);
// Registry, UI and menu-catalogue shortcuts (see [`crate::shortcut_dispatch::bindings`]).
+150 -9
View File
@@ -725,6 +725,40 @@ fn distort_allows(mode: TransformMode, h: Hit) -> bool {
mode != TransformMode::Distort || !matches!(h, Hit::Outside | Hit::Edge(_))
}
/// The turn at each corner of a quad (cross products of consecutive edges): all the same sign
/// for a convex quad, mixed for a concave or self-intersecting one.
fn turns(q: &[[f64; 2]; 4]) -> [f64; 4] {
std::array::from_fn(|k| {
let (a, b, c) = (q[k], q[(k + 1) % 4], q[(k + 2) % 4]);
(b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
})
}
/// Is `q` convex with the orientation `sign`, every corner turning by more than a sliver?
fn convex(q: &[[f64; 2]; 4], sign: f64, min_turn: f64) -> bool {
turns(q).iter().all(|t| t * sign > min_turn)
}
/// Distort and Perspective stop a corner where the box would turn concave or fold over itself,
/// as Photoshop does (#1323): the result moves from `from` towards `to` as far as the quad stays
/// convex. A box that is not convex to begin with is left free.
fn keep_convex(from: [[f64; 2]; 4], to: [[f64; 2]; 4]) -> [[f64; 2]; 4] {
let t0 = turns(&from);
let sign = t0[0].signum();
// A sliver: a thousandth of the starting box's smallest turn, so the stop is short of flat.
let min_turn = t0.iter().map(|t| t.abs()).fold(f64::INFINITY, f64::min) * 1e-3;
if !(min_turn.is_finite() && min_turn > 0.0) || !convex(&from, sign, 0.0) || convex(&to, sign, min_turn) {
return to;
}
let lerp = |t: f64| -> [[f64; 2]; 4] { std::array::from_fn(|k| [from[k][0] + (to[k][0] - from[k][0]) * t, from[k][1] + (to[k][1] - from[k][1]) * t]) };
let (mut lo, mut hi) = (0.0f64, 1.0f64);
for _ in 0..40 {
let mid = (lo + hi) / 2.0;
if convex(&lerp(mid), sign, min_turn) { lo = mid } else { hi = mid }
}
lerp(lo)
}
fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods: egui::Modifiers) {
let (dx, dy) = (p[0] - g.start[0], p[1] - g.start[1]);
match g.hit {
@@ -776,13 +810,16 @@ fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods: egui::Mod
_ => 1,
};
let (mx, my) = if horizontal { (dx, 0.0) } else { (0.0, dy) };
s.quad[i] = [g.quad0[i][0] + mx, g.quad0[i][1] + my];
s.quad[j] = [g.quad0[j][0] - mx, g.quad0[j][1] - my];
let mut q = g.quad0;
q[i] = [g.quad0[i][0] + mx, g.quad0[i][1] + my];
q[j] = [g.quad0[j][0] - mx, g.quad0[j][1] - my];
s.quad = keep_convex(g.quad0, q);
}
Hit::Corner(i) if mods.command => {
// Distort: move the corner freely.
s.quad = g.quad0;
s.quad[i] = [g.quad0[i][0] + dx, g.quad0[i][1] + dy];
// Distort: move the corner freely, up to where the box would fold over (#1323).
let mut q = g.quad0;
q[i] = [g.quad0[i][0] + dx, g.quad0[i][1] + dy];
s.quad = keep_convex(g.quad0, q);
}
Hit::Edge(i) if mods.command => {
// Skew: the edge's two corners move together (⇧: only along the edge).
@@ -1268,6 +1305,22 @@ fn readout(t: &TransformSession) -> (f64, f64, f64, f64) {
/// Width of the mode, cancel and commit cluster kept on the right of the options bar.
const ACTIONS_W: f32 = 140.0;
/// Reach of the reference point X/Y fields: the largest document side (`image.canvasSize`'s limit).
const POSITION_LIMIT_PX: f32 = 300_000.0;
/// Reach of the W/H fields. The engine takes any scale; this lets a 30 px layer span the largest
/// document (#1267).
const SCALE_LIMIT_PCT: f32 = 1_000_000.0;
/// The W or H field's limit for a box side of `side` px: as far as the result stays within the
/// largest document side, so a typed scale can't ask for an image too large to allocate.
fn scale_limit_pct(side: f64) -> f32 {
let side = side.abs();
if !side.is_finite() || side < 1e-6 {
return SCALE_LIMIT_PCT;
}
((f64::from(POSITION_LIMIT_PX) / side * 100.0) as f32).clamp(100.0, SCALE_LIMIT_PCT)
}
/// Options bar while transforming: reference point X/Y, W/H %, angle, interpolation, and, pinned
/// to the right, the warp switch, cancel and commit.
pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
@@ -1299,9 +1352,9 @@ fn transform_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSes
let mut px = t.pivot[0] as f32;
let mut py = t.pivot[1] as f32;
lbl(ui, "X:");
let rx = crate::widgets::value_field(ui, &mut px, -30000.0..=30000.0, "px", 72.0);
let rx = crate::widgets::value_field(ui, &mut px, -POSITION_LIMIT_PX..=POSITION_LIMIT_PX, "px", 72.0);
lbl(ui, "Y:");
let ry = crate::widgets::value_field(ui, &mut py, -30000.0..=30000.0, "px", 72.0);
let ry = crate::widgets::value_field(ui, &mut py, -POSITION_LIMIT_PX..=POSITION_LIMIT_PX, "px", 72.0);
if (rx.changed() || ry.changed())
&& let Some(s) = app.ui.transform.as_mut()
{
@@ -1311,8 +1364,9 @@ fn transform_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSes
}
crate::widgets::vline(ui, 22.0);
let (mut w, mut h) = (sx as f32, sy as f32);
let (wlim, hlim) = (scale_limit_pct(t.rect[2] - t.rect[0]), scale_limit_pct(t.rect[3] - t.rect[1]));
lbl(ui, "W:");
let rw = crate::widgets::value_field(ui, &mut w, -10000.0..=10000.0, "%", 66.0);
let rw = crate::widgets::value_field(ui, &mut w, -wlim..=wlim, "%", 66.0);
let link_id = egui::Id::new("transform-link");
let mut link: bool = ui.data(|d| d.get_temp(link_id)).unwrap_or(true);
if crate::icons::button(ui, if link { "link" } else { "unlink" }, 22.0, link, tl!("Maintain aspect ratio")).clicked() {
@@ -1320,10 +1374,12 @@ fn transform_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSes
ui.data_mut(|d| d.insert_temp(link_id, link));
}
lbl(ui, "H:");
let rh = crate::widgets::value_field(ui, &mut h, -10000.0..=10000.0, "%", 66.0);
let rh = crate::widgets::value_field(ui, &mut h, -hlim..=hlim, "%", 66.0);
if rw.changed() || rh.changed() {
let (kx, ky) = if link {
let k = if rw.changed() { w as f64 / sx.max(1e-9) } else { h as f64 / sy.max(1e-9) };
// Linked, the other side follows: keep it within its own limit too.
let k = k.min(f64::from(wlim) / sx.abs().max(1e-9)).min(f64::from(hlim) / sy.abs().max(1e-9));
(k, k)
} else {
(w as f64 / sx.max(1e-9), h as f64 / sy.max(1e-9))
@@ -1594,6 +1650,60 @@ mod tests {
assert!(h.state().ui.transform.is_none());
}
/// Types `text` + Enter into the `n`th numeric field of the transform bar (X, Y, W, H, angle…).
fn type_into_bar_field(n: usize, text: &str) -> TransformSession {
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.ui.transform = Some(session());
let mut h = Harness::builder().with_size(vec2(900.0, 48.0)).build_ui_state(
|ui, app: &mut PhotocraftApp| {
if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
ui.horizontal_centered(|ui| options_bar(app, ui));
},
app,
);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio);
h.run_steps(6);
h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(n).unwrap().click();
h.run();
for c in text.chars() {
h.event(egui::Event::Text(c.to_string()));
h.run();
}
h.key_press(egui::Key::Enter);
h.run_steps(2);
h.state().ui.transform.clone().unwrap()
}
/// Large documents need scales past 10000% and positions past 30000 px (#1267).
#[test]
fn transform_fields_reach_large_documents() {
let t = type_into_bar_field(2, "15000");
let (sx, sy, _, _) = readout(&t);
assert!((sx - 15000.0).abs() < 0.5 && (sy - 15000.0).abs() < 0.5, "{sx} {sy}");
assert!((t.quad[1][0] - t.quad[0][0] - 15_000.0).abs() < 1.0, "{:?}", t.quad);
let t = type_into_bar_field(0, "250000");
assert!((t.pivot[0] - 250_000.0).abs() < 1.0, "{:?}", t.pivot);
}
/// A typed scale stops where the box reaches the largest document side, not past what can be
/// allocated: the 100 × 50 px test box tops out at 300000 % wide.
#[test]
fn typed_scales_stay_within_the_largest_document() {
assert_eq!(scale_limit_pct(20.0), SCALE_LIMIT_PCT);
assert_eq!(scale_limit_pct(3000.0), 10_000.0);
assert_eq!(scale_limit_pct(1e9), 100.0);
assert_eq!(scale_limit_pct(0.0), SCALE_LIMIT_PCT);
assert_eq!(scale_limit_pct(f64::NAN), SCALE_LIMIT_PCT);
let t = type_into_bar_field(2, "99999999");
let (sx, sy, _, _) = readout(&t);
let side = t.rect[2] - t.rect[0];
assert!(sx <= f64::from(scale_limit_pct(side)) + 0.5 && sy <= f64::from(scale_limit_pct(t.rect[3] - t.rect[1])) + 0.5, "{sx} {sy}");
}
fn drag(s: &mut TransformSession, from: [f64; 2], to: [f64; 2], mods: egui::Modifiers) {
let g = Gesture { hit: hit(s, from, 8.0), start: from, quad0: s.quad, pivot0: s.pivot };
apply_drag(s, g, to, mods);
@@ -1906,6 +2016,37 @@ mod tests {
assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Free);
}
#[test]
fn a_distort_corner_stops_before_the_box_folds_over() {
// #1323: dragging a corner across the opposite diagonal stops short of it, so the box
// stays convex instead of folding into a bow tie.
let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24));
app.ui.extras.snap = false;
let ctx = egui::Context::default();
crate::menus::invoke(&mut app, &ctx, "edit.transform.distort", json!({})).unwrap();
let q0 = app.ui.transform.as_ref().unwrap().quad;
// Top-left far past the bottom-right corner.
press_drag(&mut app, q0[0], [60.0, 60.0], egui::Modifiers::NONE);
let q = app.ui.transform.as_ref().unwrap().quad;
let sign = turns(&q0)[0].signum();
assert!(turns(&q).iter().all(|t| t * sign > 0.0), "still convex: {q:?}");
assert_eq!([q[1], q[2], q[3]], [q0[1], q0[2], q0[3]], "the other corners stay put");
// It went as far as it could along the drag: up to the TR–BL diagonal (x + y = 32).
assert!(q[0][0] > 15.0 && q[0][0] < 16.0 && (q[0][0] - q[0][1]).abs() < 1e-6, "{q:?}");
// A drag that keeps the box convex is not held back.
press_drag(&mut app, q[0], [2.0, 4.0], egui::Modifiers::NONE);
assert_eq!(app.ui.transform.as_ref().unwrap().quad[0], [2.0, 4.0]);
}
#[test]
fn keep_convex_leaves_a_degenerate_start_alone() {
let flat = [[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]];
let to = [[5.0, 5.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]];
assert_eq!(keep_convex(flat, to), to);
let nan = [[f64::NAN, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
let _ = keep_convex(nan, to);
}
#[test]
fn the_legacy_preference_swaps_corner_proportions() {
let none = egui::Modifiers::NONE;
+9 -1
View File
@@ -94,6 +94,12 @@ pub struct ViewOptions {
/// and the Middle Eastern & South Asian composer.
pub language_features: String,
pub middle_eastern_composer: bool,
/// Parameters from the last successfully applied New Guide Layout dialog.
pub guide_layout: Value,
}
fn default_guide_layout() -> Value {
json!({"columns": 8, "gutter": 20, "rows": 0, "rowGutter": 0, "margin": 0, "centerColumns": false, "clearExisting": false})
}
impl Default for ViewOptions {
@@ -112,6 +118,7 @@ impl Default for ViewOptions {
font_preview_size: "medium".into(),
language_features: "defaultFeatures".into(),
middle_eastern_composer: false,
guide_layout: default_guide_layout(),
}
}
}
@@ -846,7 +853,8 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Val
json!({"from": ["any", "rgb", "grayscale", "cmyk", "lab", "indexed", "bitmap", "duotone", "multichannel"], "to": ["rgb", "grayscale", "cmyk", "lab"]}),
),
"view.newGuideLayout" => {
dialog(app, json!({"columns": 8, "gutter": 20, "rows": 0, "rowGutter": 0, "margin": 0, "centerColumns": false, "clearExisting": false}), json!({}))
let fields = app.ui.view.guide_layout.clone();
dialog(app, fields, json!({}))
}
"type.warpText" => {
let styles: Vec<&str> = std::iter::once("none").chain(photocraft_text::warp::STYLES.iter().map(|(_, s)| *s)).collect();
+40
View File
@@ -172,3 +172,43 @@ fn engine_commands_open_their_dialogs() {
crate::menus::invoke_unguarded(&mut app, &ctx, "file.closeAll", json!({})).unwrap();
assert!(app.ui.views.is_empty() && app.session.documents().is_empty());
}
#[test]
fn new_guide_layout_remembers_successful_values_not_cancelled_edits() {
let (mut app, ctx) = app_with(1);
let first = menu(&mut app, &ctx, "view.newGuideLayout", json!({})).unwrap()["dialog"].as_u64().unwrap();
assert_eq!(app.ui.dialog_mut(first).unwrap().fields["columns"], 8);
assert_eq!(app.ui.dialog_mut(first).unwrap().fields["gutter"], 20);
for (key, value) in [("columns", json!(2)), ("gutter", json!(0)), ("rows", json!(2)), ("rowGutter", json!(0))] {
app.ui.dialog_mut(first).unwrap().fields.insert(key.into(), value);
}
crate::dialogs::confirm(&mut app, first).unwrap();
let second = menu(&mut app, &ctx, "view.newGuideLayout", json!({})).unwrap()["dialog"].as_u64().unwrap();
let fields = &app.ui.dialog_mut(second).unwrap().fields;
assert_eq!(fields["columns"], 2);
assert_eq!(fields["gutter"], 0);
assert_eq!(fields["rows"], 2);
assert_eq!(fields["rowGutter"], 0);
assert_eq!(fields["clearExisting"], false);
// A cancelled edit must not replace the last successfully used values.
app.ui.dialog_mut(second).unwrap().fields.insert("columns".into(), json!(9));
app.ui.close_dialog(second);
let third = menu(&mut app, &ctx, "view.newGuideLayout", json!({})).unwrap()["dialog"].as_u64().unwrap();
assert_eq!(app.ui.dialog_mut(third).unwrap().fields["columns"], 2);
// The remembered state is part of the serializable UI state.
let json_state = serde_json::to_value(&app.ui).unwrap();
assert_eq!(json_state["view"]["guide_layout"]["columns"], 2);
let restored: crate::state::UiState = serde_json::from_value(json_state).unwrap();
assert_eq!(restored.view.guide_layout["rows"], 2);
}
#[test]
fn new_guide_layout_does_not_remember_a_failed_command() {
let (mut app, _) = app_with(0);
let id = front(&mut app, "view.newGuideLayout", &json!({})).unwrap().unwrap()["dialog"].as_u64().unwrap();
app.ui.dialog_mut(id).unwrap().fields.insert("columns".into(), json!(3));
assert!(crate::dialogs::confirm(&mut app, id).is_err());
assert_eq!(app.ui.view.guide_layout["columns"], 8);
}
+12 -3
View File
@@ -510,17 +510,26 @@ pub fn hue_stops() -> Vec<Color32> {
/// A compact labelled dropdown in the studio style.
pub fn dropdown<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool {
dropdown_hovered(ui, id, current, options, width).0
}
/// [`dropdown`], also returning the option under the pointer in its open list (live previews).
pub fn dropdown_hovered<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (bool, Option<T>) {
let label = options.iter().find(|(v, _)| v == current).map(|(_, l)| tl!(l)).unwrap_or("—");
let mut changed = false;
let (mut changed, mut hovered) = (false, None);
egui::ComboBox::from_id_salt(id).selected_text(label).width(width).height(420.0).icon(chevron_icon).show_ui(ui, |ui| {
for (v, l) in options {
if ui.selectable_label(v == current, tl!(l)).clicked() {
let item = ui.selectable_label(v == current, tl!(l));
if item.hovered() {
hovered = Some(v.clone());
}
if item.clicked() {
*current = v.clone();
changed = true;
}
}
});
changed
(changed, hovered)
}
/// The body of a right-click menu: as tall as its items up to the part of the window that can be
+1 -1
View File
@@ -2,7 +2,7 @@
- **Language:** Rust only. No JavaScript or TypeScript. On the web, `wasm-bindgen` generates a small loader; never hand-write JS.
- **Licence:** contributions are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are not open source (`docs/brand/LICENSE-brand.txt`).
- **Clean-room:** do not copy code, shaders, icons, ICC profiles or other assets from proprietary software (such as Photoshop). Match behaviour and look by observation and public specs. Only use assets with permissive licences, keep their license next to the asset (e.g. `assets/fonts/OFL-*.txt`, `assets/icons/LICENSE-lucide.txt`), and list every asset in `ATTRIBUTION.md`. **Fonts** live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo: add new fonts there, and build with them through the optional `CRAFT_FONTS_DIR` build input (`docs/development.md` › Fonts; rules in `../craftrules/standards/fonts.md`).
- **Clean-room:** do not copy code, shaders, icons, ICC profiles or other assets from proprietary software (such as Photoshop). Match behaviour and look by observation and public specs. Only use assets with permissive licences, keep their license next to the asset (e.g. `assets/fonts/OFL-*.txt`, `assets/icons/LICENSE-lucide.txt`), and list every asset in `ATTRIBUTION.md`. **Fonts** live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo: add new fonts there, and build with them through the optional `CRAFT_FONTS_DIR` build input (`docs/development.md` › Fonts; rules in `../craftrules/standards/fonts.md`, a sibling checkout — `storytold/craftrules` is not public, so ask a maintainer for the rules relevant to your change).
- **Never crash:** non-test code must not panic: no `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!`/`unimplemented!` and no `unsafe`. Errors go through `Result` and `?`, input-derived indices and sizes are checked, and every crash fix ships with a regression test. See *Never crash* in `AGENTS.md`.
- **Commands, not handlers:** new features are engine commands with tests, and the UI calls them (checklist below).
- **Layering:** `cargo xtask layers` must pass. Register new crates in `xtask/src/layers.rs`.
+1 -1
View File
@@ -21,7 +21,7 @@ Image code is slow at `opt-level 0`, so the workspace profile builds dependencie
## Fonts (craft-fonts)
Font assets shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo: don't commit font files here (Inter and JetBrains Mono in `assets/fonts/` are the only exceptions; new fonts go to craft-fonts). The rules are in [`craftrules/standards/fonts.md`](../../craftrules/standards/fonts.md) ([on GitHub](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)).
Font assets shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo: don't commit font files here (Inter and JetBrains Mono in `assets/fonts/` are the only exceptions; new fonts go to craft-fonts). The rules are in `craftrules/standards/fonts.md` in a sibling `craftrules` checkout (see below); that repository is not public, so outside contributors can ask a maintainer for the rules that apply to their change.
craft-fonts is an **optional build input**, never a Cargo dependency:
+1 -1
View File
@@ -2,7 +2,7 @@
The release playbook shared by every crafting app lives in craftrules:
[`../craftrules/release/playbook.md`](../../craftrules/release/playbook.md)
(`storytold/craftrules`). It is the canonical copy; don't duplicate it here.
(`storytold/craftrules`, a sibling checkout; the repository is not public). It is the canonical copy; don't duplicate it here.
PhotoCraft is its reference implementation (`.github/workflows/release.yml`, `packaging/`,
`cargo xtask version`). PhotoCraft-specific details are in [releasing.md](releasing.md).
+2 -2
View File
@@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| [Performance](#performance) | 3 | 22 | 13 | 47 scenarios: 3 within budget, 22 over budget or failing, 15 tracked only, 6 not run, 7 not measurable yet (baseline 2026-10-05) |
| [File compatibility](#file-compatibility) | 3 | 9 | 15 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 229/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |
| [Tools](#tools) | 6 | 15 | 9 | |
| [Workspace and UI](#workspace-and-ui) | 0 | 5 | 18 | settings that do nothing: 57 of 135 (target 0) |
| [Workspace and UI](#workspace-and-ui) | 0 | 5 | 18 | settings that do nothing: 57 of 137 (target 0) |
| [Type](#type) | 0 | 3 | 6 | |
| [Automation](#automation) | 3 | 2 | 6 | 627 of 627 menu items live (100.0%) |
| [Reliability](#reliability) | 4 | 1 | 2 | never-crash lints on 27 of 27 crates; panic_hunt present |
@@ -154,7 +154,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
## Workspace and UI
**Settings that do nothing: 57 of 135** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
**Settings that do nothing: 57 of 137** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
Unread: `general.color_picker`, `general.beep_when_done`, `general.export_clipboard`, `general.resize_image_during_place`, `general.always_create_smart_objects_when_placing`, `general.animated_zoom`, `general.zoom_resizes_windows`, `interface.show_channels_in_color`, `interface.dynamic_color_sliders`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.open_documents_as_tabs`, `workspace.enable_floating_document_window_docking`, `workspace.large_tabs`, `workspace.enable_narrow_options_bar`, `tools.zoom_clicked_point_to_center`, `tools.enable_flick_panning`, `tools.vary_round_brush_hardness_on_hud`, `tools.show_transformation_values`, `tools.double_click_layer_mask_launches_select_and_mask`, `file_handling.image_previews`, `file_handling.lowercase_extension`, `file_handling.save_in_background`, `file_handling.ignore_exif_profile_tag`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `cursors.brush_preview_color`, `units_and_rulers.type_units`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `units_and_rulers.print_resolution`, `units_and_rulers.screen_resolution`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.smart_quotes`, `type_.missing_glyph_protection`, `type_.show_font_names_in_english`, `type_.use_esc_to_commit`, `type_.text_engine`, `type_.font_preview`, `type_.fill_new_type_layers_with_placeholder`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `enhanced_controls.zoom_with_trackpad_pinch`, `enhanced_controls.rotate_view_with_trackpad`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`.
View File
Whitespace-only changes.
-5
View File
@@ -1,5 +0,0 @@
running 7 tests
.......
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.53s