mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 14:51:31 -05:00
Merge storytold/photocraft main
# Conflicts: # docs/scorecard.md
This commit is contained in:
@@ -17,6 +17,7 @@ next to them.
|
||||
| `assets/icons/{arrow-left-right,circle-dashed,ellipsis,file-plus,folder-plus,grid-2x2,house,link-2,message-square,panel-left,pipette,rectangle-horizontal,rectangle-vertical,redo-2,square-dashed,square-dashed-mouse-pointer,triangle-alert,type,x}.svg` | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/{link-2,type,x}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/vector-shape.svg` | Vector path shape-layer glyph with four anchor points | @superplay2021 | Original work for PhotoCraft | MIT OR Apache-2.0 |
|
||||
| `assets/icons/gradient-tool.svg` | Gradient tool glyph with a horizontal opacity ramp | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/spirit-level.svg` | Straighten tool glyph: a spirit level with its vial and bubble under a dotted arc | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/type-vertical.svg` | Vertical Type tool glyph: Lucide `type`'s T, drawn narrower to make room for a downward arrow of our own at its left | Lucide Icons and Contributors; arrow by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/type.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/path-op-{new-layer,combine,subtract,intersect,exclude,merge}.svg` | Path Operations glyphs (Pen options bar): a single square for New Layer, and two overlapping squares showing the area each operation keeps (union, back minus front, overlap, everything but the overlap, the merged outline), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
@@ -27,6 +28,7 @@ next to them.
|
||||
| `assets/app-icon/photocraft-nightly.png`, `photocraft-nightly-1024.png`, `photocraft-nightly.ico`, `photocraft-nightly.icns` | PhotoCraft nightly deep-background derivatives | @skylartaylor | Original project-owned256 and padded1024 masters at the revision and hashes in [`nightly-provenance.json`](assets/app-icon/nightly-provenance.json); code-generated background-contribution change only, preserving foreground/alpha; no badge or crescent | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) |
|
||||
| `packaging/nightly-archive-tests.py` (runtime-generated temporary files) | Synthetic flat-archive inventory and exclusive-output fixtures; regular-file payloads, not real image/executable validity | @skylartaylor | Original test-generated strings/files and symlinks from the committed script; no external media or user documents | MIT OR Apache-2.0 |
|
||||
| `packaging/macos/dmg/` (all files) | PhotoCraft DMG window background and layout | @XusBadia, from the PhotoCraft app icon | Original work, see [`packaging/macos/dmg/README.md`](packaging/macos/dmg/README.md) | MIT OR Apache-2.0, like the code |
|
||||
| `crates/ui-egui/src/dialogs/adjust_editors/black_white_presets.rs` | Built-in Black & White tonal and filter mixes | PhotoCraft contributors (@Bobderto) | Original weights chosen to produce the named tonal and color-filter effects, from [PhotoCraft `2b1afe637`](https://github.com/storytold/photocraft/commit/2b1afe637cabe3eba622c8edd3e92b279aa8dfe4) | MIT OR Apache-2.0 |
|
||||
| `crates/ui-egui/src/theme.rs` (Solarized Dark palette) | Solarized colour scheme used by the Solarized Dark theme | Ethan Schoonover | <https://ethanschoonover.com/solarized/> | MIT, [`LICENSE-solarized.txt`](crates/ui-egui/src/LICENSE-solarized.txt) |
|
||||
| `crates/ui-egui/src/theme.rs` (Breeze Light and Breeze Dark themes) | The Breeze Light and Breeze Dark themes are original colour values on PhotoCraft's Studio layout, chosen to look close to KDE Plasma's Breeze (cool blue-greys, blue accent, 5 px frame radius) so the app blends into a Plasma desktop. None of Breeze's colour values, files or code are copied; the values are a few levels away from its schemes and tuned for text contrast | PhotoCraft contributors | Inspired by the look of KDE Breeze, <https://invent.kde.org/plasma/breeze> (its colour schemes are LGPL-2.0-or-later) | Original work |
|
||||
| `crates/ui-egui/src/theme.rs` (Soft Dark and Soft Light themes) | Original colour values and radii for two low-contrast themes on PhotoCraft's Studio layout; no third-party palette, file or code is used | PhotoCraft contributors | Original | Original work |
|
||||
|
||||
Generated
+2
@@ -7103,6 +7103,7 @@ version = "0.23.1"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
"core-graphics",
|
||||
"craft",
|
||||
"craft-file-formats",
|
||||
"craft-i18n",
|
||||
@@ -7141,6 +7142,7 @@ dependencies = [
|
||||
"toml",
|
||||
"web-time",
|
||||
"winsafe",
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -101,8 +101,8 @@ fn recovery_dir() -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
/// Write `bytes` crash-safely (temp file beside the target, fsync, rename, directory fsync; see
|
||||
/// [`photocraft_format::atomic`]). Every document write (Save, Save As, Export, Save for Web) and
|
||||
/// the preferences go through here, so a failed or interrupted save never destroys the old file.
|
||||
/// [`photocraft_format::atomic`]). Save, Save As, overwriting exports and preferences use this so
|
||||
/// a failed or interrupted write never destroys the old file.
|
||||
fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||
photocraft_format::atomic_write(path, bytes).map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -602,6 +602,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>, wa
|
||||
file_panels: Some(file_panels),
|
||||
settings: Some(settings_store()),
|
||||
write: Some(Box::new(|path: &str, bytes: &[u8]| write_atomic(Path::new(path), bytes))),
|
||||
write_new: Some(Box::new(|path, bytes| photocraft_format::write_noreplace(Path::new(path), bytes).map_err(|e| format!("{path}: {e}")))),
|
||||
file_stamp: Some(Box::new(|path: &str| {
|
||||
// Follows a symlink, as Save writes through it to the file it points at.
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||
<defs>
|
||||
<!-- The toolbar tints the alpha mask: reveal its background at left and the icon colour at right. -->
|
||||
<linearGradient id="ramp" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||
<stop offset="0" stop-color="#000" stop-opacity="0"/>
|
||||
<stop offset="1" stop-color="#000"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="3" y="5" width="18" height="14" rx="2" fill="url(#ramp)" stroke="#000" stroke-width="2"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 485 B |
@@ -1168,7 +1168,8 @@ fn apply_sketch(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) -> bool {
|
||||
let mut l = win.lum();
|
||||
blur1(&mut l, w, h, 0.3 + g("smoothness") * 0.3);
|
||||
for i in 0..win.c.len() {
|
||||
win.c[i] = mix(bg, fg, smoothstep(bal + 0.02, bal - 0.02, l[i]));
|
||||
// Smooth the shapes without introducing colors between the ink and paper.
|
||||
win.c[i] = if l[i] < bal { fg } else { bg };
|
||||
}
|
||||
}
|
||||
F::TornEdges => {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
use photocraft_color::{PixelFormat, blend, dither_noise};
|
||||
use photocraft_raster::Surface;
|
||||
|
||||
use super::{BlendMode, FillMode, GradientShape, Rect, paint_gradient, sample_stops, tool_gradient_t};
|
||||
|
||||
const WIDTH: i32 = 2560;
|
||||
const STOPS: [(f32, [f32; 4]); 2] = [(0.0, [0.0, 0.0, 0.0, 1.0]), (1.0, [1.0, 1.0, 1.0, 1.0])];
|
||||
|
||||
fn row(format: PixelFormat, base: u8, mode: BlendMode, dither: bool) -> Surface {
|
||||
let mut surface = Surface::new(format);
|
||||
let area = Rect::new(0, 0, WIDTH, 1);
|
||||
let gray = f32::from(base) / 255.0;
|
||||
surface.fill_rect(area, &[gray, gray, gray, 1.0]);
|
||||
paint_gradient(&mut surface, area, (0.0, 0.0), (WIDTH as f32, 0.0), GradientShape::Linear, &STOPS, false, 1.0, FillMode::Blend(mode), dither, None, false);
|
||||
surface
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_hard_mix_switches_at_the_normal_ramp_byte_boundary() {
|
||||
let normal = row(PixelFormat::RGBA8, 0, BlendMode::Normal, false);
|
||||
for (base, first_white) in [(128, 127), (100, 156)] {
|
||||
let hard_mix = row(PixelFormat::RGBA8, base, BlendMode::HardMix, false);
|
||||
let mut saw = [0usize; 2];
|
||||
for x in 0..WIDTH {
|
||||
let normal_level = (normal.pixel(x, 0)[0] * 255.0).round() as u8;
|
||||
let white = normal_level >= first_white;
|
||||
assert_eq!(hard_mix.pixel(x, 0)[0], f32::from(u8::from(white)), "base {base}, x={x}, normal {normal_level}");
|
||||
if normal_level == first_white - 1 || normal_level == first_white {
|
||||
saw[usize::from(white)] += 1;
|
||||
}
|
||||
}
|
||||
assert!(saw.into_iter().all(|pixels| pixels > 1), "both tested colour runs have more than one pixel");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dithering_deep_rgb_and_other_modes_keep_the_existing_float_composite() {
|
||||
for (format, mode, dither) in [
|
||||
(PixelFormat::RGBA8, BlendMode::HardMix, true),
|
||||
(PixelFormat::RGBA16, BlendMode::HardMix, false),
|
||||
(PixelFormat::RGBA32F, BlendMode::HardMix, false),
|
||||
(PixelFormat::RGBA8, BlendMode::Multiply, false),
|
||||
] {
|
||||
let actual = row(format, 100, mode, dither);
|
||||
let mut expected = Surface::new(format);
|
||||
expected.write_pixel(0, 0, &[100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 1.0]);
|
||||
let base = expected.rgba(0, 0);
|
||||
for x in 0..WIDTH {
|
||||
let t = tool_gradient_t(GradientShape::Linear, (0.0, 0.0), (WIDTH as f32, 0.0), x as f32 - 0.5, -0.5);
|
||||
let mut color = sample_stops(&STOPS, t);
|
||||
if dither {
|
||||
let noise = (dither_noise(x, 0) - 0.5) / 255.0;
|
||||
for channel in &mut color[..3] {
|
||||
*channel = (*channel + noise).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
expected.write_pixel(x, 0, &blend::composite(mode, base, color, 1.0));
|
||||
assert_eq!(actual.pixel(x, 0), expected.pixel(x, 0), "{format:?} {mode:?}, dither={dither}, x={x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use photocraft_color::PixelFormat;
|
||||
use photocraft_raster::Surface;
|
||||
|
||||
use super::{BlendMode, FillMode, GradientShape, Rect, paint_gradient};
|
||||
|
||||
#[test]
|
||||
fn gradient_hard_mix_matches_all_u8_pairs_and_uses_each_rgb_channel() {
|
||||
let mut surface = Surface::new(PixelFormat::RGBA8);
|
||||
for base in 0..256 {
|
||||
let gray = base as f32 / 255.0;
|
||||
surface.fill_rect(Rect::new(0, base, 256, base + 1), &[gray, gray, gray, 1.0]);
|
||||
}
|
||||
let blue = 200.0 / 255.0;
|
||||
paint_gradient(
|
||||
&mut surface,
|
||||
Rect::new(0, 0, 256, 256),
|
||||
(-0.5, 0.0),
|
||||
(254.5, 0.0),
|
||||
GradientShape::Linear,
|
||||
&[(0.0, [0.0, 1.0, blue, 1.0]), (1.0, [1.0, 0.0, blue, 1.0])],
|
||||
false,
|
||||
1.0,
|
||||
FillMode::Blend(BlendMode::HardMix),
|
||||
false,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
for base in 0..256 {
|
||||
for source in 0..256 {
|
||||
let expected = [source, 255 - source, 200].map(|channel| match (base + channel).cmp(&255) {
|
||||
Ordering::Less => 0.0,
|
||||
Ordering::Greater => 1.0,
|
||||
Ordering::Equal => f32::from(u8::from(channel < 128)),
|
||||
});
|
||||
let actual = surface.pixel(source, base);
|
||||
assert_eq!(actual[..3], expected, "base {base}, red source {source}");
|
||||
assert_eq!(actual[3], 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_hard_mix_preserves_source_over_and_locked_alpha() {
|
||||
for locked in [false, true] {
|
||||
let mut surface = Surface::new(PixelFormat::RGBA8);
|
||||
surface.write_pixel(1, 0, &[127.0 / 255.0, 127.0 / 255.0, 127.0 / 255.0, 128.0 / 255.0]);
|
||||
let color = [128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0];
|
||||
paint_gradient(
|
||||
&mut surface,
|
||||
Rect::new(0, 0, 2, 1),
|
||||
(0.0, 0.0),
|
||||
(1.0, 0.0),
|
||||
GradientShape::Linear,
|
||||
&[(0.0, color), (1.0, color)],
|
||||
false,
|
||||
0.5,
|
||||
FillMode::Blend(BlendMode::HardMix),
|
||||
false,
|
||||
None,
|
||||
locked,
|
||||
);
|
||||
let byte = |x, channel: usize| (surface.pixel(x, 0)[channel] * 255.0).round() as u8;
|
||||
if locked {
|
||||
assert_eq!(byte(0, 3), 0);
|
||||
assert_eq!((byte(1, 0), byte(1, 3)), (64, 128));
|
||||
} else {
|
||||
assert_eq!((byte(0, 0), byte(0, 3)), (128, 128));
|
||||
assert_eq!((byte(1, 0), byte(1, 3)), (85, 192));
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-12
@@ -32,18 +32,24 @@ pub(crate) fn add(src: &Image, out: Rect, ctx: &Ctx, amount: f32, dist: Distribu
|
||||
continue;
|
||||
}
|
||||
let (x, y) = (out.x0 + (i % w) as i32, out.y0 + (i / w) as i32);
|
||||
for (c, pv) in px.iter_mut().enumerate().take(cc) {
|
||||
let ch = if mono { 0 } else { c as u32 };
|
||||
let v = match dist {
|
||||
Distribution::Uniform => (hash01(x, y, ch, seed) - 0.5) * 2.0 * a,
|
||||
Distribution::Gaussian => {
|
||||
let u1 = hash01(x, y, ch * 2 + 101, seed).max(1e-7);
|
||||
let u2 = hash01(x, y, ch * 2 + 102, seed);
|
||||
(-2.0 * u1.ln()).sqrt() * (std::f32::consts::TAU * u2).cos() * a * 0.5
|
||||
}
|
||||
};
|
||||
// Integer storage clamps on write; float surfaces keep the value.
|
||||
*pv += v;
|
||||
let value = |ch| match dist {
|
||||
Distribution::Uniform => (hash01(x, y, ch, seed) - 0.5) * 2.0 * a,
|
||||
Distribution::Gaussian => {
|
||||
let u1 = hash01(x, y, ch * 2 + 101, seed).max(1e-7);
|
||||
let u2 = hash01(x, y, ch * 2 + 102, seed);
|
||||
(-2.0 * u1.ln()).sqrt() * (std::f32::consts::TAU * u2).cos() * a * 0.5
|
||||
}
|
||||
};
|
||||
// Integer storage clamps on write; float surfaces keep the value.
|
||||
if mono {
|
||||
let v = value(0);
|
||||
for pv in px.iter_mut().take(cc) {
|
||||
*pv += v;
|
||||
}
|
||||
} else {
|
||||
for (c, pv) in px.iter_mut().enumerate().take(cc) {
|
||||
*pv += value(c as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
res
|
||||
|
||||
@@ -78,6 +78,7 @@ fn composite_area(
|
||||
mode: FillMode,
|
||||
coverage: impl Fn(i32, i32) -> f32 + Sync,
|
||||
color: impl Fn(i32, i32) -> [f32; 4] + Sync,
|
||||
blend_pixel: impl Fn(BlendMode, [f32; 4], [f32; 4], f32, bool) -> [f32; 4] + Sync,
|
||||
lock_transparency: bool,
|
||||
inks: Option<[f32; 4]>,
|
||||
rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)>,
|
||||
@@ -123,8 +124,7 @@ fn composite_area(
|
||||
continue;
|
||||
}
|
||||
let o = match mode {
|
||||
FillMode::Blend(m) if lock_transparency => blend::composite_atop(m, d, color(x, y), k),
|
||||
FillMode::Blend(m) => blend::composite(m, d, color(x, y), k),
|
||||
FillMode::Blend(m) => blend_pixel(m, d, color(x, y), k, lock_transparency),
|
||||
// Locked transparency keeps the alpha, so Clear leaves the pixel as it is.
|
||||
FillMode::Clear if lock_transparency => d,
|
||||
FillMode::Clear => [d[0], d[1], d[2], d[3] * (1.0 - k.min(1.0))],
|
||||
@@ -157,6 +157,10 @@ fn composite_area(
|
||||
}
|
||||
}
|
||||
|
||||
fn composite_blend(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], coverage: f32, lock_transparency: bool) -> [f32; 4] {
|
||||
if lock_transparency { blend::composite_atop(mode, backdrop, source, coverage) } else { blend::composite(mode, backdrop, source, coverage) }
|
||||
}
|
||||
|
||||
/// [`FillMode::Behind`] for one pixel: `src` laid under `d` at coverage `k`, with the Brush's
|
||||
/// Behind formula (`photocraft_paint`'s render): the fill's share is `src α × k × (1 − d α)`.
|
||||
fn behind(d: [f32; 4], src: [f32; 4], k: f32) -> [f32; 4] {
|
||||
@@ -194,6 +198,10 @@ pub fn paint_gradient(
|
||||
let smooth_16 =
|
||||
fmt.sample == photocraft_color::SampleType::U16 && matches!(fmt.mode, photocraft_color::ColorMode::Rgb | photocraft_color::ColorMode::Grayscale);
|
||||
let dither = dither && !smooth_16;
|
||||
let hard_mix_rgb8 = mode == FillMode::Blend(BlendMode::HardMix)
|
||||
&& fmt.mode == photocraft_color::ColorMode::Rgb
|
||||
&& fmt.sample == photocraft_color::SampleType::U8
|
||||
&& !dither;
|
||||
composite_area(
|
||||
s,
|
||||
area,
|
||||
@@ -212,12 +220,35 @@ pub fn paint_gradient(
|
||||
}
|
||||
c
|
||||
},
|
||||
|mode, backdrop, source, coverage, locked| {
|
||||
if hard_mix_rgb8 {
|
||||
composite_hard_mix_gradient(backdrop, source, coverage, locked)
|
||||
} else {
|
||||
composite_blend(mode, backdrop, source, coverage, locked)
|
||||
}
|
||||
},
|
||||
lock_transparency,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
fn composite_hard_mix_gradient(backdrop: [f32; 4], mut source: [f32; 4], coverage: f32, locked: bool) -> [f32; 4] {
|
||||
// Round the comparison exactly as a Normal RGB8 gradient would store it. Equal sums
|
||||
// take white for a dark source and black for a light source.
|
||||
let quantize = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u16;
|
||||
let blend_weight = if locked { 1.0 } else { backdrop[3] };
|
||||
for (color, base) in source[..3].iter_mut().zip(&backdrop[..3]) {
|
||||
let s = quantize(*color);
|
||||
let sum = quantize(*base) + s;
|
||||
let mixed = if sum > 255 || (sum == 255 && s <= 127) { 1.0 } else { 0.0 };
|
||||
// In source-over, only the overlap uses the blend. The uncovered part keeps the
|
||||
// unblended gradient colour. Normal then applies the existing coverage and alpha math.
|
||||
*color = (1.0 - blend_weight) * *color + blend_weight * mixed;
|
||||
}
|
||||
composite_blend(BlendMode::Normal, backdrop, source, coverage, locked)
|
||||
}
|
||||
|
||||
/// Paint bucket: fills the region similar to the seed pixel (on the layer's
|
||||
/// own pixels) within `area`, respecting the selection.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -352,7 +383,7 @@ fn fill_region(
|
||||
if hit == Some(&true) { strength(x, y) } else { 0.0 }
|
||||
};
|
||||
let rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if use_rim { Some(&on_ring) } else { None };
|
||||
composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, rim);
|
||||
composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, composite_blend, lock_transparency, inks, rim);
|
||||
}
|
||||
|
||||
/// Over `region.bbox` (row-major): the pixels the region leaves uncovered that touch one of its
|
||||
@@ -378,6 +409,14 @@ mod gradient_dither_16bit_tests;
|
||||
#[path = "paint_gradient_sample_tests.rs"]
|
||||
mod paint_gradient_sample_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gradient_hard_mix_tie_tests.rs"]
|
||||
mod gradient_hard_mix_tie_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gradient_hard_mix_rounded_source_tests.rs"]
|
||||
mod gradient_hard_mix_rounded_source_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -532,9 +532,21 @@ mod tests {
|
||||
assert!(read_radius(sigma(25.0, bounds)) > 97);
|
||||
let area = output_area(&p, s.content_bounds(), bounds, None);
|
||||
let full = apply_tiled(&s, &p, area, bounds, None, 4096, None);
|
||||
let tiled = apply_tiled(&s, &p, area, bounds, None, 128, None);
|
||||
let inner = Rect::new(0, 0, size, size);
|
||||
let d = max_diff(&full.read_region(inner), &tiled.read_region(inner));
|
||||
// Keep every tile that contributes checked pixels, including each edge tile's
|
||||
// original rectangle and halo. The remaining tiles lie wholly outside the canvas.
|
||||
let tile = 128;
|
||||
let tile_start = |pixel: i32, origin: i32| origin + (pixel - origin).div_euclid(tile) * tile;
|
||||
let visible_tiles = Rect::new(
|
||||
tile_start(bounds.x0, area.x0),
|
||||
tile_start(bounds.y0, area.y0),
|
||||
tile_start(bounds.x1 - 1, area.x0) + tile,
|
||||
tile_start(bounds.y1 - 1, area.y0) + tile,
|
||||
)
|
||||
.intersect(&area);
|
||||
let tiled = apply_tiled(&s, &p, visible_tiles, bounds, None, tile, None);
|
||||
let center = size / 2;
|
||||
assert!(max_diff(&full.pixel(center, center), &s.pixel(center, center)) > 1e-4, "the full frame must be relit");
|
||||
let d = max_diff(&full.read_region(bounds), &tiled.read_region(bounds));
|
||||
assert!(d <= 1e-4, "tile seam {d}");
|
||||
}
|
||||
|
||||
|
||||
+42
-15
@@ -110,6 +110,8 @@ fn all_filters() -> Vec<FilterParams> {
|
||||
FilterParams::SmartSharpen { amount: 100.0, radius: 1.0, reduce_noise: 20.0 },
|
||||
FilterParams::HighPass { radius: 3.0 },
|
||||
FilterParams::AddNoise { amount: 25.0, distribution: Distribution::Gaussian, monochromatic: false, seed: 3 },
|
||||
FilterParams::AddNoise { amount: 25.0, distribution: Distribution::Uniform, monochromatic: true, seed: 3 },
|
||||
FilterParams::AddNoise { amount: 25.0, distribution: Distribution::Gaussian, monochromatic: true, seed: 3 },
|
||||
FilterParams::Median { radius: 2.0 },
|
||||
FilterParams::DustAndScratches { radius: 2.0, threshold: 10.0 },
|
||||
FilterParams::Minimum { radius: 1.0, preserve: Preserve::Squareness },
|
||||
@@ -291,24 +293,49 @@ fn high_pass_of_flat_is_mid_gray() {
|
||||
assert!((p[0] - 0.5).abs() < 1e-5 && (p[1] - 0.5).abs() < 1e-5);
|
||||
}
|
||||
|
||||
/// Both noise distributions preserve alpha and share a seeded value across color channels.
|
||||
#[test]
|
||||
fn noise_is_deterministic_monochrome_and_centred() {
|
||||
let s = flat(SampleType::F32, R, [0.5, 0.5, 0.5, 1.0]);
|
||||
let p = FilterParams::AddNoise { amount: 50.0, distribution: Distribution::Uniform, monochromatic: true, seed: 1 };
|
||||
let a = run(&s, &p);
|
||||
assert_eq!(a, run(&s, &p));
|
||||
let v = a.read_region(R);
|
||||
let mut mean = 0.0;
|
||||
for px in v.as_chunks::<4>().0 {
|
||||
assert_eq!(px[0], px[1]);
|
||||
assert_eq!(px[1], px[2]);
|
||||
assert!((px[0] - 0.5).abs() <= 0.25 + 1e-6);
|
||||
mean += px[0];
|
||||
for distribution in [Distribution::Uniform, Distribution::Gaussian] {
|
||||
let s = flat(SampleType::F32, R, [0.5, 0.5, 0.5, 1.0]);
|
||||
let p = FilterParams::AddNoise { amount: 50.0, distribution, monochromatic: true, seed: 1 };
|
||||
let a = run(&s, &p);
|
||||
assert_eq!(a, run(&s, &p));
|
||||
let v = a.read_region(R);
|
||||
let mut mean = 0.0;
|
||||
for px in v.as_chunks::<4>().0 {
|
||||
assert_eq!(px[0], px[1]);
|
||||
assert_eq!(px[1], px[2]);
|
||||
if matches!(distribution, Distribution::Uniform) {
|
||||
assert!((px[0] - 0.5).abs() <= 0.25 + 1e-6);
|
||||
}
|
||||
assert_eq!(px[3], 1.0);
|
||||
mean += px[0];
|
||||
}
|
||||
mean /= (v.len() / 4) as f32;
|
||||
assert!((mean - 0.5).abs() < 0.03, "{mean}");
|
||||
let other_seed = run(&s, &FilterParams::AddNoise { amount: 50.0, distribution, monochromatic: true, seed: 2 });
|
||||
assert_ne!(a, other_seed);
|
||||
}
|
||||
}
|
||||
|
||||
/// RGB8 goldens from 799e1296's original Add Noise, before monochrome sampling was hoisted.
|
||||
#[test]
|
||||
fn monochrome_noise_matches_original_rgb8_bytes() {
|
||||
let area = Rect::new(0, 0, 3, 2);
|
||||
let mut source = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, false));
|
||||
source.fill_rect(area, &[0.5, 0.5, 0.5]);
|
||||
let rgb_bytes = |surface: &Surface| surface.read_region(area).iter().map(|v| (v * 255.0).round() as u8).collect::<Vec<_>>();
|
||||
let cases: [(Distribution, [u8; 18]); 2] = [
|
||||
(Distribution::Uniform, [65, 65, 65, 96, 96, 96, 134, 134, 134, 67, 67, 67, 86, 86, 86, 118, 118, 118]),
|
||||
(Distribution::Gaussian, [105, 105, 105, 104, 104, 104, 117, 117, 117, 103, 103, 103, 167, 167, 167, 136, 136, 136]),
|
||||
];
|
||||
for (distribution, expected) in cases {
|
||||
let monochrome = apply(&source, &FilterParams::AddNoise { amount: 50.0, distribution, monochromatic: true, seed: 1 }, area, area, None);
|
||||
assert_eq!(rgb_bytes(&monochrome).as_slice(), expected.as_slice(), "{distribution:?}");
|
||||
let colored = apply(&source, &FilterParams::AddNoise { amount: 50.0, distribution, monochromatic: false, seed: 1 }, area, area, None);
|
||||
assert!(rgb_bytes(&colored).as_chunks::<3>().0.iter().any(|pixel| pixel[0] != pixel[1] || pixel[1] != pixel[2]), "{distribution:?}");
|
||||
}
|
||||
mean /= (v.len() / 4) as f32;
|
||||
assert!((mean - 0.5).abs() < 0.03, "{mean}");
|
||||
let other_seed = run(&s, &FilterParams::AddNoise { amount: 50.0, distribution: Distribution::Uniform, monochromatic: true, seed: 2 });
|
||||
assert_ne!(a, other_seed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -191,8 +191,8 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept
|
||||
}
|
||||
None => (0.0, 0.0, 0.0),
|
||||
};
|
||||
let sat = colorize_saturation((*saturation / 100.0 + ds).clamp(-1.0, 1.0), *lightness / 100.0, *colorize, depth);
|
||||
let out = hue_saturation_in(c, *hue + dh, sat, (*lightness / 100.0).clamp(-1.0, 1.0), *colorize, depth);
|
||||
let sat = colorize_saturation((*saturation / 100.0).clamp(-1.0, 1.0), *lightness / 100.0, *colorize, depth);
|
||||
let out = hue_saturation_in(c, *hue + dh, sat, ds.clamp(-1.0, 1.0), (*lightness / 100.0).clamp(-1.0, 1.0), *colorize, depth);
|
||||
range_lightness(out, dl)
|
||||
})
|
||||
}
|
||||
@@ -434,6 +434,9 @@ mod gradient_map_grayscale_tests;
|
||||
#[cfg(test)]
|
||||
mod tone_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod hue_saturation_range_multiply_tests;
|
||||
|
||||
/// Legacy Brightness/Contrast scales contrast around 128 of 255 (contrast 80 keeps 128 at 128,
|
||||
/// measured on Photoshop 27.11; a 0.5 pivot moved it to 130).
|
||||
pub const LEGACY_PIVOT: f32 = 128.0 / 255.0;
|
||||
|
||||
@@ -30,15 +30,18 @@ pub fn colorize_saturation(s: f32, lightness: f32, colorize: bool, depth: Option
|
||||
/// Colorize sets the hue and saturation instead of shifting them; at 0% it leaves only the
|
||||
/// lightness, as in Photoshop (#2326). Ticking Colorize in the dialog starts saturation at 25%.
|
||||
pub fn hue_saturation(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool) -> [f32; 3] {
|
||||
hue_saturation_in(c, hue, s, l, colorize, None)
|
||||
hue_saturation_in(c, hue, s, 0.0, l, colorize, None)
|
||||
}
|
||||
|
||||
/// [`hue_saturation`] in a document of `depth`. At 32 bits Photoshop doesn't clip the raised
|
||||
/// saturation, so saturated colours leave 0..1 (red with Hue +40, Saturation +25, Lightness -10
|
||||
/// becomes (1.0477, 0.649, -0.1477)), and it scales each colour's chroma around its lightness by
|
||||
/// [`hdr_saturation_factor`], so colours at or above lightness 1 keep their hue too: the photoshop
|
||||
/// corpus's rgb32 hue-saturation.psd is exact so.
|
||||
pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool, depth: Option<SampleType>) -> [f32; 3] {
|
||||
/// corpus's rgb32 hue-saturation.psd is exact so. A colour range's saturation `range_s` scales
|
||||
/// the pixel's saturation again after the master's, so their factors multiply: Master -50 with
|
||||
/// Reds -50 leaves a quarter of red's saturation, (255, 0, 0) becomes (159, 95, 95) in the
|
||||
/// reference application (#14741). Colorize ignores it, as ranges don't apply there.
|
||||
pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, range_s: f32, l: f32, colorize: bool, depth: Option<SampleType>) -> [f32; 3] {
|
||||
let hdr = depth == Some(SampleType::F32);
|
||||
let lighten = |v: f32| if l > 0.0 { v + (1.0 - v) * l } else { v * (1.0 + l) };
|
||||
if colorize {
|
||||
@@ -56,12 +59,13 @@ pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool,
|
||||
if hdr {
|
||||
// The chroma, not the HSL saturation, whose `2 - max - min` divisor is 0 at lightness 1
|
||||
// and negative above it: (2, 0, 0) with Hue +40 becomes (2, 1.333, 0) in Photoshop.
|
||||
let d = (lc[0].max(lc[1]).max(lc[2]) - lc[0].min(lc[1]).min(lc[2])) * hdr_saturation_factor(s);
|
||||
let d = (lc[0].max(lc[1]).max(lc[2]) - lc[0].min(lc[1]).min(lc[2])) * (hdr_saturation_factor(s) * hdr_saturation_factor(range_s));
|
||||
return hue_rgb(hh, ll - d / 2.0, ll + d / 2.0);
|
||||
}
|
||||
// Raising saturation divides by 1 - s, lowering it multiplies by 1 + s: +50 % doubles it
|
||||
// (measured in Photoshop 27.11); +100 % saturates any colour that has some.
|
||||
let ss = if s > 0.0 { ss / (1.0 - s).max(1.0 / 512.0) } else { ss * (1.0 + s) }.clamp(0.0, 1.0);
|
||||
let scale = |v: f32, by: f32| if by > 0.0 { v / (1.0 - by).max(1.0 / 512.0) } else { v * (1.0 + by) };
|
||||
let ss = scale(scale(ss, s), range_s).clamp(0.0, 1.0);
|
||||
hsl_to_rgb(hh, ss, ll)
|
||||
}
|
||||
|
||||
@@ -71,7 +75,7 @@ pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool,
|
||||
/// 1/256 and stops at 32767/256, so +25 % gives 340/256, +99 % 63.75 and +100 % 127.996.
|
||||
/// compose.wgsl's Hue/Saturation does the same in whole numbers.
|
||||
pub fn hdr_saturation_factor(s: f32) -> f32 {
|
||||
// The 1e-4 keeps a master plus range sum on its step: -0.46 + 0.96 is 0.49999997 in f32.
|
||||
// The 1e-4 keeps a value a rounding error under a step on that step: 0.49999997 is +50 %.
|
||||
let s = s.clamp(-1.0, 1.0);
|
||||
if s <= 0.0 {
|
||||
return 1.0 - (-s * 256.0 + 1e-4).floor() / 256.0;
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//! #14741: a colour range's Saturation multiplies the Master Saturation's factor instead of
|
||||
//! adding to it.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn hue_sat(master: f32, reds: f32) -> Adjustment {
|
||||
let mut ranges = HueRange::defaults();
|
||||
ranges[0].saturation = reds;
|
||||
Adjustment::HueSaturation { hue: 0.0, saturation: master, lightness: 0.0, colorize: false, ranges }
|
||||
}
|
||||
|
||||
fn run(adj: &Adjustment, c: [f32; 3], depth: SampleType) -> [f32; 3] {
|
||||
let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]);
|
||||
apply_depth(adj, &mut b, Transfer::Gamma(1.0), Some(depth));
|
||||
[b.px[0][0], b.px[0][1], b.px[0][2]]
|
||||
}
|
||||
|
||||
fn levels(c: [f32; 3]) -> [f32; 3] {
|
||||
c.map(|v| (v * 255.0).round())
|
||||
}
|
||||
|
||||
fn within(got: [f32; 3], want: [f32; 3], tolerance: f32) -> bool {
|
||||
levels(got).iter().zip(levels(want)).all(|(g, w)| (g - w).abs() <= tolerance)
|
||||
}
|
||||
|
||||
/// The reference application, measured: Master -50 with Reds -50 turns (255, 0, 0) into
|
||||
/// (159, 95, 95), a quarter of red's saturation. Adding the two made -100 and grey.
|
||||
#[test]
|
||||
fn master_and_reds_minus_fifty_keep_a_quarter_of_red() {
|
||||
let got = run(&hue_sat(-50.0, -50.0), [1.0, 0.0, 0.0], SampleType::U8);
|
||||
let want = [159.0, 95.0, 95.0].map(|v| v / 255.0);
|
||||
assert!(within(got, want, 1.0), "{:?}", levels(got));
|
||||
}
|
||||
|
||||
/// The 72-hue ramp of the measurement at HSL saturation 100 % and 50 %: no Reds cell turns grey,
|
||||
/// and away from the range's fades every cell has master × range of its saturation.
|
||||
#[test]
|
||||
fn ramp_cells_take_the_product_of_both_factors() {
|
||||
let adj = hue_sat(-50.0, -50.0);
|
||||
for s in [1.0, 0.5] {
|
||||
for step in 0..72 {
|
||||
let deg = step as f32 * 5.0;
|
||||
let c = hsl_to_rgb(deg / 360.0, s, 0.5);
|
||||
let got = run(&adj, c, SampleType::U8);
|
||||
let from_red = deg.min(360.0 - deg);
|
||||
if from_red < 45.0 {
|
||||
let chroma = got[0].max(got[1]).max(got[2]) - got[0].min(got[1]).min(got[2]);
|
||||
assert!(chroma * 255.0 >= 8.0, "hue {deg} at {s}: {:?} is grey", levels(got));
|
||||
}
|
||||
let factor = match from_red {
|
||||
d if d <= 15.0 => 0.25,
|
||||
d if d >= 45.0 => 0.5,
|
||||
_ => continue,
|
||||
};
|
||||
let want = hsl_to_rgb(deg / 360.0, s * factor, 0.5);
|
||||
assert!(within(got, want, 2.0), "hue {deg} at {s}: {:?}, want {:?}", levels(got), levels(want));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Raised and mixed settings combine as the same factors applied in turn: +50 doubles the
|
||||
/// saturation, -50 halves it, +25 multiplies it by 4/3.
|
||||
#[test]
|
||||
fn raised_and_mixed_settings_multiply_their_factors() {
|
||||
let red = |s: f32| hsl_to_rgb(0.0, s, 0.5);
|
||||
for (master, reds, s, want) in
|
||||
[(50.0, -50.0, 0.4, 0.4), (-50.0, 50.0, 0.4, 0.4), (25.0, 25.0, 0.3, 0.3 * 16.0 / 9.0), (50.0, 50.0, 0.4, 1.0), (-100.0, 50.0, 0.4, 0.0)]
|
||||
{
|
||||
let got = run(&hue_sat(master, reds), red(s), SampleType::U8);
|
||||
assert!(within(got, red(want), 1.0), "master {master}, reds {reds}: {:?}, want {:?}", levels(got), levels(red(want)));
|
||||
}
|
||||
}
|
||||
|
||||
/// 32 bits scale the chroma by the product of their own factors: a quarter of red's chroma for
|
||||
/// -50 twice, and Reds -50 halves what Master +50 (510/256) or +100 (32767/256) alone gives.
|
||||
#[test]
|
||||
fn thirty_two_bits_multiply_too() {
|
||||
let chroma = |c: [f32; 3]| c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2]);
|
||||
for (master, reds, want) in [(-50.0, -50.0, 0.25), (50.0, -50.0, 255.0 / 256.0), (100.0, -50.0, 32767.0 / 512.0)] {
|
||||
let got = run(&hue_sat(master, reds), [1.0, 0.0, 0.0], SampleType::F32);
|
||||
assert!((chroma(got) - want).abs() < 1e-3 * want, "master {master}, reds {reds}: {got:?}, chroma {want}");
|
||||
assert!(got[1..].iter().all(|v| (v - (1.0 - want) / 2.0).abs() < 1e-3 * want.max(1.0)), "{got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A range alone reaches the saturation step as a master of the same value does, bit for bit, on
|
||||
/// a colour inside the range: one setting alone is untouched by the change.
|
||||
#[test]
|
||||
fn one_setting_alone_passes_through_unchanged() {
|
||||
let c = hsl_to_rgb(2.0 / 360.0, 0.6, 0.45);
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
for k in -20..=20 {
|
||||
let v = k as f32 * 5.0;
|
||||
let range = run(&hue_sat(0.0, v), c, depth).map(f32::to_bits);
|
||||
let master = run(&hue_sat(v, 0.0), c, depth).map(f32::to_bits);
|
||||
assert_eq!(range, master, "{depth:?}, {v}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_values_stay_finite() {
|
||||
for depth in [SampleType::U8, SampleType::F32] {
|
||||
for (m, r) in [(f32::INFINITY, -50.0), (f32::NEG_INFINITY, 50.0), (100.0, 100.0), (-100.0, -100.0), (100.0, -100.0), (500.0, 500.0), (-500.0, 1e9)] {
|
||||
let got = run(&hue_sat(m, r), [0.8, 0.1, 0.2], depth);
|
||||
assert!(got.iter().all(|v| v.is_finite()), "{depth:?}, {m}, {r}: {got:?}");
|
||||
}
|
||||
let _ = run(&hue_sat(f32::NAN, f32::NAN), [0.8, 0.1, 0.2], depth);
|
||||
}
|
||||
}
|
||||
@@ -87,13 +87,8 @@ fn thirty_two_bit_hue_saturation_keeps_bright_colours() {
|
||||
let got = hdr(&adj, c);
|
||||
assert!(near(got, want), "hue {hue}, saturation {sat}, {c:?}: {got:?}, Photoshop {want:?}");
|
||||
}
|
||||
// A master plus a range edit that add up to a whole step stay on it: Reds +96 over a master
|
||||
// -46 scales red as much as a master +50 alone (in f32 the sum is 0.49999997).
|
||||
let mut ranges = HueRange::defaults();
|
||||
ranges[0].saturation = 96.0;
|
||||
let summed = Adjustment::HueSaturation { hue: 0.0, saturation: -46.0, lightness: 0.0, colorize: false, ranges };
|
||||
let single = Adjustment::HueSaturation { hue: 0.0, saturation: 50.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() };
|
||||
assert_eq!(hdr(&summed, [1.0, 0.0, 0.0]), hdr(&single, [1.0, 0.0, 0.0]));
|
||||
// A value a rounding error under a step stays on it: 0.49999997 is +50 %.
|
||||
assert_eq!(hdr_saturation_factor(0.49999997), hdr_saturation_factor(0.5));
|
||||
// Lightness 0 with a negative channel divides by zero the same way.
|
||||
let adj = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() };
|
||||
assert!(hdr(&adj, [0.25, -0.25, 0.0]).iter().all(|v| v.is_finite()));
|
||||
|
||||
@@ -258,6 +258,8 @@ mod inner_shadow_noise_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod outer_glow_noise_tests;
|
||||
#[cfg(test)]
|
||||
mod outer_glow_precise_edge_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -274,5 +276,8 @@ mod satin_size_one_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod inner_glow_size_one_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod inner_glow_noise_tests;
|
||||
#[cfg(test)]
|
||||
mod stroke_partial_alpha_tests;
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
//! #14926 - BUG-LAYER-STYLE-INNER-GLOW-NOISE-TOO-WEAK.
|
||||
//!
|
||||
//! Measured on the issue's test document: 400 x 300 px, RGB 8 bit, white Background, an orange
|
||||
//! (255, 128, 0) pixel layer covering x 100..299, y 75..224. Inner Glow black, Normal, 100 %,
|
||||
//! Softer, Source Edge, Choke 0, Size 10, Contour Linear, Range 50 %. The issue counts the G
|
||||
//! channel of the flattened top band y 75..83, x 110..289 (1620 px): G 128 is the layer's own
|
||||
//! orange (no glow), G 0 is full black glow. The shared `noise` law (#14936, #14952) leaves 244
|
||||
//! band pixels without glow at Noise 50, while the reference application shows 343.
|
||||
|
||||
use super::*;
|
||||
|
||||
const DOC_W: usize = 400;
|
||||
const DOC_H: usize = 300;
|
||||
|
||||
/// The layer's alpha over the whole document: solid over x 100..=299, y 75..=224.
|
||||
fn document_shape() -> Map {
|
||||
let mut m = Map::new(DOC_W, DOC_H, 0.0);
|
||||
for y in 75..=224 {
|
||||
for x in 100..=299 {
|
||||
m.v[y * DOC_W + x] = 1.0;
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// The issue's Inner Glow settings: black, Normal, 100 %, Softer, Source Edge, Choke 0, Size 10,
|
||||
/// Contour Linear, Range 50 %, Jitter 0, Anti-aliased off, Noise `noise`.
|
||||
fn glow(noise: f32) -> Glow {
|
||||
Glow {
|
||||
common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0),
|
||||
paint: FxPaint::Color(photocraft_color::Color::BLACK),
|
||||
technique: GlowTechnique::Softer,
|
||||
spread: 0.0,
|
||||
size: 10.0,
|
||||
contour: Contour::Linear,
|
||||
anti_alias: false,
|
||||
range: 0.5,
|
||||
jitter: 0.0,
|
||||
noise,
|
||||
source: GlowSource::Edge,
|
||||
}
|
||||
}
|
||||
|
||||
fn map(noise: f32) -> Map {
|
||||
glow_map(&document_shape(), &glow(noise), true, (0, 0))
|
||||
}
|
||||
|
||||
/// The G channel of the orange layer under a black Normal inner glow of coverage `c`.
|
||||
fn g_u8(c: f32) -> u8 {
|
||||
(128.0 * (1.0 - c)).round().clamp(0.0, 128.0) as u8
|
||||
}
|
||||
|
||||
/// The issue's band, y 75..=83 and x 110..=289 (1620 px), as G channel values.
|
||||
fn band(m: &Map) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(180 * 9);
|
||||
for y in 75..=83 {
|
||||
for x in 110..=289 {
|
||||
out.push(g_u8(m.get(x, y)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Done when: Noise 50 on that band leaves 260..430 pixels at G 128 (no glow at all), at most
|
||||
/// 30 pixels equal to the noiseless result, and reaches G 0. The shared law alone leaves 244.
|
||||
#[test]
|
||||
fn noise_fifty_scatters_the_glow_across_the_band() {
|
||||
let plain = band(&map(0.0));
|
||||
let noisy = band(&map(0.5));
|
||||
let gone = noisy.iter().filter(|v| **v == 128).count();
|
||||
let equal = noisy.iter().zip(&plain).filter(|(a, b)| a == b).count();
|
||||
let min = noisy.iter().copied().min().unwrap_or(128);
|
||||
assert!((260..=430).contains(&gone), "Noise 50: {gone} pixels without glow, want 260..430 (reference: 343)");
|
||||
assert!(equal <= 30, "Noise 50: {equal} pixels equal to the noiseless result, want at most 30 (reference: 8)");
|
||||
assert_eq!(min, 0, "Noise 50: minimum G {min}, want 0");
|
||||
}
|
||||
|
||||
/// Done when: Noise 100 leaves 400..580 pixels at G 128 (reference: 490).
|
||||
#[test]
|
||||
fn noise_hundred_thins_the_glow_further() {
|
||||
let noisy = band(&map(1.0));
|
||||
let gone = noisy.iter().filter(|v| **v == 128).count();
|
||||
assert!((400..=580).contains(&gone), "Noise 100: {gone} pixels without glow, want 400..580 (reference: 490)");
|
||||
}
|
||||
|
||||
/// Done when: the interior beyond the glow's reach stays G 128 at every Noise.
|
||||
#[test]
|
||||
fn noise_keeps_the_interior_beyond_the_glow_clean() {
|
||||
let plain = map(0.0);
|
||||
for noise in [0.25f32, 0.5, 1.0] {
|
||||
let noisy = map(noise);
|
||||
for y in (100..=200).step_by(5) {
|
||||
for x in (130..=270).step_by(7) {
|
||||
assert_eq!(plain.get(x, y), 0.0, "noiseless coverage at ({x},{y}) is not empty");
|
||||
assert_eq!(noisy.get(x, y), 0.0, "noise {noise} lit up ({x},{y}): {}", noisy.get(x, y));
|
||||
assert_eq!(g_u8(noisy.get(x, y)), 128, "noise {noise} moved the interior at ({x},{y}) off 128");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Done when: the same settings give the identical image twice.
|
||||
#[test]
|
||||
fn the_same_noise_renders_identically_twice() {
|
||||
for noise in [0.5f32, 1.0] {
|
||||
let a = map(noise);
|
||||
let b = map(noise);
|
||||
assert_eq!(a.v, b.v, "noise {noise} is not deterministic");
|
||||
}
|
||||
}
|
||||
|
||||
/// Noise that is not a positive number leaves the glow exactly as Noise 0 does, and the inner
|
||||
/// strength does not reach the Outer Glow, whose band was measured on the shared law (#14952).
|
||||
#[test]
|
||||
fn odd_noise_values_and_outer_glows_keep_the_shared_law() {
|
||||
let plain = map(0.0);
|
||||
for odd in [-0.5f32, f32::NAN, f32::INFINITY] {
|
||||
assert_eq!(map(odd).v, plain.v, "noise {odd} changed the inner glow");
|
||||
}
|
||||
let shape = document_shape();
|
||||
let outer = glow_map(&shape, &glow(0.0), false, (0, 0));
|
||||
let mut by_law = outer.clone();
|
||||
noise(&mut by_law, 0.5, 0, 0);
|
||||
assert_eq!(glow_map(&shape, &glow(0.5), false, (0, 0)).v, by_law.v, "the outer glow left the shared law");
|
||||
}
|
||||
|
||||
/// A hash over every coverage value of a map: the map is bit-for-bit unchanged iff this is.
|
||||
fn bit_hash(m: &Map) -> u64 {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for v in &m.v {
|
||||
h = (h ^ u64::from(v.to_bits())).wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// Noise 0 stays bit-identical: the whole-map FNV hash `glow_map` gives for the issue's
|
||||
/// document with Noise 0 on origin/main.
|
||||
#[test]
|
||||
fn noise_zero_maps_stay_bit_identical() {
|
||||
assert_eq!(bit_hash(&map(0.0)), 0xefad_fffb_8195_d0b9, "the Noise 0 inner glow map moved");
|
||||
}
|
||||
|
||||
/// The Centre source and the Precise technique were not measured, so they keep the shared law at every Noise: only
|
||||
/// the measured Softer, Edge-sourced Inner Glow gets the stronger mid-Noise scatter.
|
||||
#[test]
|
||||
fn unmeasured_centre_and_precise_inner_glows_keep_the_shared_law() {
|
||||
let shape = document_shape();
|
||||
let centre = |noise| Glow { source: GlowSource::Center, ..glow(noise) };
|
||||
let precise = |noise| Glow { technique: GlowTechnique::Precise, ..glow(noise) };
|
||||
let precise_centre = |noise| Glow { technique: GlowTechnique::Precise, source: GlowSource::Center, ..glow(noise) };
|
||||
for (name, make) in [("Centre", ¢re as &dyn Fn(f32) -> Glow), ("Precise", &precise), ("Precise Centre", &precise_centre)] {
|
||||
for amount in [0.25f32, 0.5] {
|
||||
let mut by_law = glow_map(&shape, &make(0.0), true, (0, 0));
|
||||
noise(&mut by_law, amount, 0, 0);
|
||||
assert_eq!(glow_map(&shape, &make(amount), true, (0, 0)).v, by_law.v, "{name}, Noise {amount}: left the shared law");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! #15006 - Outer Glow: a flat-contour Precise band's outermost pixel is soft on a pixel-aligned
|
||||
//! edge.
|
||||
//!
|
||||
//! Measured on the issue's document: 60 x 60 px, transparent, a black 20 x 20 square at x/y
|
||||
//! 20..39. Outer Glow Normal 100 %, Precise, Spread 0, Size 4 px, Range 50 %, custom flat contour
|
||||
//! (0,255)-(255,255), Anti-aliased off. Along row 30, x 14 and 15 read alpha 0, x 16 (4 px out)
|
||||
//! 213 and x 17..19 255. On the diagonal, (16, 16) reads 0, (17, 17) 161 and (18, 18) 255.
|
||||
|
||||
use super::{Contour, Effect, FxPaint, Glow, GlowSource, GlowTechnique};
|
||||
use photocraft_color::{BlendMode, Color, ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, FxCommon, Layer, adjust::CurvePoint};
|
||||
use photocraft_geom::{Rect, Size};
|
||||
|
||||
fn outer_glow(contour: Contour) -> Glow {
|
||||
Glow {
|
||||
common: FxCommon::new(BlendMode::Normal, 1.0),
|
||||
paint: FxPaint::Color(Color::BLACK),
|
||||
technique: GlowTechnique::Precise,
|
||||
spread: 0.0,
|
||||
size: 4.0,
|
||||
contour,
|
||||
anti_alias: false,
|
||||
range: 0.5,
|
||||
jitter: 0.0,
|
||||
noise: 0.0,
|
||||
source: GlowSource::Edge,
|
||||
}
|
||||
}
|
||||
|
||||
fn flat() -> Contour {
|
||||
Contour::Custom { name: "Flat".into(), points: vec![CurvePoint { input: 0.0, output: 1.0 }, CurvePoint { input: 1.0, output: 1.0 }], corners: vec![] }
|
||||
}
|
||||
|
||||
fn alphas(glow: Glow) -> impl Fn(i32, i32) -> u8 {
|
||||
let mut doc = Document::new("Outer glow", Size::new(60, 60), ColorMode::Rgb, SampleType::U8);
|
||||
let mut layer = Layer::raster("Square", doc.pixel_format());
|
||||
layer.surface_mut().unwrap().fill_rect(Rect::new(20, 20, 40, 40), &[0.0, 0.0, 0.0, 1.0]);
|
||||
layer.effects.items.push(Effect::OuterGlow(glow));
|
||||
doc.layers.push(layer);
|
||||
let image = crate::flatten(&doc);
|
||||
move |x, y| (image.get(x, y)[3] * 255.0).round() as u8
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pixel_at_size_px_out_is_soft() {
|
||||
let alpha = alphas(outer_glow(flat()));
|
||||
for (x, expected) in [(14, 0), (15, 0), (17, 255), (18, 255), (19, 255)] {
|
||||
assert_eq!(alpha(x, 30), expected, "x {x}");
|
||||
}
|
||||
let edge = alpha(16, 30);
|
||||
assert!(edge.abs_diff(213) <= 3, "x 16, 4 px out: expected 213, got {edge}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_corner_diagonal_fades_the_same_way() {
|
||||
let alpha = alphas(outer_glow(flat()));
|
||||
assert_eq!(alpha(16, 16), 0);
|
||||
assert_eq!(alpha(18, 18), 255);
|
||||
let diagonal = alpha(17, 17);
|
||||
assert!(diagonal.abs_diff(161) <= 5, "(17, 17), √18 px out: expected 161, got {diagonal}");
|
||||
}
|
||||
@@ -109,9 +109,9 @@ fn softer_edge_floor(size: f32) -> f32 {
|
||||
/// rounded down to a table entry for both techniques); the coverage where it reaches 1 is per
|
||||
/// technique:
|
||||
///
|
||||
/// - Precise: the falloff is linear in distance, so the edge is the distance left to the reach's
|
||||
/// end: the last pixel steps down by how far inside the reach its centre is (one soft pixel,
|
||||
/// as Photoshop's flat-contour band).
|
||||
/// - Precise: a fixed coverage, [`PRECISE_FULL_COVERAGE`]. The falloff is linear in distance, so
|
||||
/// at Spread 0 the band fades over its last `0.24 · (size + 1)` px: about one soft pixel at
|
||||
/// Size 4, two to three at Size 10, as Photoshop's flat-contour band.
|
||||
/// - Softer: coverage is a tent blur, and the same coverage means a different distance for a
|
||||
/// straight edge and a single pixel, so no coverage-only model gives the distance. The edge
|
||||
/// reaches 1 at the coverage one opaque pixel gives one pixel inside its reach along a row
|
||||
@@ -122,7 +122,7 @@ fn softer_edge_floor(size: f32) -> f32 {
|
||||
/// So:
|
||||
///
|
||||
/// - coverage 0 always paints 0, for any contour (nothing beyond the reach);
|
||||
/// - a high contour is solid up to the last pixel of the reach, which steps down;
|
||||
/// - a high contour is solid up to the outer pixels of the reach, which step down;
|
||||
/// - it never paints less than the Linear contour would, so a contour that already follows or
|
||||
/// stays under the falloff (Linear, or a custom curve with `contour(0) = 0` rising no faster
|
||||
/// than the reach edge) is unchanged. The reach does not depend on Range: Range stretches the
|
||||
@@ -151,6 +151,14 @@ pub fn glow_paint_lut(g: &Glow, inner: bool) -> Option<Vec<f32>> {
|
||||
)
|
||||
}
|
||||
|
||||
/// The Precise coverage at which a high contour's reach edge paints in full (#15006), whatever
|
||||
/// the Size: with `v = ½·(1 − (d − solid) / soft)`, Photoshop paints `v / 0.12`. Measured at
|
||||
/// Range 50 %, Spread 0: Size 4 at 4 px out (a pixel-aligned edge) 213 of 255 and at √18 px (a
|
||||
/// corner's diagonal) 161; Size 10, #11361's ellipse row `153, 120, 92` (this gives
|
||||
/// `155, 123, 92`). Other Ranges and Spreads are unmeasured. Tying the knee to the distance
|
||||
/// instead (`1 / (2·soft)`, the reach's last pixel) left the pixel at Size px out solid.
|
||||
const PRECISE_FULL_COVERAGE: f32 = 0.12;
|
||||
|
||||
/// Entries in a glow's transfer table: the GPU's `compose.wgsl` `lut` reads 4096, linearly
|
||||
/// interpolated, as the CPU's [`lut_at`] does.
|
||||
const GLOW_LUT_LEN: usize = 4096;
|
||||
@@ -170,16 +178,11 @@ fn glow_reach_edge(per_coverage: f32, v: f32) -> f32 {
|
||||
/// coverage rounded down to a whole table step (at least one), so the knee lands on a table entry
|
||||
/// and the table interpolates the edge exactly (rounding down only widens what paints in full).
|
||||
///
|
||||
/// - Precise: `v = ½·(1 − (d − solid) / soft)`, which reaches 0 at `d = size + 1` (centre to
|
||||
/// centre), so the distance left to the reach's end is `size + 1 − d = 2·soft·v`: full at
|
||||
/// `v = 1 / (2·soft)`.
|
||||
/// - Precise: full at [`PRECISE_FULL_COVERAGE`].
|
||||
/// - Softer: full at [`softer_full_coverage`].
|
||||
fn glow_edge_per_coverage(g: &Glow) -> f32 {
|
||||
let full = match g.technique {
|
||||
GlowTechnique::Precise => {
|
||||
let solid = g.size * g.spread;
|
||||
0.5 / (g.size + 1.0 - solid).max(1e-3)
|
||||
}
|
||||
GlowTechnique::Precise => PRECISE_FULL_COVERAGE,
|
||||
GlowTechnique::Softer => softer_full_coverage(spread_split(g.size, g.spread).1),
|
||||
};
|
||||
let steps = (GLOW_LUT_LEN - 1) as f32;
|
||||
@@ -582,7 +585,13 @@ pub(super) fn glow_map(shape: &Map, g: &Glow, inner: bool, origin: (i32, i32)) -
|
||||
if inner && g.source == GlowSource::Center {
|
||||
m = m.map(|v| 1.0 - v);
|
||||
}
|
||||
noise(&mut m, g.noise, origin.0, origin.1);
|
||||
// #14926: an Inner Glow scatters harder at mid Noise than the shared law gives (measured
|
||||
// band: Noise 50 leaves 343 of 1620 px without glow, Noise 100 490). The square root keeps
|
||||
// Noise 0 and Noise 100 where they are and lifts Noise 50 to the law's 0.71 (about 340 px).
|
||||
// Only the measured Softer, Edge-sourced case; Centre and Precise keep the shared law.
|
||||
let measured = inner && g.technique == GlowTechnique::Softer && g.source == GlowSource::Edge;
|
||||
let amount = if measured && g.noise > 0.0 { g.noise.sqrt() } else { g.noise };
|
||||
noise(&mut m, amount, origin.0, origin.1);
|
||||
if inner {
|
||||
for (v, a) in m.v.iter_mut().zip(&shape.v) {
|
||||
*v *= a;
|
||||
|
||||
@@ -1004,8 +1004,8 @@ fn flat_contour_outer_glow_is_a_solid_band_with_one_soft_pixel() {
|
||||
let n = 60;
|
||||
let at = |m: &Map, x: usize| m.v[30 * n + x];
|
||||
// Precise, with the square's left column half covered: its edge sits mid-pixel, so the
|
||||
// pixels out from it are 1.5, 2.5, 3.5, 4.5, 5.5 px (centre to centre) from the shape, and
|
||||
// the reach (size + 1 = 5) ends half-way across the 4.5 px one.
|
||||
// pixels out from it are 1.5, 2.5, 3.5, 4.5, 5.5 px (centre to centre) from the shape. The
|
||||
// 4.5 px one has coverage 0.05, which the 0.12 knee (#15006) paints at 5/12.
|
||||
let mut shape = square_20_40();
|
||||
for y in 20..40 {
|
||||
shape.v[y * n + 19] = 0.5;
|
||||
@@ -1014,18 +1014,17 @@ fn flat_contour_outer_glow_is_a_solid_band_with_one_soft_pixel() {
|
||||
for x in 16..=19 {
|
||||
assert!(at(&m, x) > 0.999, "precise, solid band at x {x}: {}", at(&m, x));
|
||||
}
|
||||
assert!((at(&m, 15) - 0.5).abs() < 0.05, "precise, the soft outer pixel: {}", at(&m, 15));
|
||||
assert!((at(&m, 15) - 5.0 / 12.0).abs() < 0.01, "precise, the soft outer pixel: {}", at(&m, 15));
|
||||
assert!(at(&m, 14) == 0.0 && at(&m, 0) == 0.0, "precise, beyond the reach: {} {}", at(&m, 14), at(&m, 0));
|
||||
// Precise, pixel-aligned edge: the pixels out from it are 1..5 px (centre to centre) from the
|
||||
// shape and the reach ends at the 5 px one's centre, so the band is solid through Size (x 16,
|
||||
// 4 px out, 1.0) and the next pixel (x 15) is beyond it. Point-sampled, as the measured Linear
|
||||
// falloff is: an area-averaged falloff would leave x 15 half covered (the reach ends 4.5 px
|
||||
// past the shape's edge, half-way across it), not 0.84.
|
||||
// shape and the reach ends at the 5 px one's centre. Photoshop's x 16 (4 px out, coverage
|
||||
// 0.1) reads 213 of 255 (#15006), and x 15 is beyond the reach.
|
||||
let shape = square_20_40();
|
||||
let m = glow_map(&shape, &contour_glow(GlowTechnique::Precise, 4.0, &FLAT), false, (0, 0));
|
||||
for x in 16..20 {
|
||||
for x in 17..20 {
|
||||
assert!(at(&m, x) > 0.999, "precise aligned, solid band at x {x}: {}", at(&m, x));
|
||||
}
|
||||
assert!((at(&m, 16) * 255.0 - 213.0).abs() <= 1.0, "precise aligned, the soft outer pixel: {}", at(&m, 16));
|
||||
assert!(at(&m, 15) == 0.0, "precise aligned, beyond the reach: {}", at(&m, 15));
|
||||
// Softer, size 4: the tent's last tap (1/64, at x 16) is above what one opaque pixel gives one
|
||||
// pixel inside its reach (t[3]·t[0] ≈ 0.0137), so a straight edge is solid through its reach.
|
||||
|
||||
@@ -87,6 +87,8 @@ pub mod layer_label_cmds;
|
||||
pub mod layer_list_cmds;
|
||||
pub mod layer_mask_props_cmds;
|
||||
pub mod layer_menu_cmds;
|
||||
#[cfg(test)]
|
||||
mod layer_merge_clipping_mask_tests;
|
||||
pub mod layer_multi_cmds;
|
||||
pub mod layer_nav_cmds;
|
||||
mod layer_params;
|
||||
|
||||
@@ -537,6 +537,33 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> {
|
||||
s.active().map(|_| ()).ok_or_else(|| "no document open".into())
|
||||
}
|
||||
|
||||
/// HDR Toning is greyed with an active selection and in CMYK, Lab and Indexed Color documents
|
||||
/// (#14735). RGB and Grayscale keep it; Duotone and Multichannel were not measured and keep
|
||||
/// today's behaviour (`Session::precondition` refuses Bitmap for every adjustment but Invert).
|
||||
fn hdr_toning_enabled(s: &Session) -> std::result::Result<(), String> {
|
||||
let d = s.active().ok_or("no document open")?;
|
||||
// The mode comes first: deselecting can't fix it.
|
||||
if let Some(reason) = hdr_toning_mode_refusal(d.doc.mode) {
|
||||
return Err(reason);
|
||||
}
|
||||
if d.doc.selection.is_some() {
|
||||
return Err("HDR Toning works on the whole image: deselect first".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A document mode that excludes HDR Toning even when the composite channel is targeted.
|
||||
pub(crate) fn hdr_toning_mode_refusal(mode: photocraft_color::ColorMode) -> Option<String> {
|
||||
use photocraft_color::ColorMode;
|
||||
let label = match mode {
|
||||
ColorMode::Cmyk => "CMYK Color",
|
||||
ColorMode::Lab => "Lab Color",
|
||||
ColorMode::Indexed => "Indexed Color",
|
||||
_ => return None,
|
||||
};
|
||||
Some(format!("HDR Toning needs an RGB or Grayscale document (this one is {label})"))
|
||||
}
|
||||
|
||||
// ---------- commands ----------
|
||||
|
||||
/// Image › Adjustments run as a smart filter (`image.adjustments.<kind>` recorded on a smart
|
||||
@@ -861,7 +888,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"HDR Toning…",
|
||||
["Image", "Adjustments"],
|
||||
r##"{"radius":1..500=30,"strength":0.1..4=0.5,"gamma":0.1..2=1,"exposure":-5..5=0,"detail":-100..300=30,"shadow":-100..100=0,"highlight":-100..100=0,"vibrance":-100..100=0,"saturation":-100..100=20,"curve":[[in,out],…] 0..255} (flattens the image)"##,
|
||||
has_doc,
|
||||
hdr_toning_enabled,
|
||||
hdr_toning
|
||||
),
|
||||
CommandSpec {
|
||||
@@ -1011,6 +1038,8 @@ fn black_white_auto(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Object(crate::adjust_params::HUE_RANGES.iter().zip(w).map(|(k, v)| ((*k).to_string(), json!(v))).collect()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod hdr_toning_enabled_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Image > Adjustments > HDR Toning is greyed with an active selection and in CMYK, Lab and
|
||||
//! Indexed Color documents (#14735), stays available in RGB at 8, 16 and 32 bit and Grayscale 8
|
||||
//! bit (keeping the mode and depth), and Duotone, Multichannel and deeper Grayscale (not measured)
|
||||
//! keep today's behaviour.
|
||||
|
||||
use crate::Session;
|
||||
use serde_json::json;
|
||||
|
||||
const HDR: &str = "image.adjustments.hdrToning";
|
||||
|
||||
fn new_doc(mode: &str, depth: u32) -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "mode": mode, "depth": depth, "background": "white"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn assert_refused(mut s: Session, what: &str) {
|
||||
assert!(!s.is_enabled(HDR), "{what}: the menu entry is greyed out");
|
||||
let d = s.active().unwrap();
|
||||
let (steps, selection, mode) = (d.history.past_len(), d.doc.selection.clone(), d.doc.mode);
|
||||
assert!(s.execute(HDR, json!({})).is_err(), "{what}: running it is refused");
|
||||
let d = s.active().unwrap();
|
||||
assert_eq!(d.history.past_len(), steps, "{what}: no history state");
|
||||
assert_eq!(d.doc.selection, selection, "{what}: the selection stays");
|
||||
assert_eq!(d.doc.mode, mode, "{what}: the mode stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_active_selection_refuses_hdr_toning() {
|
||||
let mut s = new_doc("rgb", 8);
|
||||
s.execute("select.all", json!({})).unwrap();
|
||||
assert!(s.active().unwrap().doc.selection.is_some());
|
||||
assert_refused(s, "RGB with a selection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_lab_and_indexed_documents_refuse_hdr_toning() {
|
||||
assert_refused(new_doc("cmyk", 8), "CMYK 8 bit");
|
||||
assert_refused(new_doc("lab", 8), "Lab 8 bit");
|
||||
let mut indexed = new_doc("rgb", 8);
|
||||
indexed.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap();
|
||||
assert_refused(indexed, "Indexed Color");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targeted_hdr_toning_names_the_unsupported_mode_before_the_channel() {
|
||||
let mut indexed = new_doc("rgb", 8);
|
||||
indexed.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap();
|
||||
let target = json!({"target": {"color": 0}});
|
||||
for (mut s, reason) in [
|
||||
(new_doc("cmyk", 8), "CMYK Color"),
|
||||
(new_doc("lab", 8), "Lab Color"),
|
||||
(indexed, "Indexed Color"),
|
||||
(new_doc("rgb", 8), "requires the composite channel"),
|
||||
] {
|
||||
let disabled = s.disabled_reason_with(HDR, &target).unwrap();
|
||||
assert!(disabled.contains(reason), "{disabled}");
|
||||
let error = s.execute(HDR, target.clone()).unwrap_err().to_string();
|
||||
assert!(error.contains(reason), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgb_all_depths_and_grayscale_8_bit_keep_hdr_toning_and_their_mode_and_depth() {
|
||||
for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 8)] {
|
||||
let mut s = new_doc(mode, depth);
|
||||
assert!(s.is_enabled(HDR), "{mode} {depth} bit");
|
||||
let d = s.active().unwrap();
|
||||
let (steps, before_mode, before_depth) = (d.history.past_len(), d.doc.mode, d.doc.depth);
|
||||
s.execute(HDR, json!({})).unwrap();
|
||||
let d = s.active().unwrap();
|
||||
assert_eq!(d.history.past_len(), steps + 1, "{mode} {depth} bit: one history state");
|
||||
assert_eq!((d.doc.mode, d.doc.depth), (before_mode, before_depth), "{mode} {depth} bit keeps its mode and depth");
|
||||
}
|
||||
}
|
||||
|
||||
/// Not measured: Multichannel, Duotone and Grayscale at 16 and 32 bit keep today's behaviour.
|
||||
#[test]
|
||||
fn unmeasured_documents_keep_todays_behaviour() {
|
||||
let mut multi = new_doc("rgb", 8);
|
||||
multi.execute("image.mode.multichannel", json!({})).unwrap();
|
||||
assert!(multi.is_enabled(HDR), "Multichannel");
|
||||
|
||||
let mut duotone = new_doc("grayscale", 8);
|
||||
duotone
|
||||
.edit("duotone", |d, _| {
|
||||
d.mode = photocraft_color::ColorMode::Duotone;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(duotone.is_enabled(HDR), "Duotone");
|
||||
|
||||
for depth in [16, 32] {
|
||||
assert!(new_doc("grayscale", depth).is_enabled(HDR), "Grayscale {depth} bit");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_refusals_say_why() {
|
||||
let why = super::hdr_toning_enabled(&new_doc("lab", 8)).unwrap_err();
|
||||
assert!(why.contains("Lab Color"), "{why}");
|
||||
let mut s = new_doc("rgb", 8);
|
||||
s.execute("select.all", json!({})).unwrap();
|
||||
let why = super::hdr_toning_enabled(&s).unwrap_err();
|
||||
assert!(why.contains("deselect"), "{why}");
|
||||
// A CMYK document with a selection names the mode: deselecting would not help.
|
||||
let mut s = new_doc("cmyk", 8);
|
||||
s.execute("select.all", json!({})).unwrap();
|
||||
let why = super::hdr_toning_enabled(&s).unwrap_err();
|
||||
assert!(why.contains("CMYK Color"), "{why}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_document_is_unchanged() {
|
||||
let mut s = crate::session();
|
||||
assert!(!s.is_enabled(HDR));
|
||||
assert_eq!(super::hdr_toning_enabled(&s).unwrap_err(), "no document open");
|
||||
assert!(s.execute(HDR, json!({})).is_err());
|
||||
}
|
||||
@@ -57,7 +57,14 @@ fn destructive_adjustments_all_depths_and_modes_one_undo_step() {
|
||||
for (id, params) in &cases {
|
||||
for depth in DEPTHS {
|
||||
for mode in MODES {
|
||||
// CMYK and Lab documents grey HDR Toning (#14735, hdr_toning_enabled_tests).
|
||||
let mut s = session(depth, mode);
|
||||
if id.ends_with("hdrToning") && matches!(mode, "cmyk" | "lab") {
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
assert!(s.execute(id, params.clone()).is_err(), "{id} {depth} {mode}: refused");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), steps, "{id} {depth} {mode}: no history step");
|
||||
continue;
|
||||
}
|
||||
let before = rgba(&s, 3, 3);
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
s.execute(id, params.clone()).unwrap_or_else(|e| panic!("{id} {depth} {mode}: {e}"));
|
||||
|
||||
@@ -296,8 +296,10 @@ fn set_scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
other => return Err(bad(CMD, format!("unknown preset `{other}` (default|custom)"))),
|
||||
};
|
||||
if next != cur {
|
||||
// The reference names the step after the submenu entry that made it (#17410).
|
||||
let label = if preset == "default" { "Set Default Measurement Scale" } else { "Custom Measurement Scale" };
|
||||
let n = next.clone();
|
||||
s.edit("Set Measurement Scale", move |d, _| {
|
||||
s.edit(label, move |d, _| {
|
||||
d.measurement.scale = n;
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -1460,4 +1462,6 @@ mod data_points_one_list_tests;
|
||||
#[cfg(test)]
|
||||
mod record_no_data_points_tests;
|
||||
#[cfg(test)]
|
||||
mod scale_history_names_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//! History step names of Image › Analysis › Set Measurement Scale, measured against the reference
|
||||
//! application (#17410): Custom (the dialog, a preset, a script set) adds one step "Custom
|
||||
//! Measurement Scale", Default adds one step "Set Default Measurement Scale", and a call that
|
||||
//! leaves the scale as it is adds no step.
|
||||
|
||||
use super::*;
|
||||
|
||||
const CMD: &str = "image.analysis.setMeasurementScale";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.past_len()
|
||||
}
|
||||
|
||||
fn last_step(s: &Session) -> String {
|
||||
s.active().unwrap().history.entries().last().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_and_bare_values_add_one_custom_step() {
|
||||
for p in [
|
||||
json!({"preset": "custom", "pixelLength": 100, "logicalLength": 2.5, "units": "cm"}),
|
||||
json!({"pixelLength": 100, "logicalLength": 2.5, "units": "cm"}),
|
||||
json!({"units": "mm"}),
|
||||
] {
|
||||
let mut s = session();
|
||||
let before = steps(&s);
|
||||
s.execute(CMD, p.clone()).unwrap();
|
||||
assert_eq!(steps(&s), before + 1, "{p}");
|
||||
assert_eq!(last_step(&s), "Custom Measurement Scale", "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_adds_one_default_step() {
|
||||
let mut s = session();
|
||||
s.execute(CMD, json!({"pixelLength": 10, "logicalLength": 1, "units": "cm"})).unwrap();
|
||||
let before = steps(&s);
|
||||
s.execute(CMD, json!({"preset": "default"})).unwrap();
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
assert_eq!(last_step(&s), "Set Default Measurement Scale");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_scale_adds_no_step() {
|
||||
let mut s = session();
|
||||
let before = steps(&s);
|
||||
s.execute(CMD, json!({"preset": "default"})).unwrap();
|
||||
assert_eq!(steps(&s), before, "Default on a default scale");
|
||||
let p = json!({"pixelLength": 10, "logicalLength": 1, "units": "cm"});
|
||||
s.execute(CMD, p.clone()).unwrap();
|
||||
let before = steps(&s);
|
||||
s.execute(CMD, p).unwrap();
|
||||
assert_eq!(steps(&s), before, "the same custom values again");
|
||||
}
|
||||
@@ -86,6 +86,13 @@ fn background_from_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
convertible(l).map_err(EngineError::Other)?;
|
||||
// Keep the one measured clipped sibling with its top-level base. Leave nested
|
||||
// targets and stacks with several clipped layers on the existing path.
|
||||
let mut above = doc.layers.iter().skip_while(|layer| layer.id != id).skip(1);
|
||||
let clipped = match (above.next(), above.next()) {
|
||||
(Some(layer), next) if !l.clipped && layer.clipped && !next.is_some_and(|layer| layer.clipped) => Some(layer.id),
|
||||
_ => None,
|
||||
};
|
||||
// Render the layer alone, as it looks (mask, opacity and effects applied), over the
|
||||
// background colour: the Background is opaque and plain.
|
||||
let mut only = l.clone();
|
||||
@@ -104,6 +111,10 @@ fn background_from_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
*crate::pixels_mut(&mut out)? = pixels;
|
||||
doc.remove(id).ok_or(EngineError::NoLayer(id))?;
|
||||
doc.layers.insert(0, out);
|
||||
if let Some(clipped) = clipped {
|
||||
let layer = doc.remove(clipped).ok_or(EngineError::NoLayer(clipped))?;
|
||||
doc.layers.insert(1, layer);
|
||||
}
|
||||
*active = Some(id);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -164,7 +164,7 @@ pub(super) fn quick_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let opts = s.quick_mask_options;
|
||||
if want {
|
||||
s.edit("Edit in Quick Mask", |doc, _| {
|
||||
s.edit("Enter Quick Mask", |doc, _| {
|
||||
doc.quick_mask = Some(quick_mask_from(doc, &opts));
|
||||
doc.quick_mask_unselected = doc.selection.is_none();
|
||||
doc.selection = None;
|
||||
|
||||
@@ -370,7 +370,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Edit"],
|
||||
None,
|
||||
r##"{"name":text}"##,
|
||||
|s| if s.is_enabled("brush.defineFromSelection") { Ok(()) } else { Err("select pixels to define a brush from".into()) },
|
||||
|s| s.disabled_reason("brush.defineFromSelection").map_or(Ok(()), Err),
|
||||
define_brush_preset
|
||||
),
|
||||
spec!(
|
||||
|
||||
@@ -5,14 +5,20 @@ use photocraft_doc::vector::PathOp;
|
||||
// ------------------------------------------------------------------ Define Brush / Custom Shape
|
||||
|
||||
pub(super) fn define_brush_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = match p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) {
|
||||
Some(n) => n.to_string(),
|
||||
None => {
|
||||
let n = s.tools.presets.iter().filter(|b| b.name.starts_with("Sampled Brush")).count() + 1;
|
||||
format!("Sampled Brush {n}")
|
||||
}
|
||||
};
|
||||
s.execute("brush.defineFromSelection", json!({"name": name}))
|
||||
let typed = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty());
|
||||
// The default counts the defaults stored this session; presets that merely share the name don't raise it (#18228). A
|
||||
// number a preset already uses is skipped, since storing under that name would replace that preset; the store matches
|
||||
// names ignoring ASCII case, so this does too.
|
||||
let mut number = s.tools.sampled_brushes.saturating_add(1);
|
||||
while typed.is_none() && s.tools.presets.iter().any(|b| b.name.eq_ignore_ascii_case(&format!("Sampled Brush {number}"))) {
|
||||
number = number.saturating_add(1);
|
||||
}
|
||||
let name = typed.map_or_else(|| format!("Sampled Brush {number}"), str::to_string);
|
||||
let defined = s.execute("brush.defineFromSelection", json!({"name": name}))?;
|
||||
if typed.is_none() {
|
||||
s.tools.sampled_brushes = number;
|
||||
}
|
||||
Ok(defined)
|
||||
}
|
||||
|
||||
/// The path Define Custom Shape uses: `"work"`, a saved path name, else the work path, the
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
//! #18481: `Ctrl+E` (`layer.mergeLayers`) with the base of a clip group alone selected is Merge Clipping Mask: the base
|
||||
//! and the layers clipped to it become one layer with the base's identity, name, place, blend mode and opacity; the
|
||||
//! composite does not change, and clipped pixels outside the base are gone. Other layers, and the cases the issue did
|
||||
//! not measure, keep Merge Down.
|
||||
|
||||
use photocraft_doc::{BlendMode, LayerId};
|
||||
use photocraft_geom::Rect;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// `Top` (blue, wider than `Red`) clipped onto `Red`, `Masked` below, on a white Background; `Red` active.
|
||||
fn clip_group() -> (Session, LayerId) {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 60, "height": 40, "background": "#ffffff"})).unwrap();
|
||||
let fill = |s: &mut Session, name: &str, rect: Rect, color: [f32; 4]| {
|
||||
s.execute("layer.new.layer", json!({"name": name})).unwrap();
|
||||
s.edit("Paint", |doc, active| {
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(rect, &color);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.active().unwrap().active_layer.unwrap()
|
||||
};
|
||||
fill(&mut s, "Masked", Rect::new(0, 20, 60, 40), [0.0, 0.6, 0.0, 1.0]);
|
||||
let red = fill(&mut s, "Red", Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]);
|
||||
fill(&mut s, "Top", Rect::new(20, 0, 50, 25), [0.0, 0.0, 1.0, 0.7]);
|
||||
s.execute("layer.createClippingMask", json!({})).unwrap();
|
||||
s.execute("layer.select", json!({"layer": red.0})).unwrap();
|
||||
(s, red)
|
||||
}
|
||||
|
||||
fn names(s: &Session) -> Vec<String> {
|
||||
s.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect()
|
||||
}
|
||||
|
||||
fn flat(s: &Session) -> Vec<[f32; 4]> {
|
||||
photocraft_compose::flatten(&s.active().unwrap().doc).into_px()
|
||||
}
|
||||
|
||||
fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 {
|
||||
a.iter().zip(b).flat_map(|(p, q)| (0..4).map(move |c| (p[c] - q[c]).abs())).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
fn undo_label(s: &Session) -> String {
|
||||
s.active().unwrap().history.undo_label().unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// The merged layer's pixel at canvas `(x, y)`.
|
||||
fn pixel(s: &Session, id: LayerId, x: i32, y: i32) -> Vec<f32> {
|
||||
s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().pixel(x, y)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_e_on_a_clip_base_merges_the_clipped_layers_into_it() {
|
||||
let (mut s, red) = clip_group();
|
||||
let before = flat(&s);
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
|
||||
s.execute("layer.mergeLayers", json!({})).unwrap();
|
||||
|
||||
assert!(!names(&s).contains(&"Top".to_string()), "Top is merged: {:?}", names(&s));
|
||||
assert!(names(&s).contains(&"Masked".to_string()), "Masked is untouched: {:?}", names(&s));
|
||||
let d = s.active().unwrap();
|
||||
let merged = d.doc.layer(red).expect("the result keeps the base's id");
|
||||
assert_eq!(merged.name, "Red");
|
||||
assert!(!merged.clipped);
|
||||
assert_eq!(d.active_layer, Some(red));
|
||||
assert_eq!(d.history.past_len(), steps + 1, "one History state");
|
||||
assert_eq!(undo_label(&s), "Merge Clipping Mask");
|
||||
assert!(max_diff(&before, &flat(&s)) < 1e-3, "the composite does not change");
|
||||
|
||||
// Inside the base the blue is blended over the red; outside the base the clipped blue is gone.
|
||||
let inside = pixel(&s, red, 25, 15);
|
||||
assert!(inside[2] > inside[0] && inside[3] > 0.99, "{inside:?}");
|
||||
assert!(pixel(&s, red, 40, 5)[3] < 1e-3, "clipped pixels outside the base are dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_result_keeps_the_bases_blend_mode_and_opacity() {
|
||||
let (mut s, red) = clip_group();
|
||||
s.execute("layer.setProps", json!({"blend": "Multiply", "opacity": 0.6})).unwrap();
|
||||
let before = flat(&s);
|
||||
|
||||
s.execute("layer.mergeLayers", json!({})).unwrap();
|
||||
|
||||
let merged = s.active().unwrap().doc.layer(red).unwrap().clone();
|
||||
assert_eq!(merged.blend, BlendMode::Multiply);
|
||||
assert!((merged.opacity - 0.6).abs() < 1e-3, "{}", merged.opacity);
|
||||
assert!(max_diff(&before, &flat(&s)) < 1e-3, "the composite does not change");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_that_is_not_a_clip_base_still_merges_down() {
|
||||
// The clipped layer itself, and a layer with nothing clipped to it.
|
||||
for name in ["Top", "Masked"] {
|
||||
let (mut s, _) = clip_group();
|
||||
let id = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap().2.id;
|
||||
s.execute("layer.select", json!({"layer": id.0})).unwrap();
|
||||
s.execute("layer.mergeLayers", json!({})).unwrap();
|
||||
assert_eq!(undo_label(&s), "Merge Down", "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Not measured in the issue: these keep today's Merge Down.
|
||||
#[test]
|
||||
fn a_base_with_a_layer_mask_or_inside_a_group_keeps_merge_down() {
|
||||
let (mut s, _) = clip_group();
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
s.execute("layer.mergeLayers", json!({})).unwrap();
|
||||
assert_eq!(undo_label(&s), "Merge Down", "a base with a layer mask");
|
||||
|
||||
let (mut s, red) = clip_group();
|
||||
let masked = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == "Masked").unwrap().2.id;
|
||||
let top = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == "Top").unwrap().2.id;
|
||||
s.execute("layer.select", json!({"layers": [masked.0, red.0, top.0]})).unwrap();
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
assert!(s.active().unwrap().doc.layer(top).unwrap().clipped, "Top is still clipped inside the group");
|
||||
s.execute("layer.select", json!({"layer": red.0})).unwrap();
|
||||
s.execute("layer.mergeLayers", json!({})).unwrap();
|
||||
assert_eq!(undo_label(&s), "Merge Down", "a base inside a group");
|
||||
}
|
||||
|
||||
/// A base whose Fill, Blend If, Advanced Blending or excluded channels the merged layer could not carry keeps Merge
|
||||
/// Down, so the composite is never changed by Merge Clipping Mask.
|
||||
#[test]
|
||||
fn a_base_with_settings_the_result_cannot_carry_keeps_merge_down() {
|
||||
type Set = fn(&mut photocraft_doc::Layer);
|
||||
let cases: [(&str, Set); 4] = [
|
||||
("Fill 50 %", |l| l.fill_opacity = 0.5),
|
||||
("Blend If", |l| l.blend_if.ranges = vec![[photocraft_doc::BlendRange { black: [0, 0], white: [128, 128] }, photocraft_doc::BlendRange::FULL]]),
|
||||
("Blend Clipped Layers as Group off", |l| l.advanced.blend_clipped = false),
|
||||
("an excluded channel", |l| l.excluded_channels = 1),
|
||||
];
|
||||
for (case, set) in cases {
|
||||
let (mut s, red) = clip_group();
|
||||
s.edit("Set", |doc, _| {
|
||||
set(doc.layer_mut(red).unwrap());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("layer.mergeLayers", json!({})).unwrap();
|
||||
assert_eq!(undo_label(&s), "Merge Down", "{case}");
|
||||
}
|
||||
}
|
||||
@@ -31,9 +31,9 @@ pub use selection::top_level;
|
||||
use selection::{doc_state, find_layers, select_all_layers, select_linked};
|
||||
pub(crate) use selection::{mask_targets, recorded_step, reselect};
|
||||
pub use selection::{select, selected, set_selection};
|
||||
pub use structure::deletion_neighbours;
|
||||
pub(crate) use structure::{check_group_depth, relink_copies};
|
||||
pub use structure::{delete_selected, duplicate_selected, group_layers, set_visible_selected};
|
||||
pub use structure::{deletion_neighbours, merges_clipping_mask};
|
||||
use structure::{link_layers, lock_layers, merge_layers, rename_layer, reverse};
|
||||
|
||||
// ---------- enabled predicates ----------
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
use photocraft_doc::{Layer, LayerId, Locks};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const GROUP_FROM_LAYERS: &str = "layer.new.groupFromLayers";
|
||||
|
||||
struct Fixture {
|
||||
session: Session,
|
||||
shared: LayerId,
|
||||
source: LayerId,
|
||||
leaving: LayerId,
|
||||
staying: LayerId,
|
||||
}
|
||||
|
||||
fn fixture(source_locks: Locks, shared_locks: Locks, own_locks: Locks) -> Fixture {
|
||||
let mut session = crate::session();
|
||||
session.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap();
|
||||
let (shared, source, leaving, staying) = session
|
||||
.edit("Fixture layers", |doc, active| {
|
||||
let mut leaving = Layer::raster("Leaving", doc.pixel_format());
|
||||
leaving.locks = own_locks;
|
||||
let staying = Layer::raster("Staying", doc.pixel_format());
|
||||
let (leaving_id, staying_id) = (leaving.id, staying.id);
|
||||
let mut source = Layer::group("Source", vec![leaving]);
|
||||
source.locks = source_locks;
|
||||
let source_id = source.id;
|
||||
let destination = Layer::group("Destination", vec![staying]);
|
||||
let mut shared = Layer::group("Shared", vec![source, destination]);
|
||||
shared.locks = shared_locks;
|
||||
let shared_id = shared.id;
|
||||
doc.layers.push(shared);
|
||||
*active = Some(staying_id);
|
||||
Ok((shared_id, source_id, leaving_id, staying_id))
|
||||
})
|
||||
.unwrap();
|
||||
for (layer, mode) in [(leaving, "replace"), (staying, "add")] {
|
||||
session.execute("layer.select", json!({"layer": layer.0, "mode": mode})).unwrap();
|
||||
}
|
||||
Fixture { session, shared, source, leaving, staying }
|
||||
}
|
||||
|
||||
fn group(session: &mut Session, command: &str) -> LayerId {
|
||||
LayerId(session.execute(command, json!({})).unwrap()["layer"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_from_layers_carries_each_departed_lock_in_the_grouping_undo_step() {
|
||||
for locks in [
|
||||
Locks { all: true, ..Default::default() },
|
||||
Locks { position: true, ..Default::default() },
|
||||
Locks { transparency: true, ..Default::default() },
|
||||
Locks { pixels: true, ..Default::default() },
|
||||
Locks { artboard: true, ..Default::default() },
|
||||
Locks { position: true, transparency: true, ..Default::default() },
|
||||
] {
|
||||
let Fixture { mut session, source, leaving, staying, .. } = fixture(locks, Locks::default(), Locks::default());
|
||||
let state = session.active().unwrap();
|
||||
let before = state.doc.clone();
|
||||
let steps = state.history.past_len();
|
||||
let group = group(&mut session, GROUP_FROM_LAYERS);
|
||||
let state = session.active().unwrap();
|
||||
let doc = &state.doc;
|
||||
assert_eq!(state.history.past_len(), steps + 1);
|
||||
assert!(doc.layer(source).unwrap().children().unwrap().is_empty());
|
||||
assert_eq!(doc.layer(group).unwrap().children().unwrap().iter().map(|layer| layer.id).collect::<Vec<_>>(), [leaving, staying]);
|
||||
assert_eq!(doc.layer(group).unwrap().locks, Locks::default());
|
||||
assert_eq!(doc.layer(leaving).unwrap().locks, locks);
|
||||
assert_eq!(doc.layer(staying).unwrap().locks, Locks::default());
|
||||
session.undo();
|
||||
assert_eq!(session.active().unwrap().doc, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_from_layers_keeps_shared_locks_inherited_and_keeps_own_locks() {
|
||||
let shared_locks = Locks { pixels: true, position: true, ..Default::default() };
|
||||
let source_locks = Locks { position: true, ..Default::default() };
|
||||
let own_locks = Locks { artboard: true, ..Default::default() };
|
||||
let Fixture { mut session, shared, leaving, staying, .. } = fixture(source_locks, shared_locks, own_locks);
|
||||
let group = group(&mut session, GROUP_FROM_LAYERS);
|
||||
let doc = &session.active().unwrap().doc;
|
||||
let new_own_locks = own_locks.union(source_locks);
|
||||
assert_eq!(doc.layer(leaving).unwrap().locks, new_own_locks);
|
||||
assert_eq!(doc.layer(staying).unwrap().locks, Locks::default());
|
||||
assert_eq!(doc.layer(group).unwrap().locks, Locks::default());
|
||||
assert_eq!(doc.effective_locks(staying), shared_locks);
|
||||
|
||||
session
|
||||
.edit("Unlock ancestor", |doc, _| {
|
||||
doc.layer_mut(shared).unwrap().locks = Locks::default();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let doc = &session.active().unwrap().doc;
|
||||
assert_eq!(doc.effective_locks(leaving), new_own_locks);
|
||||
assert!(!doc.effective_locks(staying).any());
|
||||
let error = session.execute("layer.translate", json!({"layer": leaving.0, "dx": 1})).unwrap_err();
|
||||
assert!(error.to_string().contains("locked"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_layers_shortcut_keeps_its_existing_lock_behavior() {
|
||||
let locks = Locks { all: true, ..Default::default() };
|
||||
let Fixture { mut session, leaving, .. } = fixture(locks, Locks::default(), Locks::default());
|
||||
group(&mut session, "layer.groupLayers");
|
||||
let doc = &session.active().unwrap().doc;
|
||||
assert!(!doc.layer(leaving).unwrap().locks.any());
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use photocraft_doc::Locks;
|
||||
|
||||
use super::selection::{reselect, selected, top_level};
|
||||
use super::{Document, EngineError, Layer, LayerContent, LayerId, PixelFormat, Result, Session, Value, bad, json};
|
||||
|
||||
@@ -135,7 +139,7 @@ pub(super) fn group_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.iter().any(|id| doc.is_background(*id)) {
|
||||
return Err(EngineError::Other("the Background layer can't go into a group".into()));
|
||||
}
|
||||
group_layers_with(s, p, &ids, ids.len() == 1, false)
|
||||
group_layers_with(s, p, &ids, true)
|
||||
}
|
||||
|
||||
/// Group Layers (⌘G) moves the explicit layer or the selection into a new, collapsed group.
|
||||
@@ -144,23 +148,24 @@ pub fn group_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(id) => vec![id],
|
||||
None => selected(s),
|
||||
};
|
||||
group_layers_with(s, p, &ids, false, true)
|
||||
group_layers_with(s, p, &ids, false)
|
||||
}
|
||||
|
||||
/// Creates the group at the topmost target, preserving layer order and applying the dialog's
|
||||
/// options in the same history step. `tag_layers` passes a colour on to the layers inside.
|
||||
fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], expanded: bool, tag_layers: bool) -> Result<Value> {
|
||||
/// options in the same history step.
|
||||
fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], from_layers: bool) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("no layer selected".into()));
|
||||
}
|
||||
let opts = crate::group_options::GroupOptions::parse("layer.groupLayers", p)?;
|
||||
let expanded = from_layers && ids.len() == 1;
|
||||
let gid = s.edit("Group Layers", |doc, active| {
|
||||
// A base takes the layers clipped to it into the group, still clipped, whether they were
|
||||
// selected or not; a clipped layer that goes in without its base is released, as in the
|
||||
// reference application (#14713).
|
||||
let mut ids = top_level(doc, ids);
|
||||
let bases: Vec<LayerId> = ids.clone();
|
||||
for id in bases {
|
||||
let selected_roots = top_level(doc, ids);
|
||||
let mut ids = selected_roots.clone();
|
||||
for &id in &selected_roots {
|
||||
ids.extend(crate::clip_group::clipped_to(doc, id));
|
||||
}
|
||||
let ids = top_level(doc, &ids);
|
||||
@@ -174,6 +179,24 @@ fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], expanded: bool
|
||||
return Err(EngineError::Other("artboards can't go into a group".into()));
|
||||
}
|
||||
let top = *ids.last().ok_or(EngineError::NoLayer(LayerId(0)))?;
|
||||
let mut carried_locks = HashMap::new();
|
||||
if from_layers {
|
||||
// Only ancestors the selected layer leaves become own locks. Shared ancestors still
|
||||
// supply their inherited locks, including when the new group is nested below them.
|
||||
let insertion_path = doc.insertion_path(top).ok_or(EngineError::NoLayer(top))?;
|
||||
let (_, destination) = insertion_path.split_last().ok_or(EngineError::NoLayer(top))?;
|
||||
for id in selected_roots {
|
||||
let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?;
|
||||
let (_, parents) = path.split_last().ok_or(EngineError::NoLayer(id))?;
|
||||
let shared = parents.iter().zip(destination).take_while(|(old, new)| old == new).count();
|
||||
let locks = (shared + 1..=parents.len())
|
||||
.filter_map(|depth| doc.layer_at(&parents[..depth]))
|
||||
.fold(Locks::default(), |locks, layer| locks.union(layer.locks));
|
||||
if locks.any() {
|
||||
carried_locks.insert(id, locks);
|
||||
}
|
||||
}
|
||||
}
|
||||
let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group"));
|
||||
let mut group = Layer::group(name, vec![]);
|
||||
if let LayerContent::Group(g) = &mut group.content {
|
||||
@@ -182,14 +205,18 @@ fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], expanded: bool
|
||||
let gid = doc.insert_above(Some(top), group);
|
||||
let mut children = Vec::with_capacity(ids.len());
|
||||
for id in &ids {
|
||||
children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?);
|
||||
let mut child = doc.remove(*id).ok_or(EngineError::NoLayer(*id))?;
|
||||
if let Some(&locks) = carried_locks.get(id) {
|
||||
child.locks = child.locks.union(locks);
|
||||
}
|
||||
children.push(child);
|
||||
}
|
||||
for child in children.iter_mut().filter(|l| release.contains(&l.id)) {
|
||||
child.clipped = false;
|
||||
}
|
||||
let group = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?;
|
||||
*group.children_mut().ok_or(EngineError::NoLayer(gid))? = children;
|
||||
opts.apply(group, tag_layers);
|
||||
opts.apply(group, !from_layers);
|
||||
check_group_depth(doc, "Group Layers")?;
|
||||
*active = Some(gid);
|
||||
Ok(gid)
|
||||
@@ -201,7 +228,13 @@ fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], expanded: bool
|
||||
pub(super) fn merge_layers(s: &mut Session) -> Result<Value> {
|
||||
let sel = selected(s);
|
||||
if sel.len() < 2 {
|
||||
// ⌘E on a lone group is Photoshop's Merge Group (#3832); on a layer, Merge Down.
|
||||
// ⌘E on a lone clip base is Merge Clipping Mask (#18481); on a lone group, Photoshop's Merge Group (#3832); on a
|
||||
// layer, Merge Down.
|
||||
if let Some(&id) = sel.first()
|
||||
&& s.active().is_some_and(|d| merges_clipping_mask(&d.doc, id))
|
||||
{
|
||||
return merge_clipping_mask(s, id);
|
||||
}
|
||||
if let Some(&id) = sel.first()
|
||||
&& s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_)))
|
||||
{
|
||||
@@ -271,6 +304,66 @@ pub(super) fn merge_layers(s: &mut Session) -> Result<Value> {
|
||||
Ok(json!({ "layer": mid.0 }))
|
||||
}
|
||||
|
||||
/// `⌘E` on `id` alone is Merge Clipping Mask: a visible pixel-bearing top-level layer with layers clipped to it. A base
|
||||
/// inside a group, with a layer or vector mask or effects, a group or an adjustment layer as the base, and a hidden base
|
||||
/// were not measured (#18481) and keep Merge Down or Merge Group. So does a base whose Fill, Blend If, Advanced Blending
|
||||
/// or excluded channels the merged layer could not carry without changing the composite (review of #18858).
|
||||
pub fn merges_clipping_mask(doc: &Document, id: LayerId) -> bool {
|
||||
let Some(l) = doc.layer(id) else { return false };
|
||||
doc.path_of(id).is_some_and(|p| p.len() == 1)
|
||||
&& l.visible
|
||||
&& l.mask.is_none()
|
||||
&& l.vector_mask.is_none()
|
||||
&& l.effects.items.is_empty()
|
||||
&& l.fill_opacity >= 1.0
|
||||
&& l.blend_if.is_default()
|
||||
&& l.advanced.is_default()
|
||||
&& l.excluded_channels == 0
|
||||
&& !matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_))
|
||||
&& !crate::clip_group::clipped_to(doc, id).is_empty()
|
||||
}
|
||||
|
||||
/// Merge Clipping Mask: the base and the layers clipped to it become one layer with the base's id, name, place, blend mode,
|
||||
/// opacity, locks, colour label and link. Clipped pixels are blended inside the base's pixels and dropped outside it, so
|
||||
/// the composite does not change; hidden clipped layers are discarded, as Merge Layers does.
|
||||
fn merge_clipping_mask(s: &mut Session, base_id: LayerId) -> Result<Value> {
|
||||
s.edit("Merge Clipping Mask", |doc, active| {
|
||||
let clipped = crate::clip_group::clipped_to(doc, base_id);
|
||||
let base = doc.layer(base_id).ok_or(EngineError::NoLayer(base_id))?.clone();
|
||||
let format = doc.pixel_format();
|
||||
// The group alone, the base drawn plainly: its blend mode and opacity stay on the result.
|
||||
let mut plain = base.clone();
|
||||
plain.blend = photocraft_doc::BlendMode::Normal;
|
||||
plain.opacity = 1.0;
|
||||
let mut solo = Document::new("merge", doc.size, format.mode, format.sample);
|
||||
solo.icc_profile = doc.icc_profile.clone();
|
||||
let mut stack = vec![plain];
|
||||
stack.extend(clipped.iter().filter_map(|id| doc.layer(*id)).filter(|l| l.visible).cloned());
|
||||
solo.layers = stack.into();
|
||||
// A Background stays canvas-sized and opaque; any other layer keeps its pixels outside the canvas.
|
||||
let pixels = if doc.is_background(base_id) {
|
||||
crate::pixels::composite_layers(&solo, format, None)
|
||||
} else {
|
||||
crate::pixels::composite_layers_uncropped(&solo, PixelFormat::new(format.mode, format.sample, true))
|
||||
};
|
||||
let mut merged = Layer::new(base.name.clone(), LayerContent::Raster(pixels));
|
||||
merged.id = base_id;
|
||||
merged.blend = base.blend;
|
||||
merged.opacity = base.opacity;
|
||||
merged.locks = base.locks;
|
||||
merged.label = base.label;
|
||||
merged.link_group = base.link_group;
|
||||
for id in &clipped {
|
||||
doc.remove(*id);
|
||||
}
|
||||
*doc.layer_mut(base_id).ok_or(EngineError::NoLayer(base_id))? = merged;
|
||||
*active = Some(base_id);
|
||||
Ok(())
|
||||
})?;
|
||||
reselect(s, vec![base_id], Some(base_id));
|
||||
Ok(json!({ "layer": base_id.0 }))
|
||||
}
|
||||
|
||||
/// Next visible layer row below the deleted target, then rows above in reverse order.
|
||||
/// Group headers precede their children in the UI, unlike Document::walk's storage order.
|
||||
pub fn deletion_neighbours(doc: &Document, target: LayerId) -> Vec<LayerId> {
|
||||
@@ -430,6 +523,10 @@ pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result<Value> {
|
||||
#[path = "group_from_layers_keeps_layer_tags_tests.rs"]
|
||||
mod group_from_layers_keeps_layer_tags_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "group_from_layers_lock_carry_tests.rs"]
|
||||
mod group_from_layers_lock_carry_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "group_from_layers_artboard_tests.rs"]
|
||||
mod group_from_layers_artboard_tests;
|
||||
|
||||
@@ -456,6 +456,33 @@ fn for_each_band(p: &Pattern, w: u32, h: u32, mut f: impl FnMut(&[[f32; 4]])) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer mask is the edit target: the active pixel layer's or group's mask is targeted, the active layer is an
|
||||
/// adjustment layer with a mask, which is what it edits, or every colour channel is hidden with no alpha channel shown, so
|
||||
/// the mask is the picture (as the desktop's target rule reads it). A shown filter mask is not the layer mask. Define
|
||||
/// Pattern and Define Brush Preset are greyed then (#18232).
|
||||
pub fn layer_mask_targeted(s: &Session) -> bool {
|
||||
let Some(st) = s.active() else { return false };
|
||||
let Some(layer) = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| l.mask.is_some()) else { return false };
|
||||
if crate::mask_view_cmds::current(st).is_some_and(|v| v.filter) {
|
||||
return false;
|
||||
}
|
||||
match st.channel_view.target {
|
||||
crate::channel_cmds::ChannelTarget::LayerMask => true,
|
||||
crate::channel_cmds::ChannelTarget::Composite if st.doc.quick_mask.is_none() => {
|
||||
let view = &st.channel_view;
|
||||
let colors_off = view.visible_colors(crate::channel_cmds::color_count(&st.doc)) == 0;
|
||||
let alpha_on = (0..st.doc.channels.len()).any(|i| view.alpha_shown(i));
|
||||
matches!(layer.content, LayerContent::Adjustment(_)) || (colors_off && !alpha_on)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn can_define(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
if layer_mask_targeted(s) { Err("a layer mask is the target".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec {
|
||||
@@ -464,7 +491,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
menu: &["Edit"],
|
||||
shortcut: None,
|
||||
params: r##"{"name":text,"rect":[x0,y0,x1,y1]?} → {"pattern":id} (name: default the document's name numbered past the library's names; rect: default the selection bounds or else the canvas; added to the library from the visible composite)"##,
|
||||
enabled: has_doc,
|
||||
enabled: can_define,
|
||||
journal: true,
|
||||
run: define,
|
||||
},
|
||||
|
||||
@@ -148,7 +148,7 @@ fn embed_all_linked(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
}
|
||||
let parent = doc.id;
|
||||
let contents: Vec<SmartContentsId> = ids.iter().map(|id| smart(doc, *id).map(|sm| sm.contents_id)).collect::<Result<_>>()?;
|
||||
s.edit("Embed All Linked", |doc, _| {
|
||||
s.edit("Embed All Linked Smart Objects", |doc, _| {
|
||||
for (id, src) in ids.iter().zip(sources) {
|
||||
smart_mut(doc, *id)?.source = src;
|
||||
refresh_or_fail(doc, *id)?;
|
||||
@@ -209,6 +209,8 @@ mod contents;
|
||||
mod filters;
|
||||
mod placing;
|
||||
mod rendering;
|
||||
#[cfg(test)]
|
||||
mod reset_transform_noop_tests;
|
||||
mod source;
|
||||
|
||||
pub(crate) use contents::on_close;
|
||||
@@ -294,7 +296,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}),
|
||||
spec!("layer.smartObjects.updateModifiedContent", "Update Modified Content", SO, r##"{"layer":id?}"##, has_linked, |s, p| {
|
||||
let id = layer_param(s, p)?;
|
||||
s.edit("Update Modified Content", |doc, _| refresh_or_fail(doc, id))?;
|
||||
s.edit("Update Modified Smart Object", |doc, _| refresh_or_fail(doc, id))?;
|
||||
Ok(json!({"layer": id.0}))
|
||||
}),
|
||||
spec!(
|
||||
|
||||
@@ -159,7 +159,7 @@ pub fn commit_child(s: &mut Session, index: usize) -> Result<bool> {
|
||||
let prev = s.active;
|
||||
s.active = Some(parent);
|
||||
s.note_active_change();
|
||||
let r = s.edit("Edit Contents", |doc, _| {
|
||||
let r = s.edit("Update Smart Objects", |doc, _| {
|
||||
let ids = instances(doc, link.contents_id);
|
||||
if ids.is_empty() {
|
||||
return Err(other("the smart object's instances were removed"));
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//! #18466: saving a smart object's contents, Convert to Layers, Update Modified Content and Embed All Linked add
|
||||
//! History states with the names measured in the reference application. The menu labels keep their own wording.
|
||||
|
||||
use photocraft_geom::Rect;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// A document whose active layer is a smart object made from one painted layer.
|
||||
fn smart_object() -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 32, "height": 24})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
paint(&mut s, [1.0, 0.0, 0.0, 1.0]);
|
||||
s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The same, with the smart object linked to a file in a directory of its own. Returns the directory too.
|
||||
fn linked_smart_object(name: &str) -> (Session, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("pc-so-history-names-{name}-{}", std::process::id()));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = smart_object();
|
||||
s.execute("layer.smartObjects.convertToLinked", json!({"path": dir.join("linked.pcraft").to_str().unwrap()})).unwrap();
|
||||
(s, dir)
|
||||
}
|
||||
|
||||
/// Fills a corner of the active document's top layer.
|
||||
fn paint(s: &mut Session, colour: [f32; 4]) {
|
||||
s.edit("setup", |doc, _| {
|
||||
doc.layers.last_mut().unwrap().surface_mut().unwrap().fill_rect(Rect::new(2, 2, 10, 10), &colour);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// The number of History states of the active document and the name of the last one.
|
||||
fn history(s: &Session) -> (usize, Option<String>) {
|
||||
let history = &s.active().unwrap().history;
|
||||
(history.past_len(), history.undo_label().map(str::to_string))
|
||||
}
|
||||
|
||||
fn named(states: usize, name: &str) -> (usize, Option<String>) {
|
||||
(states, Some(name.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_the_contents_adds_update_smart_objects_to_the_parent() {
|
||||
let mut s = smart_object();
|
||||
let parent = s.active_index().unwrap();
|
||||
let (states, _) = history(&s);
|
||||
let child = s.execute("layer.smartObjects.editContents", json!({})).unwrap()["document"].as_u64().unwrap() as usize;
|
||||
paint(&mut s, [0.0, 1.0, 0.0, 1.0]);
|
||||
s.execute("layer.smartObjects.saveContents", json!({})).unwrap();
|
||||
s.set_active(parent);
|
||||
assert_eq!(history(&s), named(states + 1, "Update Smart Objects"));
|
||||
// Closing a changed contents document saves it the same way, under the same name.
|
||||
s.set_active(child);
|
||||
paint(&mut s, [0.0, 0.0, 1.0, 1.0]);
|
||||
s.execute("file.close", json!({})).unwrap();
|
||||
s.set_active(parent);
|
||||
assert_eq!(history(&s), named(states + 2, "Update Smart Objects"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_layers_adds_convert_smart_object_to_layers() {
|
||||
let mut s = smart_object();
|
||||
let (states, _) = history(&s);
|
||||
s.execute("layer.smartObjects.convertToLayers", json!({})).unwrap();
|
||||
assert_eq!(history(&s), named(states + 1, "Convert Smart Object to Layers"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_modified_content_adds_update_modified_smart_object() {
|
||||
let (mut s, dir) = linked_smart_object("update");
|
||||
let (states, _) = history(&s);
|
||||
s.execute("layer.smartObjects.updateModifiedContent", json!({})).unwrap();
|
||||
assert_eq!(history(&s), named(states + 1, "Update Modified Smart Object"));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embed_all_linked_adds_embed_all_linked_smart_objects() {
|
||||
let (mut s, dir) = linked_smart_object("embed");
|
||||
let (states, _) = history(&s);
|
||||
s.execute("layer.smartObjects.embedAllLinked", json!({})).unwrap();
|
||||
assert_eq!(history(&s), named(states + 1, "Embed All Linked Smart Objects"));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_menu_entries_keep_their_labels() {
|
||||
let _session = crate::session();
|
||||
for (id, label) in [
|
||||
("layer.smartObjects.editContents", "Edit Contents"),
|
||||
("layer.smartObjects.convertToLayers", "Convert to Layers"),
|
||||
("layer.smartObjects.updateModifiedContent", "Update Modified Content"),
|
||||
("layer.smartObjects.embedAllLinked", "Embed All Linked"),
|
||||
] {
|
||||
assert_eq!(crate::commands::find(id).unwrap().label, label, "{id}");
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,18 @@ pub(super) fn reset_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(name) = stuck.first() {
|
||||
return Err(other(format!("the {name} smart filter is not supported, so the smart object's transform can't be reset")));
|
||||
}
|
||||
// Already at 100 %, unrotated, unskewed, without Distort, Perspective or Warp (a whole-pixel move
|
||||
// is no transform: the reset keeps the object where it sits): the reference application leaves
|
||||
// the item enabled and changes nothing, adding no History state (#18286), so the document's
|
||||
// changed flag stays as it was too. Checked after the refusals the step has always made (a filter
|
||||
// it can't apply, a layer locked in place), which stay as they were.
|
||||
if sm.warp.is_none() && sm.perspective.is_none() && sm.transform.m[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
if crate::transform_cmds::locked_for_transform(&st.doc, id) {
|
||||
let name = st.doc.layer(id).map_or("", |l| l.name.as_str());
|
||||
return Err(other(format!("layer \"{name}\" is locked")));
|
||||
}
|
||||
return Ok(json!({"layer": id.0, "transform": sm.transform.m}));
|
||||
}
|
||||
// The contents' own box in source pixels: 100 % maps it one-to-one onto the document.
|
||||
let [x0, y0, x1, y1] = source_box(&st.doc, sm).ok_or_else(|| other("the smart object's contents are unavailable"))?;
|
||||
let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! Reset Transform on a smart object that has no transform changes nothing: no History state, and
|
||||
//! the document's changed flag stays as it was (#18286). Measured in the reference application: the
|
||||
//! menu item stays enabled on such an object, and choosing it adds no state; on a transformed
|
||||
//! object it adds exactly one.
|
||||
|
||||
use super::*;
|
||||
|
||||
const RESET: &str = "layer.smartObjects.resetTransform";
|
||||
|
||||
/// A document with one painted layer converted to a smart object; the smart object's id.
|
||||
fn smart_session() -> (Session, u64) {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.edit("setup", |doc, active| {
|
||||
let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
|
||||
surface.fill_rect(Rect::new(8, 6, 40, 30), &[0.8, 0.3, 0.1, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let id = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn state_count(s: &Session) -> usize {
|
||||
s.active().unwrap().history.entries().len()
|
||||
}
|
||||
|
||||
fn dirty(s: &Session) -> bool {
|
||||
s.active().unwrap().is_dirty()
|
||||
}
|
||||
|
||||
/// Marks the document saved, as File ▸ Save would.
|
||||
fn mark_saved(s: &mut Session) {
|
||||
let st = s.active_mut().unwrap();
|
||||
st.saved_revision = st.revision;
|
||||
}
|
||||
|
||||
fn layer(s: &Session, id: u64) -> Layer {
|
||||
s.active().unwrap().doc.layer(LayerId(id)).unwrap().clone()
|
||||
}
|
||||
|
||||
/// The issue's steps: Convert to Smart Object, then Reset Transform. Enabled, and nothing happens:
|
||||
/// the layer, the History and a saved document's clean state all stay.
|
||||
#[test]
|
||||
fn an_untransformed_smart_object_resets_without_a_state_and_stays_clean() {
|
||||
let (mut s, id) = smart_session();
|
||||
assert!(s.is_enabled(RESET), "the item stays enabled on an untransformed smart object");
|
||||
mark_saved(&mut s);
|
||||
let (states, before) = (state_count(&s), layer(&s, id));
|
||||
s.execute(RESET, json!({})).unwrap();
|
||||
assert_eq!(state_count(&s), states, "no history state");
|
||||
assert!(!dirty(&s), "a saved document stays unmodified");
|
||||
assert_eq!(layer(&s, id), before, "the layer is unchanged");
|
||||
assert!(s.is_enabled(RESET), "still enabled afterwards");
|
||||
}
|
||||
|
||||
/// A document that already had changes keeps them marked: the no-op neither adds a step nor
|
||||
/// clears the flag.
|
||||
#[test]
|
||||
fn a_modified_document_stays_modified() {
|
||||
let (mut s, id) = smart_session();
|
||||
assert!(dirty(&s), "the fixture's edits mark the document changed");
|
||||
let states = state_count(&s);
|
||||
s.execute(RESET, json!({"layer": id})).unwrap();
|
||||
assert_eq!(state_count(&s), states, "no history state for a named layer either");
|
||||
assert!(dirty(&s), "still changed");
|
||||
}
|
||||
|
||||
/// Moving by whole pixels is no transform: the placement is still 100 %, unrotated and unskewed,
|
||||
/// and Reset Transform keeps the object where it is, so it changes nothing.
|
||||
#[test]
|
||||
fn a_moved_smart_object_is_untransformed() {
|
||||
let (mut s, id) = smart_session();
|
||||
s.execute("layer.translate", json!({"dx": 7, "dy": -3})).unwrap();
|
||||
let (states, before) = (state_count(&s), layer(&s, id));
|
||||
s.execute(RESET, json!({})).unwrap();
|
||||
assert_eq!(state_count(&s), states, "no history state");
|
||||
assert_eq!(layer(&s, id), before, "the layer stays where it was moved to");
|
||||
}
|
||||
|
||||
/// On a transformed object the reset is still one state, and a second reset (now untransformed)
|
||||
/// adds none.
|
||||
#[test]
|
||||
fn a_transformed_smart_object_still_adds_exactly_one_state() {
|
||||
let (mut s, id) = smart_session();
|
||||
s.execute("edit.transform", json!({"layer": id, "scaleX": 50, "scaleY": 30, "rotate": 30})).unwrap();
|
||||
mark_saved(&mut s);
|
||||
let states = state_count(&s);
|
||||
s.execute(RESET, json!({})).unwrap();
|
||||
assert_eq!(state_count(&s), states + 1, "one history state");
|
||||
assert!(dirty(&s), "a real reset changes the document");
|
||||
s.execute(RESET, json!({})).unwrap();
|
||||
assert_eq!(state_count(&s), states + 1, "the second reset finds nothing to do");
|
||||
}
|
||||
|
||||
/// Only a Warp, no other transform: still transformed (unmeasured in the reference; the issue keeps
|
||||
/// today's behaviour), so the reset takes the Warp off in one state.
|
||||
#[test]
|
||||
fn a_warp_alone_counts_as_a_transform() {
|
||||
let (mut s, _) = smart_session();
|
||||
s.execute("edit.transform.warp", json!({"style": "arc", "bend": 30})).unwrap();
|
||||
let states = state_count(&s);
|
||||
s.execute(RESET, json!({})).unwrap();
|
||||
assert_eq!(state_count(&s), states + 1, "one history state");
|
||||
let d = s.active().unwrap();
|
||||
let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("a smart object") };
|
||||
assert!(sm.warp.is_none(), "the Warp is gone");
|
||||
}
|
||||
|
||||
/// Distort leaves a projective placement whose affine part can read as 100 %: still transformed.
|
||||
#[test]
|
||||
fn a_distorted_smart_object_counts_as_transformed() {
|
||||
let (mut s, id) = smart_session();
|
||||
let r = layer(&s, id).surface().unwrap().content_bounds();
|
||||
let (x0, y0, x1, y1) = (f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1));
|
||||
s.execute("edit.transform", json!({"layer": id, "rect": [x0, y0, x1, y1], "quad": [[x0, y0], [x1, y0], [x1 - 6.0, y1 - 4.0], [x0, y1]]})).unwrap();
|
||||
let states = state_count(&s);
|
||||
s.execute(RESET, json!({})).unwrap();
|
||||
assert_eq!(state_count(&s), states + 1, "one history state");
|
||||
}
|
||||
|
||||
/// A position-locked object was refused before and still is, transformed or not (unmeasured in the
|
||||
/// reference; the issue keeps today's behaviour): nothing changes and no state is added.
|
||||
#[test]
|
||||
fn a_position_locked_untransformed_object_is_still_refused() {
|
||||
let (mut s, id) = smart_session();
|
||||
s.execute("layer.lockLayers", json!({"position": true})).unwrap();
|
||||
let (states, before) = (state_count(&s), layer(&s, id));
|
||||
let err = s.execute(RESET, json!({})).unwrap_err().to_string();
|
||||
assert!(err.contains("locked"), "{err}");
|
||||
assert_eq!(state_count(&s), states, "no history state");
|
||||
assert_eq!(layer(&s, id), before);
|
||||
}
|
||||
@@ -187,7 +187,7 @@ pub(super) fn convert_to_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let discarded = sm.smart_filters.len();
|
||||
let out = unpacked(so, layers);
|
||||
let (new_id, group) = (out.id, out.is_group());
|
||||
s.edit("Convert to Layers", |doc, active| {
|
||||
s.edit("Convert Smart Object to Layers", |doc, active| {
|
||||
let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?;
|
||||
*doc.layer_at_mut(&path).ok_or(EngineError::NoLayer(id))? = out;
|
||||
*active = Some(new_id);
|
||||
@@ -224,3 +224,7 @@ fn check_destination_shapes(
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "contents_unpack_history_names_tests.rs"]
|
||||
mod contents_unpack_history_names_tests;
|
||||
|
||||
@@ -173,7 +173,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"path.transform",
|
||||
"Free Transform Path",
|
||||
[],
|
||||
r##"{"name":str|"work"|"layer"="work","layer":id? (with layer target),"vectorMask":bool=false (with the layer target: its vector mask's path, not a shape layer's path),"matrix":[a,b,c,d,e,f] | "quad":[[x,y]×4] (Distort/Perspective: where the frame's corners go, clockwise from top-left) | "style"|"mesh"|"warp":… (Warp, as edit.transform.warp) | "translateX":px?,"translateY":px?,"scaleX":factor?,"scaleY":factor?,"angle":degrees?,"rect":[x0,y0,x1,y1]? (the quad's or warp's frame; default = path control bounds)} (numeric transforms pivot on path bounds center)"##,
|
||||
r##"{"name":str|"work"|"layer"="work","layer":id? (with layer target),"vectorMask":bool=false (with the layer target: its vector mask's path, not a shape layer's path),"anchors":[[subpath,knot]×…] (Free Transform Points: only these anchors, each with its own handles, follow the map, and translate/scale/angle and the Distort/Warp frame use their bounds; one "Transform Points" step),"matrix":[a,b,c,d,e,f] | "quad":[[x,y]×4] (Distort/Perspective: where the frame's corners go, clockwise from top-left) | "style"|"mesh"|"warp":… (Warp, as edit.transform.warp) | "translateX":px?,"translateY":px?,"scaleX":factor?,"scaleY":factor?,"angle":degrees?,"rect":[x0,y0,x1,y1]? (the quad's or warp's frame; default = the bounds of what is transformed)} (numeric transforms pivot on those bounds' center)"##,
|
||||
has_doc,
|
||||
path_transform
|
||||
),
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! #18452: no lock blocks the four Layer › Combine Shapes operations, as in the reference application. The result is
|
||||
//! the top layer, with the locks it had. Lock Pixels, Lock Transparent Pixels and a lock inherited from a group were
|
||||
//! not measured and follow the same rule. Merge Shape Components was not measured and still refuses.
|
||||
|
||||
use photocraft_doc::vector::Path;
|
||||
use photocraft_doc::{Document, LayerContent, LayerId, Locks};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const OPERATIONS: [&str; 4] = [
|
||||
"layer.combineShapes.unite",
|
||||
"layer.combineShapes.subtractFrontShape",
|
||||
"layer.combineShapes.intersectShapeAreas",
|
||||
"layer.combineShapes.excludeOverlappingShapes",
|
||||
];
|
||||
const MERGE_COMPONENTS: &str = "layer.combineShapes.mergeShapeComponents";
|
||||
|
||||
const ALL: Locks = Locks { transparency: false, pixels: false, position: false, artboard: false, all: true };
|
||||
const POSITION: Locks = Locks { transparency: false, pixels: false, position: true, artboard: false, all: false };
|
||||
const PIXELS: Locks = Locks { transparency: false, pixels: true, position: false, artboard: false, all: false };
|
||||
const TRANSPARENCY: Locks = Locks { transparency: true, pixels: false, position: false, artboard: false, all: false };
|
||||
|
||||
/// Two overlapping rectangle shape layers, both selected. Returns the bottom and the top one.
|
||||
fn two_selected_shapes() -> (Session, LayerId, LayerId) {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
let bottom = s.execute("shape.create", json!({"rect": [10, 10, 40, 40]})).unwrap()["layer"].as_u64().unwrap();
|
||||
let top = s.execute("shape.create", json!({"rect": [30, 30, 40, 40]})).unwrap()["layer"].as_u64().unwrap();
|
||||
select(&mut s, LayerId(bottom), LayerId(top));
|
||||
(s, LayerId(bottom), LayerId(top))
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, bottom: LayerId, top: LayerId) {
|
||||
s.execute("layer.select", json!({"layer": bottom.0})).unwrap();
|
||||
s.execute("layer.select", json!({"layer": top.0, "mode": "add"})).unwrap();
|
||||
}
|
||||
|
||||
fn lock(s: &mut Session, id: LayerId, locks: Locks) {
|
||||
s.edit("lock", |doc, _| {
|
||||
doc.layer_mut(id).unwrap().locks = locks;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn doc(s: &Session) -> &Document {
|
||||
&s.active().unwrap().doc
|
||||
}
|
||||
|
||||
fn path(s: &Session, id: LayerId) -> Path {
|
||||
match &doc(s).layer(id).unwrap().content {
|
||||
LayerContent::Shape(shape) => shape.path.clone(),
|
||||
_ => panic!("not a shape layer"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The path `operation` gives without any lock.
|
||||
fn unlocked(operation: &str) -> Path {
|
||||
let (mut s, _, top) = two_selected_shapes();
|
||||
s.execute(operation, json!({})).unwrap();
|
||||
path(&s, top)
|
||||
}
|
||||
|
||||
/// Runs `operation` and checks that it merged the bottom layer into the top one as without a lock, left the top layer
|
||||
/// with `kept` as its own locks, and that one Undo brings back both layers and their locks.
|
||||
fn assert_merges(s: &mut Session, bottom: LayerId, top: LayerId, operation: &str, kept: Locks, case: &str) {
|
||||
let before = doc(s).clone();
|
||||
s.execute(operation, json!({})).unwrap_or_else(|e| panic!("{operation}, {case}: {e}"));
|
||||
assert!(doc(s).layer(bottom).is_none(), "{operation}, {case}: the bottom layer is merged away");
|
||||
assert!(path(s, top) == unlocked(operation), "{operation}, {case}: the same shape as without the lock");
|
||||
assert_eq!(doc(s).layer(top).unwrap().locks, kept, "{operation}, {case}: the top layer's own locks");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(*doc(s) == before, "{operation}, {case}: one Undo restores the layers and their locks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_all_on_the_bottom_layer_does_not_block_and_the_result_has_no_lock() {
|
||||
for operation in OPERATIONS {
|
||||
let (mut s, bottom, top) = two_selected_shapes();
|
||||
lock(&mut s, bottom, ALL);
|
||||
assert_merges(&mut s, bottom, top, operation, Locks::default(), "Lock All on the bottom layer");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lock_on_the_top_layer_does_not_block_and_stays_on_the_result() {
|
||||
for operation in OPERATIONS {
|
||||
for (locks, case) in [(ALL, "Lock All on the top layer"), (POSITION, "Lock Position on the top layer")] {
|
||||
let (mut s, bottom, top) = two_selected_shapes();
|
||||
lock(&mut s, top, locks);
|
||||
assert_merges(&mut s, bottom, top, operation, locks, case);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Not measured; the item asks for the same rule.
|
||||
#[test]
|
||||
fn lock_pixels_lock_transparency_and_a_locked_group_do_not_block_either() {
|
||||
for operation in OPERATIONS {
|
||||
for (locks, case) in [(PIXELS, "Lock Pixels"), (TRANSPARENCY, "Lock Transparent Pixels")] {
|
||||
let (mut s, bottom, top) = two_selected_shapes();
|
||||
lock(&mut s, bottom, locks);
|
||||
lock(&mut s, top, locks);
|
||||
assert_merges(&mut s, bottom, top, operation, locks, case);
|
||||
}
|
||||
let (mut s, bottom, top) = two_selected_shapes();
|
||||
let group = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
|
||||
lock(&mut s, group, ALL);
|
||||
select(&mut s, bottom, top);
|
||||
assert!(doc(&s).effective_locks(top).all, "the group's lock reaches the layers");
|
||||
assert_merges(&mut s, bottom, top, operation, Locks::default(), "Lock All on the group around both");
|
||||
}
|
||||
}
|
||||
|
||||
/// Not measured, so Merge Shape Components keeps refusing locked layers.
|
||||
#[test]
|
||||
fn merge_shape_components_still_refuses_a_locked_layer() {
|
||||
let (mut s, bottom, _) = two_selected_shapes();
|
||||
lock(&mut s, bottom, ALL);
|
||||
let before = doc(&s).clone();
|
||||
assert!(s.execute(MERGE_COMPONENTS, json!({})).is_err());
|
||||
assert!(*doc(&s) == before, "nothing changed");
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::params::{color, f64p, layer_id, op_from, parse_path, path_json};
|
||||
use super::shape::{map_path, map_shape, transform_shape, with_shape};
|
||||
use super::{
|
||||
Affine, BlendMode, ClippingPath, Color, Document, EngineError, LayerContent, LayerId, NamedPath, Path, Rect, Result, SelectionMode, Session, Value, bad,
|
||||
json, parse_blend, sel, vector,
|
||||
Affine, BlendMode, ClippingPath, Color, Document, EngineError, LayerContent, LayerId, NamedPath, Path, Point, Rect, Result, SelectionMode, Session, Value,
|
||||
bad, json, parse_blend, sel, vector,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -233,6 +233,88 @@ enum PathMap {
|
||||
Warp(Box<photocraft_geom::warp::Warp>),
|
||||
}
|
||||
|
||||
/// One point of the path through `map`; a point the map sends out of bounds is an error.
|
||||
fn point_through(map: &PathMap, p: Point) -> Result<Point> {
|
||||
let q = match map {
|
||||
PathMap::Affine(a) => a.apply(p),
|
||||
PathMap::Projective(h) => {
|
||||
let (x, y) = h.apply(p.x, p.y);
|
||||
Point::new(x, y)
|
||||
}
|
||||
PathMap::Warp(w) => {
|
||||
let (x, y) = w.map(p.x, p.y);
|
||||
Point::new(x, y)
|
||||
}
|
||||
};
|
||||
(q.x.is_finite() && q.y.is_finite()).then_some(q).ok_or_else(|| EngineError::Other("the distortion sends part of the path out of bounds".into()))
|
||||
}
|
||||
|
||||
/// The anchors `path.transform` moves on their own (Free Transform Points, #13209), named as
|
||||
/// `path.moveAnchors` names them: `[subpath, knot]` pairs. `None` transforms the whole path; an empty
|
||||
/// or malformed list is an error, and a repeated pair moves that point once.
|
||||
fn anchor_list(cmd: &str, p: &Value) -> Result<Option<Vec<[usize; 2]>>> {
|
||||
let Some(v) = p.get("anchors") else { return Ok(None) };
|
||||
if v.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(list) = v.as_array().filter(|list| !list.is_empty()) else {
|
||||
return Err(bad(cmd, "`anchors` must list [subpath, knot] pairs"));
|
||||
};
|
||||
let mut out: Vec<[usize; 2]> = Vec::with_capacity(list.len());
|
||||
for a in list {
|
||||
let [s, k] = a
|
||||
.as_array()
|
||||
.filter(|a| a.len() == 2)
|
||||
.and_then(|a| Some([a[0].as_u64()?, a[1].as_u64()?]))
|
||||
.and_then(|v| Some([usize::try_from(v[0]).ok()?, usize::try_from(v[1]).ok()?]))
|
||||
.ok_or_else(|| bad(cmd, "each anchor is [subpath, knot] with whole numbers"))?;
|
||||
if !out.contains(&[s, k]) {
|
||||
out.push([s, k]);
|
||||
}
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// The bounds the transform acts on, as `[x0, y0, x1, y1]`: the anchors and their own handles a point
|
||||
/// transform names — the same measure [`Path::control_bounds`] is for the whole path — or the whole
|
||||
/// path's control bounds. An index that is not a knot of `path` is an error.
|
||||
fn acted_on_bounds(cmd: &str, path: &Path, anchors: Option<&[[usize; 2]]>) -> Result<[f64; 4]> {
|
||||
let mut b: Option<[f64; 4]> = None;
|
||||
if let Some(anchors) = anchors {
|
||||
for &[s, k] in anchors {
|
||||
let Some(node) = path.subpaths.get(s).and_then(|sp| sp.knots.get(k)) else {
|
||||
return Err(bad(cmd, format!("no anchor [{s}, {k}] on this path")));
|
||||
};
|
||||
for p in [node.anchor, node.in_ctrl, node.out_ctrl] {
|
||||
b = Some(match b {
|
||||
Some([x0, y0, x1, y1]) => [x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)],
|
||||
None => [p.x, p.y, p.x, p.y],
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
b = path.control_bounds().map(|(x0, y0, x1, y1)| [x0, y0, x1, y1]);
|
||||
}
|
||||
b.ok_or_else(|| bad(cmd, "path has no points to transform"))
|
||||
}
|
||||
|
||||
/// Free Transform Points (#13209): only the listed knots follow the map, each with its own handles;
|
||||
/// every other anchor and handle of the path stays exactly where it is.
|
||||
fn map_selected_points(path: &Path, anchors: &[[usize; 2]], map: &PathMap) -> Result<Path> {
|
||||
let mut out = path.clone();
|
||||
for &[s, k] in anchors {
|
||||
// The indices were checked against the same path before anything was edited.
|
||||
let Some(node) = out.subpaths.get_mut(s).and_then(|sp| sp.knots.get_mut(k)) else {
|
||||
return Err(EngineError::Other(format!("no anchor [{s}, {k}] on this path")));
|
||||
};
|
||||
let (anchor, handle_in, handle_out) = (point_through(map, node.anchor)?, point_through(map, node.in_ctrl)?, point_through(map, node.out_ctrl)?);
|
||||
node.anchor = anchor;
|
||||
node.in_ctrl = handle_in;
|
||||
node.out_ctrl = handle_out;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(super) fn path_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "path.transform";
|
||||
let name = p.get("name").and_then(Value::as_str).unwrap_or("work").to_owned();
|
||||
@@ -251,15 +333,17 @@ pub(super) fn path_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// its groups. Pixel-only locks still allow mask edits; shape content checks them below.
|
||||
crate::commands::check_all_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?;
|
||||
}
|
||||
// The box Distort, Perspective and Warp frame: `rect`, else the path's control bounds.
|
||||
// The anchors of a point-level transform (Free Transform Points, #13209), checked against the
|
||||
// path before anything changes: a stale anchor list must refuse, not move another point.
|
||||
let anchors = anchor_list(CMD, p)?;
|
||||
if let Some(anchors) = &anchors {
|
||||
acted_on_bounds(CMD, &transform_target(s, &name, layer_id, vector_mask)?, Some(anchors))?;
|
||||
}
|
||||
// The box Distort, Perspective and Warp frame: `rect`, else the bounds of what is transformed.
|
||||
let frame = |s: &Session| -> Result<[f64; 4]> {
|
||||
let r = match coords(p, "rect", 4)? {
|
||||
Some(r) => [r[0], r[1], r[2], r[3]],
|
||||
None => {
|
||||
let (x0, y0, x1, y1) =
|
||||
transform_target(s, &name, layer_id, vector_mask)?.control_bounds().ok_or_else(|| bad(CMD, "path has no points to transform"))?;
|
||||
[x0, y0, x1, y1]
|
||||
}
|
||||
None => acted_on_bounds(CMD, &transform_target(s, &name, layer_id, vector_mask)?, anchors.as_deref())?,
|
||||
};
|
||||
if r[2] - r[0] <= 0.0 || r[3] - r[1] <= 0.0 {
|
||||
return Err(bad(CMD, "`rect` must have a positive width and height (a straight path needs a `rect`)"));
|
||||
@@ -311,9 +395,10 @@ pub(super) fn path_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (tx, ty) = (number("translateX", 0.0)?, number("translateY", 0.0)?);
|
||||
let (sx, sy) = (number("scaleX", 1.0)?, number("scaleY", 1.0)?);
|
||||
let angle = number("angle", 0.0)?;
|
||||
// An explicit `layer` parameter determines both the transformed path and its pivot (#3062).
|
||||
// An explicit `layer` parameter determines both the transformed path and its pivot (#3062);
|
||||
// `anchors` pivots on the bounds of the anchors it names.
|
||||
let path = transform_target(s, &name, layer_id, vector_mask)?;
|
||||
let (x0, y0, x1, y1) = path.control_bounds().ok_or_else(|| bad(CMD, "path has no points to transform"))?;
|
||||
let [x0, y0, x1, y1] = acted_on_bounds(CMD, &path, anchors.as_deref())?;
|
||||
let (cx, cy) = ((x0 + x1) * 0.5, (y0 + y1) * 0.5);
|
||||
PathMap::Affine(
|
||||
Affine::translate(-cx, -cy)
|
||||
@@ -327,27 +412,38 @@ pub(super) fn path_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
PathMap::Projective(h) => json!({ "name": name, "homography": h.0 }),
|
||||
PathMap::Warp(_) => json!({ "name": name, "warp": true }),
|
||||
};
|
||||
let label = if anchors.is_some() { "Transform Points" } else { "Transform Path" };
|
||||
if !vector_mask
|
||||
&& let Some(id) = layer_id
|
||||
&& s.active().and_then(|d| d.doc.layer(id)).is_some_and(|layer| matches!(layer.content, LayerContent::Shape(_)))
|
||||
{
|
||||
with_shape(s, id, "Transform Path", |shape, _| {
|
||||
match &map {
|
||||
PathMap::Affine(a) => transform_shape(shape, a),
|
||||
PathMap::Projective(h) => map_shape(shape, Some(h), None)?,
|
||||
PathMap::Warp(w) => map_shape(shape, None, Some(w))?,
|
||||
with_shape(s, id, label, |shape, _| {
|
||||
if let Some(anchors) = &anchors {
|
||||
// Only part of the outline moved: the live shape's parameters cannot describe that,
|
||||
// as with any other point-level path edit.
|
||||
shape.path = map_selected_points(&shape.path, anchors, &map)?;
|
||||
shape.live = None;
|
||||
} else {
|
||||
match &map {
|
||||
PathMap::Affine(a) => transform_shape(shape, a),
|
||||
PathMap::Projective(h) => map_shape(shape, Some(h), None)?,
|
||||
PathMap::Warp(w) => map_shape(shape, None, Some(w))?,
|
||||
}
|
||||
}
|
||||
shape.psd_raw = None;
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(out);
|
||||
}
|
||||
s.edit("Transform Path", |doc, _| {
|
||||
s.edit(label, |doc, _| {
|
||||
let path = path_mut(doc, &name, layer_id)?;
|
||||
*path = match &map {
|
||||
PathMap::Affine(a) => path.transform(a),
|
||||
PathMap::Projective(h) => map_path(path, Some(h), None)?,
|
||||
PathMap::Warp(w) => map_path(path, None, Some(w))?,
|
||||
*path = match &anchors {
|
||||
Some(anchors) => map_selected_points(path, anchors, &map)?,
|
||||
None => match &map {
|
||||
PathMap::Affine(a) => path.transform(a),
|
||||
PathMap::Projective(h) => map_path(path, Some(h), None)?,
|
||||
PathMap::Warp(w) => map_path(path, None, Some(w))?,
|
||||
},
|
||||
};
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -861,7 +861,9 @@ fn combine_targets(s: &Session, p: &Value, narrow: &[&str]) -> Result<Option<Vec
|
||||
/// the result is then baked with tolerance `bake`. The other layers are removed; one history step.
|
||||
fn merge_shape_layers(s: &mut Session, ids: &[LayerId], op: Option<PathOp>, label: &str, bake: Option<f64>) -> Result<Value> {
|
||||
let (&keep, _) = ids.split_last().ok_or_else(|| EngineError::Other("Combine Shapes needs two or more shape layers".into()))?;
|
||||
if let Some(st) = s.active() {
|
||||
// No lock blocks the four Combine Shapes operations; the result is the top layer, with its own locks (#18452).
|
||||
// Merge Shape Components was not measured and still refuses.
|
||||
if let Some(st) = s.active().filter(|_| op.is_none()) {
|
||||
for id in ids {
|
||||
let locks = st.doc.effective_locks(*id);
|
||||
if locks.all || locks.pixels {
|
||||
@@ -951,6 +953,10 @@ mod triangle_layer_name_tests;
|
||||
#[path = "triangle_box_geometry_tests.rs"]
|
||||
mod triangle_box_geometry_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "combine_shapes_locked_layers_tests.rs"]
|
||||
mod combine_shapes_locked_layers_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod arrow_affine_regression_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1300,12 +1300,11 @@ fn combine_shapes_fails_gracefully() {
|
||||
}
|
||||
}
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
// Locked layers refuse the merge without touching the document.
|
||||
// Locks do not block the merge (#18452).
|
||||
s.execute("layer.lockLayers", json!({"all": true})).unwrap();
|
||||
assert!(doc(&s).effective_locks(LayerId(a)).all);
|
||||
let before = doc(&s).clone();
|
||||
assert!(s.execute("layer.combineShapes.unite", json!({})).is_err());
|
||||
assert_eq!(*doc(&s), before);
|
||||
s.execute("layer.combineShapes.unite", json!({})).unwrap();
|
||||
assert!(doc(&s).layer(LayerId(a)).is_none(), "the locked layers merge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -63,7 +63,10 @@ pub(crate) fn refusal(s: &Session, id: &str, p: &Value) -> Option<String> {
|
||||
}
|
||||
}
|
||||
if id == "image.adjustments.hdrToning" {
|
||||
return Some("HDR Toning requires the composite channel".into());
|
||||
return s
|
||||
.active()
|
||||
.and_then(|state| crate::adjust_cmds::hdr_toning_mode_refusal(state.doc.mode))
|
||||
.or_else(|| Some("HDR Toning requires the composite channel".into()));
|
||||
}
|
||||
if crate::channel_cmds::routed(id) && p.get("newLayer").and_then(Value::as_bool) == Some(true) {
|
||||
return Some("Creating a new layer requires the composite channel".into());
|
||||
|
||||
@@ -412,6 +412,9 @@ pub struct ToolState {
|
||||
/// The pair Quick Mask put aside, with its CMYK roles: the Quick Mask pair outside Quick
|
||||
/// Mask, the pixel (or layer mask) pair inside it (#17490).
|
||||
pub quick_mask_aside: ([[f32; 4]; 2], CmykPair),
|
||||
/// How many "Sampled Brush N" defaults Define Brush Preset stored in this session, which gives the next N. Deleting
|
||||
/// or renaming those presets doesn't lower it, and is not saved to settings (#18228).
|
||||
pub sampled_brushes: u32,
|
||||
}
|
||||
|
||||
/// Native CMYK inks associated with each color role.
|
||||
@@ -565,6 +568,7 @@ impl Default for ToolState {
|
||||
cmyk_roles: [[None; 2]; 2],
|
||||
quick_mask_on: false,
|
||||
quick_mask_aside: (Self::MASK_COLORS, [None; 2]),
|
||||
sampled_brushes: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ fn embed_all_linked_embeds_both_linked_objects_in_one_undoable_step() {
|
||||
assert_eq!(embedded(&s, ids[2]), third, "the already embedded object is untouched");
|
||||
let entries = s.active().unwrap().history.entries();
|
||||
assert_eq!(entries.len(), before + 1, "one history step");
|
||||
assert_eq!(entries.last().map(String::as_str), Some("Embed All Linked"));
|
||||
assert_eq!(entries.last().map(String::as_str), Some("Embed All Linked Smart Objects"));
|
||||
assert!(!s.is_enabled("layer.smartObjects.embedAllLinked"), "nothing left to embed");
|
||||
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
|
||||
@@ -159,7 +159,7 @@ pub fn effect_defaults(kind: &str) -> Value {
|
||||
json!({"blend": "Screen", "opacity": 35, "color": "#ffffff", "technique": "softer", "spread": 0, "size": 7, "range": 50, "contour": "Linear", "antiAlias": false, "noise": 0})
|
||||
}
|
||||
"innerGlow" => {
|
||||
json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "technique": "softer", "source": "edge", "choke": 0, "size": 5, "range": 50, "contour": "Linear", "antiAlias": false, "noise": 0})
|
||||
json!({"blend": "Screen", "opacity": 35, "color": "#ffffff", "technique": "softer", "source": "edge", "choke": 0, "size": 7, "range": 50, "contour": "Linear", "antiAlias": false, "noise": 0})
|
||||
}
|
||||
"stroke" => json!({"size": 1, "position": "inside", "blend": "Normal", "opacity": 100, "overprint": false, "color": "#000000"}),
|
||||
"colorOverlay" => json!({"blend": "Normal", "color": "#ff0000", "opacity": 100}),
|
||||
@@ -576,15 +576,13 @@ fn fresh_effect(kind: &str) -> Option<Effect> {
|
||||
noise: 0.0,
|
||||
knocks_out: !inner,
|
||||
};
|
||||
// The two glows share their shape, but not their factory values: the Outer Glow starts at
|
||||
// the reference application's white 35 % Size 7 (#14944), the Inner Glow at today's values
|
||||
// until #14917 measures its own.
|
||||
let glow = |inner: bool| Glow {
|
||||
common: FxCommon::new(BlendMode::Screen, if inner { 0.75 } else { 0.35 }),
|
||||
paint: FxPaint::Color(if inner { Color::rgb(1.0, 1.0, 190.0 / 255.0) } else { Color::WHITE }),
|
||||
// Both glows start at the reference application's white 35 % Size 7 (#14944, #14917).
|
||||
let glow = || Glow {
|
||||
common: FxCommon::new(BlendMode::Screen, 0.35),
|
||||
paint: FxPaint::Color(Color::WHITE),
|
||||
technique: GlowTechnique::Softer,
|
||||
spread: 0.0,
|
||||
size: if inner { 5.0 } else { 7.0 },
|
||||
size: 7.0,
|
||||
contour: Contour::Linear,
|
||||
anti_alias: false,
|
||||
range: 0.5,
|
||||
@@ -595,8 +593,8 @@ fn fresh_effect(kind: &str) -> Option<Effect> {
|
||||
Some(match kind {
|
||||
"dropShadow" => Effect::DropShadow(shadow(false)),
|
||||
"innerShadow" => Effect::InnerShadow(shadow(true)),
|
||||
"outerGlow" => Effect::OuterGlow(glow(false)),
|
||||
"innerGlow" => Effect::InnerGlow(glow(true)),
|
||||
"outerGlow" => Effect::OuterGlow(glow()),
|
||||
"innerGlow" => Effect::InnerGlow(glow()),
|
||||
"stroke" => Effect::Stroke(StrokeFx {
|
||||
common: FxCommon::new(BlendMode::Normal, 1.0),
|
||||
size: 1.0,
|
||||
@@ -1227,7 +1225,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
style_cmd!(
|
||||
"innerGlow",
|
||||
"Inner Glow…",
|
||||
r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="screen","technique":"softer|precise","source":"edge|center","choke":0..100,"size":px,"range":1..100=50,"contour":name|curve,"antiAlias":bool,"noise":0..100,"add":bool}"##
|
||||
r##"{"color":"#rrggbb","opacity":0..100=35,"blend":str="screen","technique":"softer|precise","source":"edge|center","choke":0..100,"size":px,"range":1..100=50,"contour":name|curve,"antiAlias":bool,"noise":0..100,"add":bool}"##
|
||||
),
|
||||
style_cmd!(
|
||||
"stroke",
|
||||
@@ -1343,6 +1341,9 @@ mod satin_defaults_tests;
|
||||
#[cfg(test)]
|
||||
mod outer_glow_defaults_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod inner_glow_defaults_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod inner_shadow_ranges_tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! #14917: the Inner Glow page's factory values (Screen, 35 %, Noise 0, white, Softer, Edge,
|
||||
//! Choke 0, Size 7, Linear, Anti-aliased off, Range 50) and the rule that a glow already stored
|
||||
//! keeps its own values. The measured pixels of the factory glow sit within 1 level of the
|
||||
//! reference application's on the white test document.
|
||||
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
use serde_json::json;
|
||||
|
||||
/// The issue's test document: 400 x 300 px at 72 ppi, RGB 8 bit, a white Background and a pixel
|
||||
/// layer with an orange (255,128,0) rectangle at x 100..299, y 75..224.
|
||||
fn test_document() -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "background": "#ffffff"})).unwrap();
|
||||
let layer = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.edit("Pixels", |doc, _| {
|
||||
let orange = [1.0, 128.0 / 255.0, 0.0, 1.0];
|
||||
doc.layer_mut(photocraft_doc::LayerId(layer)).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::from_xywh(100, 75, 200, 150), &orange);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The one glow the active layer carries, as an inner glow.
|
||||
fn inner_glow(s: &Session) -> Glow {
|
||||
let d = s.active().unwrap();
|
||||
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
|
||||
match l.effects.items.as_slice() {
|
||||
[Effect::InnerGlow(g)] => g.clone(),
|
||||
other => panic!("no inner glow: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// #14917: Layer > Layer Style > Inner Glow... on a layer without one starts from the reference
|
||||
/// application's factory values; the dialog seeds a new instance from `effect_defaults`.
|
||||
#[test]
|
||||
fn a_new_inner_glow_starts_at_the_factory_values() {
|
||||
let d = effect_defaults("innerGlow");
|
||||
assert_eq!(d["blend"], json!("Screen"), "blend");
|
||||
assert_eq!(d["opacity"], json!(35), "opacity");
|
||||
assert_eq!(d["noise"], json!(0), "noise");
|
||||
assert_eq!(d["color"], json!("#ffffff"), "colour");
|
||||
assert_eq!(d["technique"], json!("softer"), "technique");
|
||||
assert_eq!(d["source"], json!("edge"), "source");
|
||||
assert_eq!(d["choke"], json!(0), "choke");
|
||||
assert_eq!(d["size"], json!(7), "size");
|
||||
assert_eq!(d["contour"], json!("Linear"), "contour");
|
||||
assert_eq!(d["antiAlias"], json!(false), "anti-aliased");
|
||||
assert_eq!(d["range"], json!(50), "range");
|
||||
}
|
||||
|
||||
/// #14917: `layer.layerStyle.innerGlow` without params makes the same effect the page starts at.
|
||||
#[test]
|
||||
fn an_inner_glow_command_without_params_makes_the_factory_effect() {
|
||||
let mut s = session();
|
||||
s.execute("layer.layerStyle.innerGlow", json!({})).unwrap();
|
||||
let g = inner_glow(&s);
|
||||
assert_eq!(g.common.blend, BlendMode::Screen, "blend mode");
|
||||
assert!((g.common.opacity * 100.0 - 35.0).abs() < 1e-4, "opacity {} %", g.common.opacity * 100.0);
|
||||
let FxPaint::Color(c) = g.paint else { panic!("not a plain colour: {:?}", g.paint) };
|
||||
let rgb = c.to_rgb();
|
||||
assert!(rgb.iter().all(|v| (v - 1.0).abs() < 1e-4), "colour {rgb:?} is not white");
|
||||
assert_eq!((g.technique, g.source, g.spread, g.size), (GlowTechnique::Softer, GlowSource::Edge, 0.0, 7.0));
|
||||
assert!(matches!(g.contour, Contour::Linear), "contour {:?}", g.contour);
|
||||
assert!(!g.anti_alias, "anti-aliased");
|
||||
assert!((g.range - 0.5).abs() < 1e-4, "range {}", g.range);
|
||||
assert_eq!(g.noise, 0.0, "noise");
|
||||
}
|
||||
|
||||
/// #14917: Reset to Default reads these factory values through `layer.layerStyle.defaultFor`
|
||||
/// until a Make Default stores other ones; the saved values keep winning (the Make Default path
|
||||
/// is not measured, so it keeps today's behaviour).
|
||||
#[test]
|
||||
fn reset_to_default_restores_the_inner_glow_factory_values() {
|
||||
let mut s = session();
|
||||
let d = s.execute("layer.layerStyle.defaultFor", json!({"kind": "innerGlow"})).unwrap();
|
||||
assert_eq!(d["user"], json!(false));
|
||||
assert_eq!((d["params"]["opacity"].as_f64(), d["params"]["color"].as_str(), d["params"]["size"].as_f64()), (Some(35.0), Some("#ffffff"), Some(7.0)));
|
||||
s.execute("layer.layerStyle.makeDefault", json!({"kind": "innerGlow", "params": {"opacity": 12, "size": 3}})).unwrap();
|
||||
let saved = s.execute("layer.layerStyle.defaultFor", json!({"kind": "innerGlow"})).unwrap();
|
||||
assert_eq!(saved["user"], json!(true));
|
||||
assert_eq!((saved["params"]["opacity"].as_f64(), saved["params"]["size"].as_f64()), (Some(12.0), Some(3.0)), "a saved default still wins");
|
||||
}
|
||||
|
||||
/// #14917 measured: OK on the factory values over the white test document. Top edge of the
|
||||
/// flattened image at x 200, y 75 inwards to 81, R.G.B; the reference application's are
|
||||
/// 255.166.76 255.155.54 255.146.36 255.139.22 255.133.11 255.129.3 255.128.0, within 1 level.
|
||||
#[test]
|
||||
fn the_factory_inner_glow_paints_the_measured_edge() {
|
||||
let mut s = test_document();
|
||||
s.execute("layer.layerStyle.innerGlow", json!({})).unwrap();
|
||||
let d = s.active().unwrap();
|
||||
let px = photocraft_compose::render(&d.doc, d.doc.bounds()).into_px();
|
||||
let rgb = |x: usize, y: usize| px[y * 400 + x].map(|v| (v * 255.0).round() as i32);
|
||||
for (y, want) in
|
||||
[(75, [255, 166, 76]), (76, [255, 155, 54]), (77, [255, 146, 36]), (78, [255, 139, 22]), (79, [255, 133, 11]), (80, [255, 129, 3]), (81, [255, 128, 0])]
|
||||
{
|
||||
let got = rgb(200, y);
|
||||
assert!(got[..3].iter().zip(want).all(|(g, w)| (g - w).abs() <= 1), "top edge at (200, {y}): {:?}, the reference gives {want:?}", &got[..3]);
|
||||
}
|
||||
}
|
||||
|
||||
/// #14917: an Inner Glow the document already carries keeps the values it was read with. The
|
||||
/// Layer Style dialog's OK (and so a PSD or `.pcraft` effect edited in it) goes through
|
||||
/// `layer.layerStyle.replace` with the effect's own snapshot: absent params leave it alone.
|
||||
#[test]
|
||||
fn a_stored_inner_glow_keeps_its_own_values_through_replace() {
|
||||
let mut s = session();
|
||||
s.execute("layer.layerStyle.innerGlow", json!({"opacity": 75, "color": "#ffffbe", "size": 5})).unwrap();
|
||||
let stored = inner_glow(&s);
|
||||
let snapshot = serde_json::to_value(Effect::InnerGlow(stored.clone())).unwrap();
|
||||
s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "innerGlow", "params": {}, "fx": snapshot}]})).unwrap();
|
||||
let kept = inner_glow(&s);
|
||||
assert_eq!(kept, stored, "an edited effect list left the glow's values alone");
|
||||
assert!((kept.common.opacity * 100.0 - 75.0).abs() < 1e-4 && (kept.size - 5.0).abs() < 1e-4, "kept {kept:?}");
|
||||
}
|
||||
@@ -89,22 +89,3 @@ fn a_stored_outer_glow_keeps_its_own_values_through_replace() {
|
||||
assert_eq!(kept, stored, "an edited effect list left the glow's values alone");
|
||||
assert!((kept.common.opacity * 100.0 - 75.0).abs() < 1e-4 && (kept.size - 5.0).abs() < 1e-4, "kept {kept:?}");
|
||||
}
|
||||
|
||||
/// #14944 is only about the Outer Glow page; the Inner Glow's factory values are #14917 and stay
|
||||
/// as they are today (the two glows share their fresh effect in the engine).
|
||||
#[test]
|
||||
fn an_inner_glow_still_starts_at_todays_values() {
|
||||
let d = effect_defaults("innerGlow");
|
||||
assert_eq!((d["opacity"].as_f64(), d["color"].as_str(), d["size"].as_f64()), (Some(75.0), Some("#ffffbe"), Some(5.0)));
|
||||
let mut s = session();
|
||||
s.execute("layer.layerStyle.innerGlow", json!({})).unwrap();
|
||||
let g = match &s.active().unwrap().doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().effects.items[0] {
|
||||
Effect::InnerGlow(g) => g.clone(),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert!((g.common.opacity * 100.0 - 75.0).abs() < 1e-4, "opacity {}", g.common.opacity);
|
||||
assert_eq!(g.size, 5.0, "size");
|
||||
let FxPaint::Color(c) = g.paint else { panic!("{:?}", g.paint) };
|
||||
let rgb = c.to_rgb();
|
||||
assert!((rgb[0] - 1.0).abs() < 1e-3 && (rgb[1] - 1.0).abs() < 1e-3 && (rgb[2] - 190.0 / 255.0).abs() < 1e-3, "colour {rgb:?}");
|
||||
}
|
||||
|
||||
@@ -309,6 +309,9 @@ pub struct Session {
|
||||
next_pending_preflight: u64,
|
||||
/// Shared native memory supervision, owned and stopped by the last session using it.
|
||||
scratch_runtime: Option<scratch::Runtime>,
|
||||
/// The scratch disk and memory settings [`Session::apply_prefs`] last configured: an edit of
|
||||
/// other preferences configures nothing again.
|
||||
scratch_applied: Option<scratch::Settings>,
|
||||
/// [`photocraft_raster::spill::epoch`] when History's byte limits were last applied: a
|
||||
/// scratch disk that pauses or resumes changes the limit ([`Session::sync_scratch_state`]).
|
||||
scratch_epoch: u64,
|
||||
@@ -334,6 +337,8 @@ mod embed_all_linked_tests;
|
||||
mod fill_layer_mode_tests;
|
||||
#[cfg(test)]
|
||||
mod new_layer_name_counter_tests;
|
||||
#[cfg(test)]
|
||||
mod quick_mask_history_name_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod second_keys_zoom_actions_tests;
|
||||
|
||||
@@ -1902,7 +1902,11 @@ impl Session {
|
||||
/// missing-glyph protection.
|
||||
pub fn apply_prefs(&mut self) {
|
||||
self.scratch_runtime.get_or_insert_with(crate::scratch::Runtime::default);
|
||||
crate::scratch::configure(self.prefs());
|
||||
let scratch = crate::scratch::Settings::of(self.prefs());
|
||||
if self.scratch_applied.as_ref() != Some(&scratch) {
|
||||
crate::scratch::configure(&scratch);
|
||||
self.scratch_applied = Some(scratch);
|
||||
}
|
||||
self.scratch_epoch = photocraft_raster::spill::epoch();
|
||||
let n = self.prefs().performance.history_states.max(1) as usize;
|
||||
let bytes = self.prefs().performance.history_cap_bytes();
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! #17493: entering Quick Mask is the History state "Enter Quick Mask", as in the reference
|
||||
//! application; leaving stays "Exit Quick Mask".
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// Runs `cmd` and returns the History states it added.
|
||||
fn added(s: &mut Session, cmd: &str, p: Value) -> Vec<String> {
|
||||
let before = s.active().unwrap().history.entries().len();
|
||||
s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
|
||||
s.active().unwrap().history.entries()[before..].to_vec()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entering_and_leaving_quick_mask_name_their_states() {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 40, "height": 40})).unwrap();
|
||||
assert_eq!(added(&mut s, "select.editInQuickMaskMode", json!({"on": true})), ["Enter Quick Mask"]);
|
||||
assert_eq!(added(&mut s, "select.editInQuickMaskMode", json!({"on": false})), ["Exit Quick Mask"]);
|
||||
}
|
||||
@@ -129,42 +129,101 @@ mod native {
|
||||
// If configure uses this query even once, it pauses for lack of room. This catches an
|
||||
// override that is missing or is installed after configuring the scratch directory.
|
||||
photocraft_raster::spill::set_volume_space_for_tests(|_| Some((0, 64 << 30)));
|
||||
super::super::configure(&crate::prefs::Preferences::default());
|
||||
super::super::configure(&super::super::Settings::of(&crate::prefs::Preferences::default()));
|
||||
assert!(!photocraft_raster::spill::paused());
|
||||
let room = (32_u64 << 30) - (64_u64 << 30) / 20;
|
||||
assert_eq!(photocraft_raster::spill::scratch_capacity(), Some(room - room / 64));
|
||||
}
|
||||
|
||||
/// A preference edit that changes neither Memory Usage nor the scratch disks configures
|
||||
/// neither again: a dragged dialog remembers its place through a preference edit every
|
||||
/// frame, and configuring took milliseconds each time.
|
||||
#[test]
|
||||
fn unrelated_preference_edits_leave_the_scratch_disk_alone() {
|
||||
const CHILD: &str = "PHOTOCRAFT_SCRATCH_UNRELATED_EDIT_TEST_CHILD";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "scratch::native::tests::unrelated_preference_edits_leave_the_scratch_disk_alone"])
|
||||
.env(CHILD, "1")
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "isolated scratch test failed: {status}");
|
||||
return;
|
||||
}
|
||||
|
||||
let mut session = crate::Session::new();
|
||||
// As at startup (`prefs_ui::startup`).
|
||||
session.apply_prefs();
|
||||
let configured = photocraft_raster::memory::configuration_generation;
|
||||
let before = configured();
|
||||
session.edit_prefs(|p| {
|
||||
p.sections.insert("photocraft.test.window".into(), serde_json::json!({"x": 1}));
|
||||
});
|
||||
assert_eq!(configured(), before, "a section edit configured the scratch disk again");
|
||||
session.edit_prefs(|p| p.performance.memory_usage_percent = Some(p.performance.memory_usage_percent.unwrap_or(70) - 10));
|
||||
assert!(configured() > before, "a Memory Usage edit must reach the memory budgets");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn configure(prefs: &Preferences) {
|
||||
/// What [`configure`] reads from the preferences. An edit that leaves it the same leaves the
|
||||
/// scratch disk and the memory budgets as they are ([`crate::Session::apply_prefs`]): configuring
|
||||
/// them again re-measures memory, probes the scratch folder and restarts a paused disk's backoff,
|
||||
/// which takes milliseconds, and preference edits come once per frame while a remembered window
|
||||
/// is dragged.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Settings {
|
||||
percent: Option<u8>,
|
||||
absolute_mb: u32,
|
||||
/// The first enabled scratch disk.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
dir: Option<std::path::PathBuf>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
size_limit_mb: u32,
|
||||
/// The tile budget's override (`PHOTOCRAFT_TILE_BUDGET_MB`), when set.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
tile_override: Option<usize>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
pub(crate) fn of(prefs: &Preferences) -> Self {
|
||||
Settings {
|
||||
percent: prefs.performance.memory_usage_percent,
|
||||
// The web build's cap applies here too (effective_memory_usage_mb).
|
||||
absolute_mb: prefs.performance.effective_memory_usage_mb(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
dir: prefs
|
||||
.scratch_disks
|
||||
.disks
|
||||
.iter()
|
||||
.find(|d| d.enabled && !d.path.trim().is_empty())
|
||||
.map(|d| if d.path.trim() == "(system temp)" { std::env::temp_dir() } else { std::path::PathBuf::from(d.path.trim()) }),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
size_limit_mb: prefs.scratch_disks.size_limit_mb,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
tile_override: std::env::var_os("PHOTOCRAFT_TILE_BUDGET_MB").is_some().then(|| prefs.performance.tile_budget_bytes()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Configures the memory budgets and the scratch disk as `settings` say.
|
||||
pub(crate) fn configure(settings: &Settings) {
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
photocraft_raster::spill::use_test_volume_space();
|
||||
let budget = photocraft_raster::memory::configure(photocraft_raster::memory::Policy {
|
||||
percent: prefs.performance.memory_usage_percent,
|
||||
// The web build's cap applies here too (effective_memory_usage_mb).
|
||||
absolute_bytes: u64::from(prefs.performance.effective_memory_usage_mb()).saturating_mul(1 << 20),
|
||||
percent: settings.percent,
|
||||
absolute_bytes: u64::from(settings.absolute_mb).saturating_mul(1 << 20),
|
||||
});
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let dir = prefs
|
||||
.scratch_disks
|
||||
.disks
|
||||
.iter()
|
||||
.find(|d| d.enabled && !d.path.trim().is_empty())
|
||||
.map(|d| if d.path.trim() == "(system temp)" { std::env::temp_dir() } else { std::path::PathBuf::from(d.path.trim()) });
|
||||
// An unusable or full directory pauses eviction without dropping resident pixels and
|
||||
// is retried with backoff; History's byte limit applies meanwhile (sync_scratch_state).
|
||||
// The reason is exposed in ui.inspect and the application's status bar.
|
||||
let tiles = if std::env::var_os("PHOTOCRAFT_TILE_BUDGET_MB").is_some() {
|
||||
prefs.performance.tile_budget_bytes()
|
||||
} else {
|
||||
usize::try_from(budget.tile_bytes).unwrap_or(usize::MAX)
|
||||
};
|
||||
let limit = prefs.scratch_disks.size_limit_mb;
|
||||
let tiles = settings.tile_override.unwrap_or_else(|| usize::try_from(budget.tile_bytes).unwrap_or(usize::MAX));
|
||||
let limit = settings.size_limit_mb;
|
||||
photocraft_raster::spill::set_size_cap((limit > 0).then(|| u64::from(limit).saturating_mul(1 << 20)));
|
||||
let _ = photocraft_raster::spill::configure(dir.as_deref(), tiles);
|
||||
let _ = photocraft_raster::spill::configure(settings.dir.as_deref(), tiles);
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = (prefs, budget);
|
||||
let _ = budget;
|
||||
}
|
||||
|
||||
@@ -58,6 +58,7 @@ pub const SHELL_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
|
||||
("view.zoomOut", "Zoom Out", &["View"], Some("Cmd+-")),
|
||||
("view.fitOnScreen", "Fit on Screen", &["View"], Some("Cmd+0")),
|
||||
("view.actualPixels", "100%", &["View"], Some("Cmd+1")),
|
||||
("view.actualSize", "Actual Size", &["View"], None),
|
||||
("view.rotateView", "Rotate View", &[], None),
|
||||
("view.rotateLeft", "Rotate View Left", &["View"], Some("Alt+Shift+,")),
|
||||
("view.rotateRight", "Rotate View Right", &["View"], Some("Alt+Shift+.")),
|
||||
|
||||
@@ -19,6 +19,8 @@ mod gradient_alpha_method_tests;
|
||||
mod gradient_behind_mode_tests;
|
||||
#[cfg(test)]
|
||||
mod gradient_mask_history_name_tests;
|
||||
#[cfg(test)]
|
||||
mod gradient_mask_opacity_half_tests;
|
||||
pub mod paint_cmds;
|
||||
pub mod pick_cmds;
|
||||
pub mod redeye_cmds;
|
||||
|
||||
@@ -1166,6 +1166,9 @@ fn presets_set_current(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn has_selection_and_pixels(s: &Session) -> std::result::Result<(), String> {
|
||||
let d = s.active().ok_or("no document")?;
|
||||
if crate::pattern_cmds::layer_mask_targeted(s) {
|
||||
return Err("a layer mask is the target".into());
|
||||
}
|
||||
// The area the command reads (selection, else canvas) is limited, not just the painted
|
||||
// extent, like Photoshop (#14275).
|
||||
let area = d.doc.selection.as_ref().map_or_else(|| d.doc.bounds(), |sel| sel.content_bounds().intersect(&d.doc.bounds()));
|
||||
@@ -1706,3 +1709,6 @@ mod filter_mask_stroke_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod define_brush_size_limit_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod define_brush_mask_target_tests;
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
//! #18232: Define Brush Preset (and the brush command it runs) and Define Pattern are greyed and refused while a layer
|
||||
//! mask is the edit target: a pixel layer's or a group's mask targeted, or an adjustment layer with its mask. Targeting
|
||||
//! the composite again, or deleting the adjustment layer's mask, makes them available. Other targets and layer kinds
|
||||
//! keep today's gates.
|
||||
|
||||
use super::*;
|
||||
|
||||
const COMMANDS: [&str; 3] = ["edit.defineBrushPreset", "brush.defineFromSelection", "edit.definePattern"];
|
||||
|
||||
/// A white 60 x 40 document with a new layer holding a black rectangle, the layer active.
|
||||
fn document() -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 60, "height": 40, "background": "#ffffff"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Tip"})).unwrap();
|
||||
s.edit("BrushSrc", |doc, active| {
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 25), &[0.0, 0.0, 0.0, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn target(s: &mut Session, channel: Value) {
|
||||
s.execute("channel.target", json!({"channel": channel})).unwrap();
|
||||
}
|
||||
|
||||
/// The brush, the brush presets, the pattern library and the document, to show that a refusal changes none of them.
|
||||
fn snapshot(s: &Session) -> (BrushSettings, Vec<BrushPreset>, usize, usize) {
|
||||
let patterns = s.patterns.items.len();
|
||||
((*s.tools.brush).clone(), s.tools.presets.to_vec(), patterns, s.active().unwrap().history.past_len())
|
||||
}
|
||||
|
||||
fn assert_refused(s: &mut Session, case: &str) {
|
||||
for command in COMMANDS {
|
||||
assert!(s.disabled_reason(command).is_some(), "{case}: {command} stays enabled");
|
||||
let before = snapshot(s);
|
||||
assert!(s.execute(command, json!({"name": "Refused"})).is_err(), "{case}: {command} ran");
|
||||
assert!(snapshot(s) == before, "{case}: {command} changed the brush, the presets, the patterns or the History");
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_enabled(s: &mut Session, case: &str) {
|
||||
for command in COMMANDS {
|
||||
assert_eq!(s.disabled_reason(command), None, "{case}: {command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pixel_layers_targeted_mask_greys_them() {
|
||||
for enabled in [true, false] {
|
||||
let mut s = document();
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
if !enabled {
|
||||
s.execute("layer.layerMask.enabled", json!({"enabled": false})).unwrap();
|
||||
}
|
||||
target(&mut s, json!("mask"));
|
||||
assert_refused(&mut s, if enabled { "a pixel layer's mask" } else { "a pixel layer's disabled mask" });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_targeted_mask_greys_them() {
|
||||
let mut s = document();
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
target(&mut s, json!("mask"));
|
||||
assert_refused(&mut s, "a group's mask");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_adjustment_layer_greys_them_until_its_mask_is_deleted() {
|
||||
let mut s = document();
|
||||
s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap();
|
||||
assert_refused(&mut s, "a new adjustment layer");
|
||||
s.execute("layer.layerMask.delete", json!({})).unwrap();
|
||||
assert_enabled(&mut s, "the adjustment layer without its mask");
|
||||
}
|
||||
|
||||
/// Back on the composite, the items work as before and make the same tip as a document that never targeted a mask.
|
||||
#[test]
|
||||
fn targeting_the_composite_again_enables_them_with_the_same_tip() {
|
||||
let mut plain = document();
|
||||
plain.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
target(&mut plain, json!("composite"));
|
||||
plain.execute("brush.defineFromSelection", json!({"name": "Tip"})).unwrap();
|
||||
|
||||
let mut s = document();
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
target(&mut s, json!("mask"));
|
||||
assert_refused(&mut s, "the mask");
|
||||
target(&mut s, json!("composite"));
|
||||
assert_enabled(&mut s, "the composite again");
|
||||
s.execute("brush.defineFromSelection", json!({"name": "Tip"})).unwrap();
|
||||
assert!(s.tools.brush.tip == plain.tools.brush.tip, "the tip is the one made without a mask target");
|
||||
s.execute("edit.definePattern", json!({"name": "Pattern"})).unwrap();
|
||||
}
|
||||
|
||||
/// With every colour channel hidden and no alpha channel shown, the mask is the picture and the target; showing a colour
|
||||
/// channel or an alpha channel again makes the items available.
|
||||
#[test]
|
||||
fn hiding_every_colour_channel_greys_them_on_a_masked_layer() {
|
||||
let mut s = document();
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
target(&mut s, json!("composite"));
|
||||
s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap();
|
||||
assert_refused(&mut s, "every colour channel hidden");
|
||||
s.execute("channel.setVisible", json!({"channel": {"color": 0}, "visible": true})).unwrap();
|
||||
assert_enabled(&mut s, "one colour channel shown again");
|
||||
|
||||
s.execute("channel.new", json!({})).unwrap();
|
||||
target(&mut s, json!("composite"));
|
||||
s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap();
|
||||
s.execute("channel.setVisible", json!({"channel": {"alpha": 0}, "visible": true})).unwrap();
|
||||
assert_enabled(&mut s, "an alpha channel shown");
|
||||
|
||||
// Without a mask there is nothing else to target.
|
||||
let mut s = document();
|
||||
s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap();
|
||||
assert_enabled(&mut s, "no mask, every colour channel hidden");
|
||||
}
|
||||
|
||||
/// Not a layer mask target: these keep today's gates.
|
||||
#[test]
|
||||
fn other_targets_and_layer_kinds_stay_enabled() {
|
||||
// A pixel layer with a mask, the composite targeted.
|
||||
let mut s = document();
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
assert_enabled(&mut s, "a masked pixel layer, composite targeted");
|
||||
|
||||
// An alpha channel, and Quick Mask.
|
||||
s.execute("channel.new", json!({})).unwrap();
|
||||
target(&mut s, json!({"alpha": 0}));
|
||||
assert_enabled(&mut s, "an alpha channel");
|
||||
target(&mut s, json!("composite"));
|
||||
s.execute("select.editInQuickMaskMode", json!({})).unwrap();
|
||||
assert_enabled(&mut s, "Quick Mask");
|
||||
|
||||
// A locked layer, a group, the Background and a Solid Color fill layer with its mask.
|
||||
let mut s = document();
|
||||
s.execute("layer.setProps", json!({"locks": {"all": true}})).unwrap();
|
||||
assert_enabled(&mut s, "a locked layer");
|
||||
let mut s = document();
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
assert_enabled(&mut s, "a group");
|
||||
let background = s.active().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.select", json!({"layer": background.0})).unwrap();
|
||||
assert_enabled(&mut s, "the Background");
|
||||
s.execute("layer.newFillLayer.solidColor", json!({"color": "#336699"})).unwrap();
|
||||
assert_enabled(&mut s, "a Solid Color fill layer");
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
use photocraft_color::BlendMode;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Session, channel_cmds};
|
||||
|
||||
const MASK_LEVEL: f32 = 128.0 / 255.0;
|
||||
|
||||
fn seeded_surface(mode: &str, depth: u8, target: &Value) -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 40, "height": 8, "mode": mode, "depth": depth, "background": "transparent"})).unwrap();
|
||||
match target.as_str() {
|
||||
Some("mask") => s.execute("layer.layerMask.revealAll", json!({})).unwrap(),
|
||||
Some("quickMask") => s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(),
|
||||
Some("pixels") => Value::Null,
|
||||
_ => s.execute("channel.new", json!({})).unwrap(),
|
||||
};
|
||||
let active = s.active().unwrap().active_layer;
|
||||
let params = json!({"target": target});
|
||||
s.edit("Seed the backdrop", |doc, _| {
|
||||
let (surface, _) = channel_cmds::target_surface(doc, active, ¶ms)?;
|
||||
let gray = [MASK_LEVEL];
|
||||
let rgba = [MASK_LEVEL, MASK_LEVEL, MASK_LEVEL, 1.0];
|
||||
let sample: &[f32] = if target == "pixels" { &rgba } else { &gray };
|
||||
for x in 0..40 {
|
||||
surface.write_pixel(x, 3, sample);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn gradient_row(mut s: Session, target: &Value, blend: &str) -> Vec<f32> {
|
||||
let params = json!({
|
||||
"from": [4, 3], "to": [32, 3], "stops": [[0, "#000000"], [1, "#ffffff"]],
|
||||
"target": target, "mode": blend, "method": "smooth", "dither": false
|
||||
});
|
||||
s.execute("paint.gradient", params.clone()).unwrap();
|
||||
let state = s.active().unwrap();
|
||||
let surface = channel_cmds::read_target_surface(&state.doc, state.active_layer, ¶ms).unwrap();
|
||||
(0..40).map(|x| surface.pixel(x, 3)[0]).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonseparable_gradient_modes_match_normal_throughout_rgb_layer_masks() {
|
||||
let target = json!("mask");
|
||||
for depth in [8, 16] {
|
||||
let normal = gradient_row(seeded_surface("rgb", depth, &target), &target, "normal");
|
||||
assert_eq!(normal[0], 0.0);
|
||||
assert_eq!(normal[39], 1.0);
|
||||
for mode in ["darkerColor", "lighterColor", "hue", "saturation", "color", "luminosity"] {
|
||||
assert_eq!(gradient_row(seeded_surface("rgb", depth, &target), &target, mode), normal, "{depth}-bit {mode}");
|
||||
}
|
||||
let darken = gradient_row(seeded_surface("rgb", depth, &target), &target, "darken");
|
||||
assert_eq!(darken[0], 0.0);
|
||||
assert!((darken[39] - MASK_LEVEL).abs() < 1.0 / 65535.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_the_rgb_mask_depths_darker_color_still_keeps_the_darker_backdrop() {
|
||||
for (mode, depth, target) in [
|
||||
("rgb", 8, json!("pixels")),
|
||||
("rgb", 8, json!("quickMask")),
|
||||
("rgb", 8, json!({"channel": 0})),
|
||||
("rgb", 32, json!("mask")),
|
||||
("gray", 16, json!("mask")),
|
||||
] {
|
||||
let normal = gradient_row(seeded_surface(mode, depth, &target), &target, "normal");
|
||||
// Float mask luma can be one representable step below white. Integer storage rounds it.
|
||||
let white_tolerance = if depth == 32 { 4.0 * f32::EPSILON } else { 0.0 };
|
||||
assert!((normal[39] - 1.0).abs() <= white_tolerance, "{mode} {depth}-bit {target}: {}", normal[39]);
|
||||
let row = gradient_row(seeded_surface(mode, depth, &target), &target, BlendMode::DarkerColor.label());
|
||||
assert!((row[39] - MASK_LEVEL).abs() < 1.0 / 65535.0, "{mode} {depth}-bit {target}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! #18669: at 50% opacity a gradient covers 128/255 of a layer mask.
|
||||
|
||||
use photocraft_raster::Surface;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn document(mode: &str, depth: u32) -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 64, "height": 8, "mode": mode, "depth": depth, "background": "transparent"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn gradient(opacity: f64, target: Value, method: Option<&str>) -> Value {
|
||||
let mut p = json!({"from": [8, 4], "to": [56, 4], "colors": ["#000000", "#ffffff"], "opacity": opacity, "target": target, "dither": false});
|
||||
if let Some(method) = method {
|
||||
p["method"] = json!(method);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
fn target<'a>(s: &'a Session, p: &Value) -> &'a Surface {
|
||||
let state = s.active().unwrap();
|
||||
crate::channel_cmds::read_target_surface(&state.doc, state.active_layer, p).unwrap()
|
||||
}
|
||||
|
||||
fn layer_mask_row(mode: &str, depth: u32, opacity: f64, method: Option<&str>) -> [f32; 3] {
|
||||
let mut s = document(mode, depth);
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
let p = gradient(opacity, json!("mask"), method);
|
||||
s.execute("paint.gradient", p.clone()).unwrap();
|
||||
[4, 32, 60].map(|x| target(&s, &p).pixel(x, 4)[0])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_opacity_leaves_127_levels_of_white_on_the_layer_mask() {
|
||||
for (mode, depth, step) in [
|
||||
("rgb", 8, 1.0 / 255.0),
|
||||
("rgb", 16, 1.0 / 65535.0),
|
||||
("rgb", 32, 0.0),
|
||||
("gray", 8, 1.0 / 255.0),
|
||||
("gray", 16, 1.0 / 65535.0),
|
||||
("gray", 32, 0.0),
|
||||
("cmyk", 8, 1.0 / 255.0),
|
||||
("lab", 8, 1.0 / 255.0),
|
||||
] {
|
||||
// The desktop dispatches the Classic gradient without a method. The report used Smooth.
|
||||
for method in [None, Some("smooth")] {
|
||||
let case = format!("{mode}/{depth} {method:?}");
|
||||
let [black, middle, white] = layer_mask_row(mode, depth, 50.0, method);
|
||||
let [full_black, full_middle, full_white] = layer_mask_row(mode, depth, 100.0, method);
|
||||
assert_eq!(full_black, 0.0, "{case} at full opacity");
|
||||
assert!((full_white - 1.0).abs() <= 0.00001, "{case}: white end at full opacity {full_white}");
|
||||
assert!((black - 127.0 / 255.0).abs() <= 0.5 * step + 0.00001, "{case}: black end left {black} white");
|
||||
let expected_middle = 1.0 - (1.0 - full_middle) * (128.0 / 255.0);
|
||||
assert!((middle - expected_middle).abs() <= step + 0.00001, "{case}: ramp midpoint {middle}, expected {expected_middle}");
|
||||
assert!((white - 1.0).abs() <= 0.00001, "{case}: white end left {white} white");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_opacity_and_non_layer_mask_targets_keep_the_requested_coverage() {
|
||||
// Include a value that rounds to 50% after the command converts to f32.
|
||||
for opacity in [49.9, 50.000_000_1] {
|
||||
let [black, _, _] = layer_mask_row("rgb", 32, opacity, Some("smooth"));
|
||||
assert!((f64::from(black) - (1.0 - opacity / 100.0)).abs() < 0.00001, "{opacity}% opacity left {black} white");
|
||||
}
|
||||
|
||||
let mut s = document("rgb", 32);
|
||||
let pixels = gradient(50.0, json!("pixels"), Some("smooth"));
|
||||
s.execute("paint.gradient", pixels.clone()).unwrap();
|
||||
assert!((target(&s, &pixels).pixel(4, 4)[3] - 0.5).abs() < 0.00001, "pixel coverage");
|
||||
|
||||
s.execute("channel.new", json!({"fill": "white"})).unwrap();
|
||||
let alpha = gradient(50.0, json!({"channel": 0}), Some("smooth"));
|
||||
s.execute("paint.gradient", alpha.clone()).unwrap();
|
||||
assert!((target(&s, &alpha).pixel(4, 4)[0] - 0.5).abs() < 0.00001, "saved alpha channel");
|
||||
|
||||
s.execute("select.all", json!({})).unwrap();
|
||||
s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap();
|
||||
let quick_mask = gradient(50.0, json!("quickMask"), Some("smooth"));
|
||||
s.execute("paint.gradient", quick_mask.clone()).unwrap();
|
||||
assert!((target(&s, &quick_mask).pixel(4, 4)[0] - 0.5).abs() < 0.00001, "Quick Mask");
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const MASK_ROW: [f32; 21] =
|
||||
[0.0, 15.0, 34.0, 53.0, 73.0, 93.0, 113.0, 131.0, 148.0, 164.0, 178.0, 191.0, 204.0, 215.0, 226.0, 235.0, 242.0, 248.0, 253.0, 255.0, 255.0];
|
||||
|
||||
fn row(mode: &str, depth: u8, target: &str, method: &str, stops: Value, opacity: Option<Value>) -> Vec<f32> {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 800, "height": 16, "mode": mode, "depth": depth, "background": "transparent"})).unwrap();
|
||||
if target == "mask" {
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
}
|
||||
let mut params = json!({"from": [100, 10], "to": [700, 10], "stops": stops, "method": method, "dither": false, "target": target});
|
||||
if let Some(opacity) = opacity {
|
||||
params["transparency"] = opacity;
|
||||
}
|
||||
s.execute("paint.gradient", params.clone()).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let surface = crate::channel_cmds::read_target_surface(&st.doc, st.active_layer, ¶ms).unwrap();
|
||||
(0..800).map(|x| if target == "mask" { surface.pixel(x, 10)[0] } else { surface.rgba(x, 10)[3] }).map(|value| value * 255.0).collect()
|
||||
}
|
||||
|
||||
fn fade(mode: &str, depth: u8, target: &str, method: &str) -> Vec<f32> {
|
||||
row(mode, depth, target, method, json!([[0, "#000000"], [1, "#000000"]]), Some(json!([[0, 100], [1, 0]])))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_transparency_follows_the_measured_layer_mask_fade() {
|
||||
for mode in ["rgb", "gray", "cmyk", "lab"] {
|
||||
for depth in [8, 16] {
|
||||
let output = fade(mode, depth, "mask", "smooth");
|
||||
for (i, expected) in MASK_ROW.into_iter().enumerate() {
|
||||
let x = 100 + 30 * i;
|
||||
assert!((output[x] - expected).abs() <= 2.0, "{mode} {depth}-bit, x={x}: {}, expected {expected}", output[x]);
|
||||
}
|
||||
assert!(output.windows(2).all(|w| w[0] <= w[1]));
|
||||
assert_eq!(output[50], 0.0);
|
||||
assert_eq!(output[750], 255.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_mask_fade_keeps_existing_pixel_deep_mask_and_other_method_curves() {
|
||||
let pixels = fade("rgb", 8, "pixels", "smooth");
|
||||
let deep_mask = fade("rgb", 32, "mask", "smooth");
|
||||
for (x, alpha) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] {
|
||||
assert!((pixels[x] - alpha).abs() <= 2.0, "pixel alpha at {x}: {}", pixels[x]);
|
||||
assert!((deep_mask[x] - (255.0 - alpha)).abs() <= 2.0, "float mask at {x}: {}", deep_mask[x]);
|
||||
}
|
||||
|
||||
for method in ["classic", "perceptual", "linear"] {
|
||||
let pixels = fade("rgb", 8, "pixels", method);
|
||||
let mask = fade("rgb", 8, "mask", method);
|
||||
for x in [50, 250, 400, 550, 750] {
|
||||
assert!((pixels[x] + mask[x] - 255.0).abs() <= 1.0, "{method} at {x}: pixel {}, mask {}", pixels[x], mask[x]);
|
||||
}
|
||||
}
|
||||
|
||||
let colors = json!([[0, "#000000"], [1, "#ffffff"]]);
|
||||
let opaque = row("rgb", 16, "mask", "smooth", colors.clone(), None);
|
||||
assert_eq!(opaque, row("rgb", 16, "mask", "smooth", colors, Some(json!([[0, 100], [1, 100]]))));
|
||||
assert_eq!((opaque[50], opaque[750]), (0.0, 255.0));
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
use photocraft_algo::paint::{FillMode, GradientShape, paint_gradient};
|
||||
use photocraft_color::BlendMode;
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::{Surface, from_rgba};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const SOURCE: [f32; 4] = [0.25, 0.5, 0.75, 1.0];
|
||||
|
||||
fn active_surface(s: &Session) -> &Surface {
|
||||
let state = s.active().unwrap();
|
||||
state.doc.layer(state.active_layer.unwrap()).unwrap().surface().unwrap()
|
||||
}
|
||||
|
||||
fn document(mode: &str, depth: u8) -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 16, "height": 8, "mode": mode, "depth": depth, "background": "transparent"})).unwrap();
|
||||
s.edit("Set the three backdrop alphas", |doc, _| {
|
||||
let surface = doc.layers[0].surface_mut().unwrap();
|
||||
let format = surface.format();
|
||||
for (x, alpha) in [(3, 1.0), (4, 0.0), (5, 0.5)] {
|
||||
surface.write_pixel(x, 3, &from_rgba(&format, [0.8, 0.3, 0.2, alpha]));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_uses_the_measured_half_opacity_step_only_on_deep_rgb_and_cmyk_pixels() {
|
||||
for (mode, depth, uses_step) in [("rgb", 8, false), ("rgb", 16, true), ("rgb", 32, true), ("cmyk", 8, false), ("cmyk", 16, true), ("gray", 16, false)] {
|
||||
for blend in [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen] {
|
||||
for (percent, coverage) in [(50.0, if uses_step { 128.0 / 255.0 } else { 0.5 }), (23.5, 0.235)] {
|
||||
let mut s = document(mode, depth);
|
||||
let mut wanted = active_surface(&s).clone();
|
||||
paint_gradient(
|
||||
&mut wanted,
|
||||
Rect::new(0, 0, 16, 8),
|
||||
(2.0, 3.0),
|
||||
(9.0, 3.0),
|
||||
GradientShape::Linear,
|
||||
&[(0.0, SOURCE), (1.0, SOURCE)],
|
||||
false,
|
||||
coverage,
|
||||
FillMode::Blend(blend),
|
||||
false,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
s.execute(
|
||||
"paint.gradient",
|
||||
json!({"from": [2, 3], "to": [9, 3], "colors": [SOURCE, SOURCE], "opacity": percent, "mode": blend.label(), "dither": false}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let actual = active_surface(&s);
|
||||
for x in 3..=5 {
|
||||
assert_eq!(actual.pixel(x, 3), wanted.pixel(x, 3), "{mode} {depth}-bit, {blend:?}, {percent}%, x={x}");
|
||||
}
|
||||
if uses_step && percent == 50.0 {
|
||||
assert!((actual.rgba(4, 3)[3] - 128.0 / 255.0).abs() < 0.0005);
|
||||
assert!((actual.rgba(5, 3)[3] - (0.5 + 64.0 / 255.0)).abs() < 0.0005);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_explicit_classic_uses_the_half_opacity_step() {
|
||||
for (method, coverage) in [("Classic", 128.0 / 255.0), ("linear", 0.5), ("perceptual", 0.5), ("smooth", 0.5)] {
|
||||
let mut s = document("rgb", 32);
|
||||
s.execute("paint.gradient", json!({"from": [2, 3], "to": [9, 3], "colors": [SOURCE, SOURCE], "method": method, "opacity": 50, "dither": false}))
|
||||
.unwrap();
|
||||
let alpha = active_surface(&s).rgba(4, 3)[3];
|
||||
assert!((alpha - coverage).abs() < 0.0005, "{method}: alpha {alpha}, expected {coverage}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_half_opacity_pixel_step_does_not_change_deep_cmyk_layer_masks() {
|
||||
let mut s = document("cmyk", 16);
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
s.execute("paint.gradient", json!({"from": [2, 3], "to": [9, 3], "colors": ["#000000", "#ffffff"], "opacity": 50, "target": "mask", "dither": false}))
|
||||
.unwrap();
|
||||
let state = s.active().unwrap();
|
||||
let mask = &state.doc.layer(state.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface;
|
||||
assert_eq!((mask.pixel(2, 3)[0] * 65535.0).round(), 32768.0);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Paint helpers: Paint Bucket and Gradient tool.
|
||||
|
||||
use photocraft_algo::paint::{FillMode, GradientShape, bucket_fill_inks, bucket_fill_region_inks, paint_gradient};
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::commands::{CommandSpec, parse_blend};
|
||||
@@ -172,7 +173,9 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Photoshop's interpolation (`method`, with `smoothness` 0..=100, default 100) baked into dense
|
||||
// stops, as for Gradient Overlay: Photoshop 27.11's Classic black → white is 0.037 at t = 1/16
|
||||
// where straight stops give 0.0625.
|
||||
let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) {
|
||||
let method_param = p.get("method");
|
||||
let method = method_param.and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name);
|
||||
let stops = match method {
|
||||
Some(m) if stops.len() >= 2 => {
|
||||
let smoothness = (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0);
|
||||
// Smooth at 100 % Smoothness bakes the colour and opacity stops apart: the colours by
|
||||
@@ -181,6 +184,16 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// were not measured in the Gradient tool and keep the merged stops.
|
||||
let split = if m == photocraft_io::GradientMethod::Smooth && smoothness >= 1.0 { split_stops(s, p, fg)? } else { None };
|
||||
match split {
|
||||
Some(split)
|
||||
if crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Mask
|
||||
&& s.active().is_some_and(|st| {
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
matches!(st.doc.mode, ColorMode::Rgb | ColorMode::Grayscale | ColorMode::Cmyk | ColorMode::Lab)
|
||||
&& matches!(st.doc.depth, SampleType::U8 | SampleType::U16)
|
||||
}) =>
|
||||
{
|
||||
smooth_split_stops_with(split, photocraft_io::gradient_bake::bake_smooth_mask_opacity)
|
||||
}
|
||||
Some(split) => smooth_split_stops(split),
|
||||
None => {
|
||||
let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect();
|
||||
@@ -200,15 +213,42 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let reverse = b(p, "reverse", false);
|
||||
let opacity = opacity(p, "paint.gradient")?;
|
||||
let mode = fill_mode(p, "paint.gradient", false)?;
|
||||
let target = crate::channel_cmds::target_of(p);
|
||||
// Masks and channels have no transparency to paint behind: Behind would change nothing there.
|
||||
if mode == FillMode::Behind && crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels {
|
||||
if mode == FillMode::Behind && target != crate::channel_cmds::Target::Pixels {
|
||||
return Err(EngineError::BadParams { cmd: "paint.gradient".into(), msg: "mode `behind` paints only a layer's pixels, not a mask or channel".into() });
|
||||
}
|
||||
let dither = b(p, "dither", true); // Photoshop dithers gradients by default (reduces banding).
|
||||
let layer = if p.get("layer").is_some() { Some(crate::commands::layer_param(s, p)?) } else { s.active().and_then(|st| st.active_layer) };
|
||||
s.edit(step_name(p), |doc, _| {
|
||||
// The measured 50% setting uses 8-bit source coverage for these layer masks and Classic pixel gradients.
|
||||
let opacity = if p.get("opacity").and_then(Value::as_f64) == Some(50.0)
|
||||
&& match target {
|
||||
crate::channel_cmds::Target::Mask => {
|
||||
matches!((doc.mode, doc.depth), (ColorMode::Rgb | ColorMode::Grayscale, _) | (ColorMode::Cmyk | ColorMode::Lab, SampleType::U8))
|
||||
}
|
||||
crate::channel_cmds::Target::Pixels => {
|
||||
(method_param.is_none() || method == Some(photocraft_io::GradientMethod::Classic))
|
||||
&& matches!((doc.mode, doc.depth), (ColorMode::Rgb, SampleType::U16 | SampleType::F32) | (ColorMode::Cmyk, SampleType::U16))
|
||||
}
|
||||
_ => false,
|
||||
} {
|
||||
128.0 / 255.0
|
||||
} else {
|
||||
opacity
|
||||
};
|
||||
let sel = doc.selection.clone();
|
||||
let area = sel.as_ref().map(|m| m.content_bounds()).filter(|r| !r.is_empty()).unwrap_or_else(|| doc.bounds()).intersect(&doc.bounds());
|
||||
// The RGB 8- and 16-bit layer mask uses Normal for modes that need a colour backdrop.
|
||||
let mode = if matches!(mode, FillMode::Blend(blend) if !blend.is_separable())
|
||||
&& crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Mask
|
||||
&& doc.mode == photocraft_color::ColorMode::Rgb
|
||||
&& matches!(doc.depth, photocraft_color::SampleType::U8 | photocraft_color::SampleType::U16)
|
||||
{
|
||||
FillMode::Blend(photocraft_color::BlendMode::Normal)
|
||||
} else {
|
||||
mode
|
||||
};
|
||||
let (surf, lock) = crate::channel_cmds::target_surface(doc, layer, p)?;
|
||||
paint_gradient(surf, area, from, to, shape, &stops, reverse, opacity, mode, dither, sel.as_ref(), lock);
|
||||
Ok(())
|
||||
@@ -234,7 +274,11 @@ pub(crate) const GRADIENT_MASK_STEP: &str = "Draw gradient on mask";
|
||||
/// positions, so the alpha is multiplied in at each one: [`gradients::apply_opacity`] would cut
|
||||
/// every interval into four (385 stops instead of 97), and `paint_gradient` scans the stops for
|
||||
/// every pixel. Positions that differ still go through `apply_opacity`.
|
||||
pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::Stops {
|
||||
pub(crate) fn smooth_split_stops(stops: gradients::FillStops) -> gradients::Stops {
|
||||
smooth_split_stops_with(stops, photocraft_io::bake_gradient_smooth_opacity)
|
||||
}
|
||||
|
||||
fn smooth_split_stops_with((cs, os): gradients::FillStops, bake_opacity: impl FnOnce(Vec<(f32, f32)>, &[f32]) -> Vec<(f32, f32)>) -> gradients::Stops {
|
||||
let mids = vec![0.5; cs.len().saturating_sub(1)];
|
||||
let colours: gradients::Stops = photocraft_io::bake_gradient(cs, &mids, 1.0, photocraft_io::GradientMethod::Smooth)
|
||||
.into_iter()
|
||||
@@ -244,7 +288,7 @@ pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::S
|
||||
})
|
||||
.collect();
|
||||
let omids = vec![0.5; os.len().saturating_sub(1)];
|
||||
let opacity = photocraft_io::bake_gradient_smooth_opacity(os, &omids);
|
||||
let opacity = bake_opacity(os, &omids);
|
||||
if colours.len() != opacity.len() || colours.iter().zip(&opacity).any(|(c, o)| (c.0 - o.0).abs() > 1e-6) {
|
||||
return gradients::apply_opacity(colours, &opacity);
|
||||
}
|
||||
@@ -317,11 +361,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gradient_mask_greyed_modes_tests.rs"]
|
||||
mod gradient_mask_greyed_modes_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod bucket_no_op_history_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod bucket_bitmap_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gradient_mask_smooth_transparency_tests.rs"]
|
||||
mod gradient_mask_smooth_transparency_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod bucket_behind_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gradient_opacity_step_tests.rs"]
|
||||
mod gradient_opacity_step_tests;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//! Background from Layer keeps a single clipped layer on its original base (#17307).
|
||||
|
||||
use photocraft_doc::LayerId;
|
||||
use photocraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
const CONVERT: &str = "layer.new.backgroundFromLayer";
|
||||
|
||||
fn active(session: &Session) -> LayerId {
|
||||
session.active().unwrap().active_layer.unwrap()
|
||||
}
|
||||
|
||||
fn order(session: &Session) -> Vec<LayerId> {
|
||||
session.active().unwrap().doc.layers.iter().map(|layer| layer.id).collect()
|
||||
}
|
||||
|
||||
fn stack() -> (Session, [LayerId; 7]) {
|
||||
let mut session = Session::new();
|
||||
session.execute("file.new", json!({"width": 200, "height": 150, "background": "transparent"})).unwrap();
|
||||
let base = active(&session);
|
||||
session.execute("select.rect", json!({"x": 0, "y": 0, "width": 16, "height": 150})).unwrap();
|
||||
session.execute("edit.fill", json!({"color": "#808080"})).unwrap();
|
||||
session.execute("select.deselect", json!({})).unwrap();
|
||||
session.execute("layer.new.layer", json!({"name": "SO"})).unwrap();
|
||||
session.execute("select.rect", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap();
|
||||
session.execute("edit.fill", json!({"color": "#c81e1e"})).unwrap();
|
||||
session.execute("select.deselect", json!({})).unwrap();
|
||||
session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
|
||||
let smart = active(&session);
|
||||
session.execute("layer.new.layer", json!({"name": "Clipped"})).unwrap();
|
||||
let clipped = active(&session);
|
||||
session.execute("edit.fill", json!({"color": "#1e1ec8"})).unwrap();
|
||||
session.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap();
|
||||
session.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap();
|
||||
let adjustment = active(&session);
|
||||
session.execute("layer.newFillLayer.solidColor", json!({"color": "#4080c0"})).unwrap();
|
||||
let fill = active(&session);
|
||||
session.execute("layer.setProps", json!({"layer": fill.0, "opacity": 0.5})).unwrap();
|
||||
let shape = session.execute("shape.create", json!({"kind": "rect", "rect": [80, 60, 100, 80], "fill": "#308020"})).unwrap();
|
||||
let shape = LayerId(shape["layer"].as_u64().unwrap());
|
||||
session.execute("layer.select", json!({"layer": shape.0})).unwrap();
|
||||
session.execute("layer.new.layer", json!({"name": "Off"})).unwrap();
|
||||
let off = active(&session);
|
||||
let ids = [base, smart, clipped, adjustment, fill, shape, off];
|
||||
assert_eq!(order(&session), ids);
|
||||
(session, ids)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converting_a_clipping_base_moves_its_clip_and_one_undo_restores_the_tree() {
|
||||
let (mut session, [base, smart, clip, adjustment, fill, shape, off]) = stack();
|
||||
session.execute("layer.select", json!({"layer": smart.0})).unwrap();
|
||||
let before = session.active().unwrap().history.past_len();
|
||||
session.execute(CONVERT, json!({})).unwrap();
|
||||
assert_eq!(order(&session), [smart, clip, base, adjustment, fill, shape, off]);
|
||||
let doc = &session.active().unwrap().doc;
|
||||
assert!(doc.is_background(smart));
|
||||
assert!(doc.layer(clip).unwrap().clipped);
|
||||
assert_eq!(active(&session), smart);
|
||||
assert_eq!(session.active().unwrap().history.past_len(), before + 1);
|
||||
session.execute("history.undo", json!({})).unwrap();
|
||||
assert_eq!(order(&session), [base, smart, clip, adjustment, fill, shape, off]);
|
||||
let doc = &session.active().unwrap().doc;
|
||||
assert!(doc.background().is_none());
|
||||
assert!(doc.layer(clip).unwrap().clipped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converting_an_unclipped_layer_or_the_clip_itself_keeps_other_layers_in_order() {
|
||||
for convert_clip in [false, true] {
|
||||
let (mut session, [base, smart, clip, adjustment, fill, shape, off]) = stack();
|
||||
let target = if convert_clip { clip } else { fill };
|
||||
session.execute(CONVERT, json!({"layer": target.0})).unwrap();
|
||||
let expected = if convert_clip { [clip, base, smart, adjustment, fill, shape, off] } else { [fill, base, smart, clip, adjustment, shape, off] };
|
||||
assert_eq!(order(&session), expected);
|
||||
let doc = &session.active().unwrap().doc;
|
||||
assert!(doc.is_background(target));
|
||||
assert_eq!(doc.layer(clip).unwrap().clipped, !convert_clip);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
//! #18228 (Edit › Define Brush Preset runs the brush command of `photocraft-engine-paint`, so this runs here): Define Brush Preset's "Sampled Brush N" default counts the defaults stored in this session. Deleting or
|
||||
//! renaming presets does not lower N, and a preset with such a name from elsewhere (a typed name, an imported set) does
|
||||
//! not raise it, but N skips a number such a preset already uses instead of replacing that preset. A call that stores
|
||||
//! nothing leaves N as it is.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use photocraft_engine::Session;
|
||||
|
||||
const DEFINE: &str = "edit.defineBrushPreset";
|
||||
|
||||
/// Opens a new white document with a black rectangle on a layer, ready for Define Brush Preset.
|
||||
fn new_document(s: &mut Session) {
|
||||
s.execute("file.new", json!({"width": 40, "height": 30, "background": "#ffffff"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.edit("BrushSrc", |doc, active| {
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(5, 5, 20, 15), &[0.0, 0.0, 0.0, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Defines a brush with `params` and returns the name it was stored under.
|
||||
fn define(s: &mut Session, params: Value) -> String {
|
||||
s.execute(DEFINE, params).unwrap();
|
||||
s.tools.current_preset.clone().expect("the new preset is the current brush")
|
||||
}
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
new_document(&mut s);
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_stored_default_raises_the_number() {
|
||||
let mut s = session();
|
||||
let mut names = vec![define(&mut s, json!({}))];
|
||||
for _ in 0..2 {
|
||||
new_document(&mut s);
|
||||
names.push(define(&mut s, json!({})));
|
||||
}
|
||||
assert_eq!(names, ["Sampled Brush 1", "Sampled Brush 2", "Sampled Brush 3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_or_renaming_the_presets_does_not_lower_it() {
|
||||
let mut s = session();
|
||||
let names: Vec<String> = (0..3).map(|_| define(&mut s, json!({}))).collect();
|
||||
for name in &names {
|
||||
s.execute("brush.presets.delete", json!({"name": name})).unwrap();
|
||||
}
|
||||
assert_eq!(define(&mut s, json!({})), "Sampled Brush 4", "after deleting presets 1-3");
|
||||
|
||||
let mut s = session();
|
||||
let first = define(&mut s, json!({}));
|
||||
s.execute("brush.presets.rename", json!({"name": first, "newName": "Renamed"})).unwrap();
|
||||
assert_eq!(define(&mut s, json!({})), "Sampled Brush 2", "after renaming preset 1");
|
||||
}
|
||||
|
||||
/// A preset named "Sampled Brush …" that the default did not make, such as a typed name, does not raise the number.
|
||||
#[test]
|
||||
fn a_typed_sampled_brush_name_does_not_raise_it() {
|
||||
let mut s = session();
|
||||
assert_eq!(define(&mut s, json!({"name": "Sampled Brush 7"})), "Sampled Brush 7");
|
||||
assert_eq!(define(&mut s, json!({})), "Sampled Brush 1", "the first default");
|
||||
}
|
||||
|
||||
/// The default never takes a name a preset already has: storing under it would replace that preset's tip.
|
||||
#[test]
|
||||
fn a_taken_number_is_skipped_and_the_preset_is_kept() {
|
||||
let mut s = session();
|
||||
let user_presets = |s: &Session| s.tools.presets.iter().filter(|b| !b.builtin).map(|b| b.name.clone()).collect::<Vec<_>>();
|
||||
define(&mut s, json!({"name": "Sampled Brush 1"}));
|
||||
let first = define(&mut s, json!({}));
|
||||
assert_ne!(first, "Sampled Brush 1", "the typed preset's name");
|
||||
assert_eq!(user_presets(&s).len(), 2, "both presets are kept: {:?}", user_presets(&s));
|
||||
let second = define(&mut s, json!({}));
|
||||
assert!(![first.as_str(), "Sampled Brush 1"].contains(&second.as_str()), "{second}");
|
||||
assert_eq!(user_presets(&s).len(), 3, "{:?}", user_presets(&s));
|
||||
|
||||
// The store matches names ignoring case, so a typed "sampled brush 1" is taken too.
|
||||
let mut s = session();
|
||||
define(&mut s, json!({"name": "sampled brush 1"}));
|
||||
let first = define(&mut s, json!({}));
|
||||
assert!(!first.eq_ignore_ascii_case("sampled brush 1"), "{first}");
|
||||
assert_eq!(user_presets(&s).len(), 2, "{:?}", user_presets(&s));
|
||||
}
|
||||
|
||||
/// A call that stores no preset leaves the number as it is.
|
||||
#[test]
|
||||
fn a_refused_call_does_not_raise_it() {
|
||||
let mut s = Session::new();
|
||||
assert!(s.execute(DEFINE, json!({})).is_err(), "no document");
|
||||
new_document(&mut s);
|
||||
assert_eq!(define(&mut s, json!({})), "Sampled Brush 1");
|
||||
}
|
||||
@@ -31,3 +31,65 @@ fn colored_pencil_honours_session_background() {
|
||||
fn neon_glow_honours_session_background() {
|
||||
assert_ne!(one("neonGlow", "#ffffff"), one("neonGlow", "#0000ff"), "filter.gallery.neonGlow must honour the session background");
|
||||
}
|
||||
|
||||
/// Stamp uses the selected ink and paper without adding intermediate colors (#9912).
|
||||
#[test]
|
||||
fn stamp_uses_only_the_selected_colors() {
|
||||
for depth in [8, 16, 32] {
|
||||
for (fg, bg, ink, paper) in [("#000000", "#ffffff", [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]), ("#ff0000", "#0000ff", [1.0, 0.0, 0.0], [0.0, 0.0, 1.0])] {
|
||||
for smoothness in [1, 5, 50] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "#808080"})).unwrap();
|
||||
s.execute("tools.setColors", json!({"foreground": fg, "background": bg})).unwrap();
|
||||
s.execute("filter.gallery.stamp", json!({"lightDarkBalance": 25, "smoothness": smoothness})).unwrap();
|
||||
for p in image(&mut s).as_chunks::<4>().0 {
|
||||
assert!(p[..3] == ink || p[..3] == paper, "{depth}-bit, smoothness {smoothness}: Stamp added an intermediate color: {p:?}");
|
||||
assert_eq!(p[3], 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Balance controls the chosen color, with the selection boundary and one-step Undo intact.
|
||||
#[test]
|
||||
fn stamp_balance_selection_and_undo() {
|
||||
for depth in [8, 16, 32] {
|
||||
for (balance, expected) in [(0, 1.0), (40, 0.0), (50, 0.0)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "#808080"})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8, "antiAlias": false})).unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let outside = px(&mut s, 2, 2);
|
||||
s.execute("filter.gallery.stamp", json!({"lightDarkBalance": balance, "smoothness": 1})).unwrap();
|
||||
assert_eq!(px(&mut s, 8, 8), [expected, expected, expected, 1.0]);
|
||||
assert_eq!(px(&mut s, 2, 2), outside);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history + 1);
|
||||
s.undo();
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Smoothness changes spatial detail without adding intermediate colors.
|
||||
#[test]
|
||||
fn stamp_smoothness_changes_spatial_detail() {
|
||||
for depth in [8, 16, 32] {
|
||||
let render = |smoothness| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "#ffffff"})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 6, "y": 6, "width": 4, "height": 4, "antiAlias": false})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s.execute("filter.gallery.stamp", json!({"lightDarkBalance": 25, "smoothness": smoothness})).unwrap();
|
||||
image(&mut s)
|
||||
};
|
||||
let fine = render(1);
|
||||
let smooth = render(50);
|
||||
assert_ne!(fine, smooth, "{depth}-bit: Smoothness must change the spatial result");
|
||||
for p in fine.as_chunks::<4>().0.iter().chain(smooth.as_chunks::<4>().0.iter()) {
|
||||
assert!(p[..3] == [0.0; 3] || p[..3] == [1.0; 3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ mod atn_video_frames;
|
||||
mod auto_blend_layer_kinds;
|
||||
mod average_smart;
|
||||
mod background_and_mask_depth;
|
||||
mod background_from_layer_clip_base;
|
||||
mod background_from_layer_grayscale;
|
||||
mod background_from_layer_history_name;
|
||||
mod background_from_layer_multi_select;
|
||||
@@ -66,6 +67,7 @@ mod crop_content_aware_layers;
|
||||
mod crop_delete_off_background;
|
||||
mod csh_import;
|
||||
mod current_affinity_artboards;
|
||||
mod define_brush_sampled_number;
|
||||
mod duplicate_layer_comps;
|
||||
mod duplicate_slices;
|
||||
mod duplicate_variables;
|
||||
|
||||
@@ -695,7 +695,7 @@ mod tests {
|
||||
assert_eq!(sel_at(&s, 35, 2), 0.0);
|
||||
// History: enter and exit are steps; undo goes back into Quick Mask with the paint.
|
||||
let labels: Vec<String> = s.active().unwrap().history.entries().iter().map(|e| e.to_string()).collect();
|
||||
assert!(labels.iter().any(|l| l.contains("Edit in Quick Mask")) && labels.iter().any(|l| l.contains("Exit Quick Mask")), "{labels:?}");
|
||||
assert!(labels.iter().any(|l| l.contains("Enter Quick Mask")) && labels.iter().any(|l| l.contains("Exit Quick Mask")), "{labels:?}");
|
||||
s.undo();
|
||||
assert!(doc(&s).quick_mask.is_some());
|
||||
assert!(doc(&s).selection.is_none());
|
||||
|
||||
@@ -340,43 +340,38 @@ fn a_listing_during_an_autosave_sees_the_entry_exactly_once() {
|
||||
let dir = temp_dir("listing-during-autosave");
|
||||
let doc = Document::new("Busy", photocraft_doc::Size { width: 4, height: 4 }, ColorMode::Rgb, SampleType::U8);
|
||||
save_once(&dir, "busy", doc.clone());
|
||||
let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let writer = {
|
||||
let (dir, done) = (dir.clone(), done.clone());
|
||||
std::thread::spawn(move || {
|
||||
// Sets `done` however the thread ends, so a failing writer stops the listing loop
|
||||
// and `join` reports its panic instead of the test hanging.
|
||||
struct SetOnDrop(Arc<std::sync::atomic::AtomicBool>);
|
||||
impl Drop for SetOnDrop {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
let _done = SetOnDrop(done);
|
||||
let saver = Autosaver::new(&dir, "busy");
|
||||
for revision in 2..=200 {
|
||||
saver.request(Arc::new(doc.clone()), revision, None, SaveOptions::default());
|
||||
// Wait for this write, so every revision replaces the sidecar once.
|
||||
let completed = loop {
|
||||
let completed = saver.take_completed();
|
||||
if !completed.is_empty() {
|
||||
break completed;
|
||||
}
|
||||
std::thread::yield_now();
|
||||
};
|
||||
assert!(completed.iter().all(|(_, result)| result.is_ok()), "revision {revision}: {completed:?}");
|
||||
}
|
||||
saver.flush()
|
||||
})
|
||||
};
|
||||
let mut listings = 0u32;
|
||||
while !done.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
let doc = Arc::new(doc);
|
||||
let saver = Autosaver::new(&dir, "busy");
|
||||
let listed_revision = || {
|
||||
let entries = list_recovery(&dir);
|
||||
let keys: Vec<&str> = entries.iter().map(|e| e.info.key.as_str()).collect();
|
||||
assert_eq!(keys, ["busy"], "listing {listings} during an autosave: {entries:?}");
|
||||
listings += 1;
|
||||
let [entry] = entries.as_slice() else { panic!("expected one entry during autosave: {entries:?}") };
|
||||
assert_eq!(entry.info.key, "busy");
|
||||
entry.info.revision
|
||||
};
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5 * 60);
|
||||
// Each replacement is another opportunity to observe a transient missing sidecar.
|
||||
for revision in 2..=200 {
|
||||
saver.request_checked(doc.clone(), revision, None, SaveOptions::default()).unwrap();
|
||||
loop {
|
||||
let completed = saver.take_completed();
|
||||
// List on this thread while the autosave worker writes. The preceding sidecar or
|
||||
// its replacement supplies the revision. A sidecar-less fallback reports zero.
|
||||
let listed = listed_revision();
|
||||
match completed.as_slice() {
|
||||
[] => {
|
||||
assert!((revision - 1..=revision).contains(&listed), "listed revision {listed} while writing {revision}");
|
||||
assert!(std::time::Instant::now() < deadline, "autosave did not complete revision {revision}");
|
||||
}
|
||||
[(written, result)] => {
|
||||
assert_eq!(*written, revision);
|
||||
result.as_ref().unwrap();
|
||||
assert_eq!(listed, revision, "the completed replacement is visible");
|
||||
break;
|
||||
}
|
||||
_ => panic!("expected one completed write: {completed:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(writer.join().unwrap().is_some_and(|r| r.is_ok()));
|
||||
assert!(listings > 0);
|
||||
assert!(saver.flush().is_some_and(|r| r.is_ok()));
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
+18
-14
@@ -479,6 +479,20 @@ fn rgb_to_hsl(c: vec3<f32>) -> vec3<f32> {
|
||||
}
|
||||
return vec3(h / 6.0, s, l);
|
||||
}
|
||||
|
||||
// compose::adjust::hue_saturation_in at 8/16 bits.
|
||||
fn scale_saturation(v: f32, s: f32) -> f32 {
|
||||
if (s > 0.0) { return v / max(1.0 - s, 1.0 / 512.0); }
|
||||
return v * (1.0 + s);
|
||||
}
|
||||
|
||||
// compose::adjust::color::hdr_saturation_factor, in whole numbers.
|
||||
fn hdr_saturation_factor(s: f32) -> f32 {
|
||||
if (s <= 0.0) { return 1.0 - floor(-s * 256.0 + 1e-4) / 256.0; }
|
||||
let steps = min(u32(floor(s * 254.0 + 1e-4)), 254u);
|
||||
return f32(min(65280u / (255u - steps), 32767u)) / 256.0;
|
||||
}
|
||||
|
||||
fn hue_ch(p: f32, q: f32, t0: f32) -> f32 {
|
||||
let t = rem_euclid(t0, 1.0);
|
||||
if (t < 1.0 / 6.0) { return p + (q - p) * 6.0 * t; }
|
||||
@@ -677,7 +691,8 @@ fn adjust(c: vec3<f32>) -> vec3<f32> {
|
||||
ds = lut(1, hsl.x);
|
||||
dl = lut(2, hsl.x);
|
||||
}
|
||||
let sat = clamp(p0.y + ds, -1.0, 1.0);
|
||||
let sat = clamp(p0.y, -1.0, 1.0);
|
||||
let rs = clamp(ds, -1.0, 1.0);
|
||||
let light = clamp(p0.z, -1.0, 1.0);
|
||||
if (p0.w > 0.5) {
|
||||
// compose::adjust::hue_saturation: Colorize at the lightened / darkened lightness.
|
||||
@@ -694,24 +709,13 @@ fn adjust(c: vec3<f32>) -> vec3<f32> {
|
||||
if (hdr) {
|
||||
// 32-bit: the chroma scaled around the lightness, unclipped, by Photoshop's factor
|
||||
// in whole numbers (compose::adjust::hue_saturation_in, hdr_saturation_factor).
|
||||
var k: f32;
|
||||
if (sat <= 0.0) {
|
||||
k = 1.0 - floor(-sat * 256.0 + 1e-4) / 256.0;
|
||||
} else {
|
||||
let steps = min(u32(floor(sat * 254.0 + 1e-4)), 254u);
|
||||
k = f32(min(65280u / (255u - steps), 32767u)) / 256.0;
|
||||
}
|
||||
let k = hdr_saturation_factor(sat) * hdr_saturation_factor(rs);
|
||||
let d = (max(max(lc.r, lc.g), lc.b) - min(min(lc.r, lc.g), lc.b)) * k;
|
||||
let lo = lh.z - d / 2.0;
|
||||
let hi = lh.z + d / 2.0;
|
||||
rgb = vec3(hue_ch(lo, hi, hh + 1.0 / 3.0), hue_ch(lo, hi, hh), hue_ch(lo, hi, hh - 1.0 / 3.0));
|
||||
} else {
|
||||
// Raising saturation divides by 1 - s; lowering it multiplies by 1 + s.
|
||||
if (sat > 0.0) {
|
||||
ss = clamp(lh.y / max(1.0 - sat, 1.0 / 512.0), 0.0, 1.0);
|
||||
} else {
|
||||
ss = clamp(lh.y * (1.0 + sat), 0.0, 1.0);
|
||||
}
|
||||
ss = clamp(scale_saturation(scale_saturation(lh.y, sat), rs), 0.0, 1.0);
|
||||
rgb = hsl_to_rgb(hh, ss, lh.z);
|
||||
}
|
||||
// compose::adjust::range_lightness: towards the brightest channel when raised, the darkest when lowered.
|
||||
|
||||
@@ -858,6 +858,12 @@ fn adjustment_layers() {
|
||||
let hs = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: -10.0, colorize: false, ranges: HueRange::defaults() };
|
||||
d.layers.push(Layer::new("hs2", LayerContent::Adjustment(hs)));
|
||||
check(&mut g, &d, &format!("hue/saturation {depth:?}"));
|
||||
// A range's saturation multiplies the master's factor (#14741).
|
||||
let hs = Adjustment::HueSaturation { hue: 0.0, saturation: 60.0, lightness: 0.0, colorize: false, ranges: hue_ranges() };
|
||||
d.layers.push(Layer::new("hs3", LayerContent::Adjustment(hs)));
|
||||
check(&mut g, &d, &format!("hue/saturation ranges {depth:?}"));
|
||||
// Off again: stacked under Threshold, it puts a 16-bit sample on the level's edge.
|
||||
d.layers.pop();
|
||||
// Threshold: whole 16-bit samples against the level in 16 bits, or the float luminosity.
|
||||
d.layers.push(Layer::new("th", LayerContent::Adjustment(Adjustment::Threshold { level: 0.5 })));
|
||||
check(&mut g, &d, &format!("threshold {depth:?}"));
|
||||
|
||||
@@ -366,19 +366,35 @@ const SMOOTH_OPACITY_GAMMA: f32 = 2.2;
|
||||
/// in the Gradient tool at 100 % Smoothness with 50 % midpoints, the only case that uses it.
|
||||
/// Constant opacity comes back as it is, clamped to 0..=1.
|
||||
pub fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> {
|
||||
bake_smooth_opacity_with(stops, midpoints, |o| o.powf(SMOOTH_OPACITY_GAMMA).cbrt(), |l| l.powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA))
|
||||
}
|
||||
|
||||
/// Smooth's opacity response for the Gradient tool on an 8- or 16-bit layer mask. The same
|
||||
/// Smooth easing with a lightness response of `L^1.75` fits the measured mask fade (#18670).
|
||||
pub fn bake_smooth_mask_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> {
|
||||
const MASK_POWER: f32 = 1.75;
|
||||
bake_smooth_opacity_with(stops, midpoints, |o| o.powf(1.0 / MASK_POWER), |l| l.powf(MASK_POWER))
|
||||
}
|
||||
|
||||
fn bake_smooth_opacity_with(
|
||||
stops: Vec<(f32, f32)>,
|
||||
midpoints: &[f32],
|
||||
to_lightness: impl Fn(f32) -> f32,
|
||||
from_lightness: impl Fn(f32) -> f32,
|
||||
) -> Vec<(f32, f32)> {
|
||||
let clamp = |o: f32| if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 };
|
||||
if stops.len() < 2 || stops.windows(2).all(|w| w[0].1 == w[1].1) {
|
||||
return stops.into_iter().map(|(t, o)| (t, clamp(o))).collect();
|
||||
}
|
||||
let mut s = stops;
|
||||
s.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [clamp(*o).powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3])).collect();
|
||||
let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [to_lightness(clamp(*o)); 3])).collect();
|
||||
const N: usize = 96;
|
||||
let mut baked: Vec<(f32, f32)> = (0..=N)
|
||||
.map(|k| {
|
||||
let t = k as f32 / N as f32;
|
||||
let l = eval(&pts, midpoints, 0.0, t, Method::Smooth)[0];
|
||||
(t, if l.is_finite() { l.clamp(0.0, 1.0).powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA) } else { 1.0 })
|
||||
(t, if l.is_finite() { from_lightness(l.clamp(0.0, 1.0)) } else { 1.0 })
|
||||
})
|
||||
.collect();
|
||||
baked.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);
|
||||
|
||||
@@ -69,7 +69,14 @@ sys-locale = "=0.3.2"
|
||||
# symbol (`i18n::decimal_separator`, a registry read): the safe binding the desktop app already
|
||||
# uses, pinned to the same version.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi"] }
|
||||
winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi", "user"] }
|
||||
|
||||
# Safe physical display dimensions for View > Actual Size. Both are already in the lockfile.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
core-graphics = "=0.23.2"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
x11rb = { version = "=0.13.2", features = ["randr"] }
|
||||
|
||||
[dev-dependencies]
|
||||
photocraft-io = { workspace = true, features = ["testgen"] }
|
||||
|
||||
@@ -93,6 +93,8 @@ impl PhotocraftApp {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
control: None,
|
||||
live_adjust: None,
|
||||
#[cfg(test)]
|
||||
preview_test_area_multiplier: 1,
|
||||
frame: 0,
|
||||
notices_live: notices::Live::default(),
|
||||
low_memory: crate::memory_warning::Watch::default(),
|
||||
|
||||
@@ -831,8 +831,11 @@ impl PrefSections {
|
||||
.filter_map(|key| Some((key.clone(), serde_json::to_value(t.tables.get(key)?).ok()?)))
|
||||
.filter(|(key, value)| session.prefs().sections.get(key) != Some(value))
|
||||
.collect();
|
||||
// Remembered, not a settings edit: no view reads the sections back from the preferences (the components
|
||||
// read them here), so the panels keep their versions and the engine applies nothing. A dialog that
|
||||
// remembers its place writes on every frame of a drag.
|
||||
if !changed.is_empty() {
|
||||
session.edit_prefs(|p| p.sections.extend(changed));
|
||||
session.prefs.remember(|p| p.sections.extend(changed));
|
||||
}
|
||||
for key in written {
|
||||
let rev = session.section_rev(&key);
|
||||
@@ -986,6 +989,19 @@ mod tests {
|
||||
assert_eq!(store.read("one"), None);
|
||||
}
|
||||
|
||||
/// A component's section write is saved, but is no settings edit: the panels' versions hold the settings revision,
|
||||
/// so an edit would rebuild every panel on each frame a dialog that remembers its place is dragged.
|
||||
#[test]
|
||||
fn a_section_write_is_saved_without_a_settings_edit() {
|
||||
let store = PrefSections::default();
|
||||
let mut session = Session::new();
|
||||
let (saved, settings) = (session.prefs.rev(), session.prefs.settings_rev());
|
||||
store.write("one", table(1));
|
||||
store.sync(&mut session);
|
||||
assert_ne!(session.prefs.rev(), saved, "the write reaches the saved preferences");
|
||||
assert_eq!(session.prefs.settings_rev(), settings, "the panels keep their versions");
|
||||
}
|
||||
|
||||
/// Every theme PhotoCraft has a palette for names a framework built-in.
|
||||
#[test]
|
||||
fn every_palette_theme_is_a_builtin() {
|
||||
|
||||
@@ -276,7 +276,7 @@ pub(crate) fn choose(app: &mut PhotocraftApp, item: Item) {
|
||||
crate::brush_picker::open(app, at);
|
||||
}
|
||||
}
|
||||
Item::Eraser(m) => app.ui.tool_options.eraser_mode = m.into(),
|
||||
Item::Eraser(m) => crate::canvas::strokes::set_eraser_mode(app, m),
|
||||
Item::Range(r) => app.ui.tool_options.tone_range = r.into(),
|
||||
Item::Sponge(m) => app.ui.tool_options.sponge_mode = m.into(),
|
||||
// Replace is a tool option: it runs no command and adds no History step (#12101).
|
||||
|
||||
@@ -36,24 +36,23 @@ fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() {
|
||||
let Some(rs) = render_state() else { return };
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.set_wgpu(rs);
|
||||
// Half the 1024 × 768 canvas these views were first written for (see `check_blend_viewport`): `a` still runs off
|
||||
// the right edge and `b` still lies apart from it.
|
||||
app.run("file.new", json!({"width":512,"height":384,"background":"#336699"})).unwrap();
|
||||
// One view crosses the right edge; the other sits apart from it. The
|
||||
// intervening pixels still have to be refreshed when Pattern Preview opens.
|
||||
app.run("file.new", json!({"width":256,"height":192,"background":"#336699"})).unwrap();
|
||||
let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
app.run("edit.fill", json!({"color":"#cc8844"})).unwrap();
|
||||
let ctx = app.ctx().clone();
|
||||
let a = DRect::new(362, 100, 662, 250);
|
||||
let b = DRect::new(0, 100, 150, 250);
|
||||
let a = DRect::new(181, 50, 331, 125);
|
||||
let b = DRect::new(0, 50, 75, 125);
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, a, None));
|
||||
app.ui.view.pattern_preview = true;
|
||||
crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(BlendMode::Multiply));
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, a, None));
|
||||
assert_visible_pixels(&mut app, b);
|
||||
let bounds = app.session.active().unwrap().doc.bounds();
|
||||
assert_visible_pixels(&mut app, bounds);
|
||||
assert_visible_pixels(&mut app, &[bounds]);
|
||||
crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None);
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, a, None));
|
||||
assert_visible_pixels(&mut app, bounds);
|
||||
assert_visible_pixels(&mut app, &[bounds]);
|
||||
|
||||
app.ui.view.pattern_preview = false;
|
||||
for mode in [BlendMode::Multiply, BlendMode::Screen] {
|
||||
@@ -64,16 +63,16 @@ fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() {
|
||||
app.perf.last_refresh_px = 0;
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
|
||||
assert_eq!(app.perf.last_refresh_px, 0, "unchanged views must retain coverage together");
|
||||
assert_visible_pixels(&mut app, visible.intersect(&bounds));
|
||||
assert_visible_pixels(&mut app, &[visible.intersect(&bounds)]);
|
||||
}
|
||||
}
|
||||
// Enabling periodic display during an existing hover must catch up the unseen gap too.
|
||||
app.ui.view.pattern_preview = true;
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, a, None));
|
||||
assert_visible_pixels(&mut app, bounds);
|
||||
assert_visible_pixels(&mut app, &[bounds]);
|
||||
crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None);
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, a, None));
|
||||
assert_visible_pixels(&mut app, bounds);
|
||||
assert_visible_pixels(&mut app, &[bounds]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -96,12 +95,12 @@ fn blend_hover_during_background_redraw_restores_committed_pixels() {
|
||||
let panned = DRect::new(2048, 1024, 2304, 1280);
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, panned, None));
|
||||
settle_redraw(&mut app);
|
||||
assert_visible_pixels(&mut app, panned);
|
||||
assert_visible_pixels(&mut app, &[panned]);
|
||||
crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None);
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, panned, None));
|
||||
settle_redraw(&mut app);
|
||||
let bounds = app.session.active().unwrap().doc.bounds();
|
||||
assert_visible_pixels(&mut app, bounds);
|
||||
assert_visible_pixels(&mut app, &[bounds]);
|
||||
}
|
||||
|
||||
fn settle_redraw(app: &mut PhotocraftApp) {
|
||||
@@ -115,19 +114,33 @@ fn settle_redraw(app: &mut PhotocraftApp) {
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_visible_pixels(app: &mut PhotocraftApp, visible: DRect) {
|
||||
fn assert_visible_pixels(app: &mut PhotocraftApp, regions: &[DRect]) {
|
||||
let (doc, _) = display_doc(app, 0);
|
||||
let gpu = app.gpu.clone().unwrap();
|
||||
let reference = doc.id.0 ^ (1u64 << 60);
|
||||
let (display, _) = canvas_display(app, &doc, None);
|
||||
gpu.upload_composite(reference, &doc, display.as_deref());
|
||||
let (_, size, shown) = gpu.read_texels(doc.id.0).unwrap();
|
||||
let (_, _, want) = gpu.read_texels(reference).unwrap();
|
||||
for y in visible.y0..visible.y1 {
|
||||
for x in visible.x0..visible.x1 {
|
||||
let index = y as usize * size[0] as usize + x as usize;
|
||||
for channel in 0..4 {
|
||||
assert!((shown[index][channel] - want[index][channel]).abs() <= 2.0 / 255.0, "preview differs at ({x},{y}) channel{channel}");
|
||||
let format = eframe::wgpu::TextureFormat::Rgba8Unorm;
|
||||
// Prepare the CPU reference while the GPU can still be drawing. Each requested
|
||||
// region is compared to the same captured canvas texture.
|
||||
let references: Vec<_> = regions
|
||||
.iter()
|
||||
.map(|®ion| {
|
||||
assert!(doc.bounds().contains_rect(®ion));
|
||||
let reference = photocraft_compose::render(&doc, region);
|
||||
(region, gpu_canvas::display_texels(format, display.as_deref(), &reference))
|
||||
})
|
||||
.collect();
|
||||
let (actual_format, size, shown) = gpu.read_texels(doc.id.0).expect("read visible canvas");
|
||||
assert_eq!(actual_format, format);
|
||||
assert_eq!(size, [doc.size.width, doc.size.height]);
|
||||
for (region, expected) in references {
|
||||
let expected = expected.as_chunks::<4>().0;
|
||||
for y in region.y0..region.y1 {
|
||||
for x in region.x0..region.x1 {
|
||||
let actual = shown[y as usize * size[0] as usize + x as usize];
|
||||
let index = ((y - region.y0) as usize) * region.width() as usize + (x - region.x0) as usize;
|
||||
for (channel, (actual, expected)) in actual.into_iter().zip(expected[index]).enumerate() {
|
||||
assert!((actual - f32::from(expected) / 255.0).abs() <= 2.0 / 255.0, "preview differs at ({x},{y}) channel {channel}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -138,11 +151,9 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) {
|
||||
let Some(rs) = render_state() else { return };
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.set_wgpu(rs);
|
||||
// Every view and count below is half of the 1024 × 768 fixture first used: the clip to the view
|
||||
// (`blend_preview::clip_damage`) and the catch-up (`blend_preview::uncovered`) are rectangle arithmetic with no
|
||||
// size threshold, and the canvas stays far below the background redraw's (that case is
|
||||
// `blend_hover_during_background_redraw_restores_committed_pixels`). The whole-canvas pixel checks cost a quarter.
|
||||
app.run("file.new", json!({"width":512,"height":384,"background":"#336699"})).unwrap();
|
||||
// View clipping and catch-up use rectangles at any size. The visible,
|
||||
// expanded and disjoint views below still require different refreshes.
|
||||
app.run("file.new", json!({"width":256,"height":192,"background":"#336699"})).unwrap();
|
||||
let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
app.run("edit.fill", json!({"color":"#cc8844"})).unwrap();
|
||||
if cpu_fallback {
|
||||
@@ -156,7 +167,7 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) {
|
||||
layers.push(photocraft_doc::LayerId(other));
|
||||
}
|
||||
let ctx = app.ctx().clone();
|
||||
let visible = DRect::new(128, 128, 256, 256);
|
||||
let visible = DRect::new(64, 64, 128, 128);
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
|
||||
assert!(app.redraws.is_empty(), "small fixture must finish synchronously");
|
||||
if cpu_fallback {
|
||||
@@ -167,25 +178,24 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) {
|
||||
let original = gpu.read_texels(id.0).unwrap();
|
||||
crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Multiply));
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
|
||||
println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 128 * 128, app.perf.gpu_info);
|
||||
assert_eq!(app.perf.last_refresh_px, 128 * 128, "hover must not recomposite offscreen pixels of a full-canvas layer");
|
||||
assert_visible_pixels(&mut app, visible);
|
||||
println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 64 * 64, app.perf.gpu_info);
|
||||
assert_eq!(app.perf.last_refresh_px, 64 * 64, "hover must not recomposite offscreen pixels of a full-canvas layer");
|
||||
assert_visible_pixels(&mut app, &[visible]);
|
||||
app.perf.last_refresh_px = 0;
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
|
||||
assert_eq!(app.perf.last_refresh_px, 0, "unchanged view and mode must reuse the texture");
|
||||
let zoomed_out = DRect::new(64, 64, 320, 320);
|
||||
let zoomed_out = DRect::new(32, 32, 160, 160);
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, zoomed_out, None));
|
||||
assert_eq!(app.perf.last_refresh_px, 256 * 256, "zooming out catches up the larger visible area");
|
||||
let panned = DRect::new(320, 128, 448, 256);
|
||||
assert_eq!(app.perf.last_refresh_px, 128 * 128, "zooming out catches up the larger visible area");
|
||||
let panned = DRect::new(160, 64, 224, 128);
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, panned, None));
|
||||
assert_eq!(app.perf.last_refresh_px, 128 * 128, "newly exposed pixels must catch up without a mode change");
|
||||
assert_eq!(app.perf.last_refresh_px, 64 * 64, "newly exposed pixels must catch up without a mode change");
|
||||
crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Screen));
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, panned, None));
|
||||
assert_eq!(app.perf.last_refresh_px, 128 * 128);
|
||||
assert_eq!(app.perf.last_refresh_px, 64 * 64);
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
|
||||
assert_eq!(app.perf.last_refresh_px, 128 * 128, "returning view must show the current mode");
|
||||
assert_visible_pixels(&mut app, visible);
|
||||
assert_visible_pixels(&mut app, panned);
|
||||
assert_eq!(app.perf.last_refresh_px, 64 * 64, "returning view must show the current mode");
|
||||
assert_visible_pixels(&mut app, &[visible, panned]);
|
||||
crate::blend_preview::hover(&mut app, &layers, None);
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
|
||||
assert_eq!(gpu.read_texels(id.0).unwrap(), original, "cancel must restore the whole texture, including previously previewed offscreen pixels");
|
||||
@@ -194,11 +204,11 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) {
|
||||
app.run("layer.setProps", json!({"layer":layer,"blend":"Multiply"})).unwrap();
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
|
||||
let bounds = app.session.active().unwrap().doc.bounds();
|
||||
assert_visible_pixels(&mut app, bounds);
|
||||
app.run("file.new", json!({"width":512,"height":384,"background":"white"})).unwrap();
|
||||
assert_visible_pixels(&mut app, &[bounds]);
|
||||
app.run("file.new", json!({"width":256,"height":192,"background":"white"})).unwrap();
|
||||
assert!(ensure_gpu(&mut app, &ctx, 1, visible, None));
|
||||
app.session.set_active(0);
|
||||
app.sync_views();
|
||||
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
|
||||
assert_visible_pixels(&mut app, bounds);
|
||||
assert_visible_pixels(&mut app, &[bounds]);
|
||||
}
|
||||
|
||||
@@ -28,6 +28,10 @@ use photocraft_geom::Rect as DRect;
|
||||
#[path = "layer_edges_drawing_tests.rs"]
|
||||
mod layer_edges_drawing_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "hand_scroll_all_windows_tests.rs"]
|
||||
mod hand_scroll_all_windows_tests;
|
||||
|
||||
impl View {
|
||||
/// This view as the framework's canvas view of `rect` at `ppp` device pixels per point, mirrored by View › Flip
|
||||
/// Horizontal and stretched by View › Pixel Aspect Ratio Correction.
|
||||
@@ -146,7 +150,7 @@ pub(crate) fn view_follows_pointer(app: &PhotocraftApp, idx: usize) -> bool {
|
||||
crate::crop_ui::moves_view(app) && app.session.active_index() == Some(idx)
|
||||
}
|
||||
|
||||
/// The user's navigation choices from Preferences (General, Tools, Enhanced Controls).
|
||||
/// The user's navigation preferences and Hand tool option.
|
||||
pub(crate) fn navigation(app: &PhotocraftApp) -> NavigationOptions {
|
||||
let p = app.session.prefs();
|
||||
let mut options = NavigationOptions::default();
|
||||
@@ -154,6 +158,7 @@ pub(crate) fn navigation(app: &PhotocraftApp) -> NavigationOptions {
|
||||
options.animated_zoom = p.general.animated_zoom;
|
||||
options.zoom_clicked_point_to_center = p.tools.zoom_clicked_point_to_center;
|
||||
options.flick_panning = p.tools.enable_flick_panning;
|
||||
options.scroll_all_windows = app.ui.tool_options.hand_scroll_all;
|
||||
options.overscroll = p.tools.overscroll;
|
||||
options.pinch_zooms = p.enhanced_controls.zoom_with_trackpad_pinch;
|
||||
options.trackpad_rotate = p.enhanced_controls.rotate_view_with_trackpad;
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//! #18630: Changing Eraser mode forgets the previous Shift-click endpoint.
|
||||
|
||||
use egui::accesskit::Role;
|
||||
use egui::{Modifiers, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::app::framework::BuildApp as _;
|
||||
use crate::brush_mode_menu::{self, Item};
|
||||
use crate::canvas::testing;
|
||||
use crate::state::Tool;
|
||||
|
||||
// Click inside the named pixels, away from the even-sized Block tip's nearest-corner tie.
|
||||
const START: [f64; 2] = [100.75, 300.75];
|
||||
const END: [f64; 2] = [300.75, 300.75];
|
||||
|
||||
fn document(mode: &str) -> Box<PhotocraftApp> {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.background_jobs = false;
|
||||
app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
app.run("edit.fill", json!({"color": "#dc1e1e"})).unwrap();
|
||||
app.run("tools.setBrush", json!({"brush": {"size": 16, "hardness": 1.0}})).unwrap();
|
||||
app.session.tools.brush.smoothing.amount = 0.0;
|
||||
app.ui.tool = Tool::Eraser;
|
||||
app.ui.tool_options.eraser_mode = mode.into();
|
||||
app.sync_views();
|
||||
testing::shown(&mut app);
|
||||
let scale = app.canvas_ppp();
|
||||
let view = &mut app.ui.views[0];
|
||||
view.zoom = scale;
|
||||
view.clear_pending();
|
||||
testing::shown(&mut app);
|
||||
assert_eq!(app.point_zoom(), 1.0, "the Block tests use one canvas point per image pixel");
|
||||
app
|
||||
}
|
||||
|
||||
fn alpha(app: &PhotocraftApp, x: i32, y: i32) -> f32 {
|
||||
let st = app.session.active().unwrap();
|
||||
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)[3]
|
||||
}
|
||||
|
||||
fn block_pixels(app: &PhotocraftApp, xs: RangeInclusive<i32>) -> Vec<f32> {
|
||||
(280..=320).flat_map(|y| xs.clone().map(move |x| alpha(app, x, y))).collect()
|
||||
}
|
||||
|
||||
fn mode_dropdown(mode: &str) -> Harness<'static, Box<PhotocraftApp>> {
|
||||
let mut h =
|
||||
Harness::builder().with_size(vec2(1800.0, 300.0)).with_step_dt(1.0 / 60.0).build_app(|ui, app| crate::panels::options_bar(app, ui), document(mode));
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
fn choose_mode(h: &mut Harness<'_, Box<PhotocraftApp>>, label: &str) {
|
||||
h.get_by_role_and_label(Role::ComboBox, "Mode").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label(label).click();
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_eraser_mode_in_the_dropdown_starts_a_separate_mark() {
|
||||
let mut control = document("block");
|
||||
testing::click(&mut control, END, Modifiers::NONE);
|
||||
let block = block_pixels(&control, 280..=320);
|
||||
let erased_x: Vec<_> = (280..=320).filter(|&x| alpha(&control, x, 300) == 0.0).collect();
|
||||
let erased_y: Vec<_> = (280..=320).filter(|&y| alpha(&control, 300, y) == 0.0).collect();
|
||||
assert_eq!((erased_x.len(), erased_y.len()), (16, 16));
|
||||
assert_eq!(erased_x[15] - erased_x[0], 15);
|
||||
assert_eq!(erased_y[15] - erased_y[0], 15);
|
||||
for y in 280..=320 {
|
||||
for x in 280..=320 {
|
||||
let want = if erased_x.contains(&x) && erased_y.contains(&y) { 0.0 } else { 1.0 };
|
||||
assert_eq!(alpha(&control, x, y), want, "the ordinary Block dab at ({x}, {y})");
|
||||
}
|
||||
}
|
||||
|
||||
let modes = [("brush", "Brush"), ("pencil", "Pencil"), ("block", "Block")];
|
||||
for (from, _) in modes {
|
||||
for (to, label) in modes.into_iter().filter(|(to, _)| *to != from) {
|
||||
let mut h = mode_dropdown(from);
|
||||
testing::click(h.state_mut(), START, Modifiers::NONE);
|
||||
assert!(alpha(h.state(), 100, 300) < 0.1, "{from} marks the first click");
|
||||
let history = h.state().session.active().unwrap().history.past_len();
|
||||
choose_mode(&mut h, label);
|
||||
assert_eq!(h.state().ui.tool_options.eraser_mode, to);
|
||||
assert_eq!(h.state().session.active().unwrap().history.past_len(), history);
|
||||
|
||||
testing::click(h.state_mut(), END, Modifiers::SHIFT);
|
||||
assert!(alpha(h.state(), 300, 300) < 0.1, "{from} to {to} marks the second click");
|
||||
assert!((110..=290).all(|x| alpha(h.state(), x, 300) == 1.0), "{from} to {to} leaves the gap opaque");
|
||||
if to == "block" {
|
||||
assert!(block_pixels(h.state(), 280..=320) == block, "{from} to {to} matches the ordinary Block dab exactly");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_the_current_eraser_mode_or_leaving_it_alone_keeps_the_line() {
|
||||
let mut ordinary = None;
|
||||
for pick_current_mode in [false, true] {
|
||||
let mut h = mode_dropdown("block");
|
||||
testing::click(h.state_mut(), START, Modifiers::NONE);
|
||||
if pick_current_mode {
|
||||
choose_mode(&mut h, "Block");
|
||||
}
|
||||
testing::click(h.state_mut(), END, Modifiers::SHIFT);
|
||||
let erased_rows: Vec<_> = (280..=320).filter(|&y| alpha(h.state(), 200, y) == 0.0).collect();
|
||||
assert_eq!(erased_rows.len(), 16);
|
||||
assert_eq!(erased_rows[15] - erased_rows[0], 15);
|
||||
assert!(erased_rows.iter().all(|&y| (100..=300).all(|x| alpha(h.state(), x, y) == 0.0)), "the same mode keeps the whole line");
|
||||
let band = block_pixels(h.state(), 80..=320);
|
||||
if let Some(ordinary) = &ordinary {
|
||||
assert!(&band == ordinary, "reselecting Block preserves every pixel of the ordinary line");
|
||||
} else {
|
||||
ordinary = Some(band);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choosing_a_different_eraser_mode_from_the_canvas_menu_also_forgets_the_endpoint() {
|
||||
let mut app = document("brush");
|
||||
testing::click(&mut app, START, Modifiers::NONE);
|
||||
testing::secondary_click(&mut app, START, Modifiers::SHIFT);
|
||||
assert!(app.ui.canvas_tool_menu.is_some(), "Shift-right-click opens the canvas menu");
|
||||
brush_mode_menu::choose(&mut app, Item::Eraser("block"));
|
||||
assert_eq!(app.ui.tool_options.eraser_mode, "block");
|
||||
testing::click(&mut app, END, Modifiers::SHIFT);
|
||||
assert_eq!(alpha(&app, 300, 300), 0.0);
|
||||
assert_eq!(alpha(&app, 200, 300), 1.0);
|
||||
}
|
||||
@@ -30,8 +30,8 @@ mod tests;
|
||||
/// the very stall this avoids.
|
||||
pub(crate) fn filter_preview_factor(app: &PhotocraftApp, doc: &Document, cmd: &str, params: &serde_json::Value) -> u32 {
|
||||
// A smart filter edit re-renders the whole stack: every stage constrains the factor.
|
||||
let k = crate::filter_dialog::smart_preview_factor(doc, cmd, params, crate::proxy::preview_factor(doc, crate::proxy::reduced_previews(app)));
|
||||
if cfg!(target_arch = "wasm32") { k } else { crate::proxy::view_factor(k, app.current_zoom(), doc.size.area()) }
|
||||
let k = crate::filter_dialog::smart_preview_factor(doc, cmd, params, crate::proxy::app_factor(app, doc));
|
||||
if cfg!(target_arch = "wasm32") { k } else { crate::proxy::view_factor(k, app.current_zoom(), crate::proxy::planning_area(app, doc)) }
|
||||
}
|
||||
|
||||
/// The open adjustment dialog (a plain one or a Smart Filter edit) while its preview shows: its dialog id and what OK
|
||||
@@ -364,11 +364,11 @@ pub(super) fn ensure_proxy_preview(app: &mut PhotocraftApp, idx: usize, zoom: f3
|
||||
(st.doc.id, st.revision, st.doc.clone())
|
||||
};
|
||||
// Low-resolution previews off: k is 1 and the canvas shows `display_doc` (full size).
|
||||
let mut k = crate::proxy::preview_factor(&doc, crate::proxy::reduced_previews(app));
|
||||
let mut k = crate::proxy::app_factor(app, &doc);
|
||||
// Zoomed in, a proxy coarser than the screen showed the drag in k-pixel blocks (#5764): when
|
||||
// the wgpu compositor draws the full-size document, use a proxy only as coarse as the screen
|
||||
// (none at 50 % and closer). Otherwise the full size would be a CPU composite per change.
|
||||
let fine = crate::proxy::view_factor(k, zoom, doc.size.area());
|
||||
let fine = crate::proxy::view_factor(k, zoom, crate::proxy::planning_area(app, &doc));
|
||||
if fine < k && app.gpu.as_ref().is_some_and(|g| g.supports(&doc)) {
|
||||
k = fine;
|
||||
}
|
||||
|
||||
@@ -14,37 +14,48 @@ fn read_mips(gpu: &GpuCanvas, key: u64) -> Vec<Vec<[f32; 4]>> {
|
||||
let tile = &doc.tiles[0];
|
||||
let (device, queue) = (&gpu.rs.device, &gpu.rs.queue);
|
||||
let bpp = texel_bytes(doc.format) as usize;
|
||||
(0..tile.levels.len())
|
||||
// Each level starts after a whole number of padded rows, so each copy offset has
|
||||
// room for its own texels and meets the copy alignment for both canvas formats.
|
||||
let mut size = 0;
|
||||
let levels: Vec<_> = (0..tile.levels.len())
|
||||
.map(|level| {
|
||||
let (w, h) = ((doc.size[0] >> level).max(1), (doc.size[1] >> level).max(1));
|
||||
let row = (w as usize * bpp).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize);
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("mip_test_readback"),
|
||||
size: (row * h as usize) as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo { texture: &tile.texture, mip_level: level as u32, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row as u32), rows_per_image: Some(h) },
|
||||
},
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
queue.submit([encoder.finish()]);
|
||||
buffer.slice(..).map_async(wgpu::MapMode::Read, |result| result.unwrap());
|
||||
assert!(gpu.health.wait(device, None));
|
||||
let data = buffer.slice(..).get_mapped_range().unwrap();
|
||||
let mut pixels = Vec::new();
|
||||
for y in 0..h as usize {
|
||||
for x in 0..w as usize {
|
||||
let offset = y * row + x * bpp;
|
||||
pixels.push(texel_to_f32(doc.format, &data[offset..offset + bpp]));
|
||||
}
|
||||
}
|
||||
pixels
|
||||
let offset = size;
|
||||
size += row * h as usize;
|
||||
(w, h, row, offset)
|
||||
})
|
||||
.collect();
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("mip_test_readback"),
|
||||
size: size as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
for (level, &(w, h, row, offset)) in levels.iter().enumerate() {
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo { texture: &tile.texture, mip_level: level as u32, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout { offset: offset as u64, bytes_per_row: Some(row as u32), rows_per_image: Some(h) },
|
||||
},
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
}
|
||||
let submission = queue.submit([encoder.finish()]);
|
||||
let slice = buffer.slice(..);
|
||||
slice.map_async(wgpu::MapMode::Read, |result| result.expect("map mip readback"));
|
||||
assert!(gpu.health.wait_idle(device, Some(submission)));
|
||||
let data = slice.get_mapped_range().expect("read mip snapshot");
|
||||
levels
|
||||
.into_iter()
|
||||
.map(|(w, h, row, offset)| {
|
||||
data[offset..offset + row * h as usize]
|
||||
.chunks_exact(row)
|
||||
.flat_map(|line| line[..w as usize * bpp].chunks_exact(bpp))
|
||||
.map(|texel| texel_to_f32(doc.format, texel))
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -124,40 +135,44 @@ fn canvas_textures_the_gpu_refuses_leave_it_working(gpu: &GpuCanvas) {
|
||||
}
|
||||
|
||||
fn check_mips(gpu: &GpuCanvas) {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
// 767 × 431 is a single tile (`DEFAULT_TILE`) with odd sides down the chain (767, 383, 191, 95 and 431,
|
||||
// 215, 107, 53), and its levels 1 and 2 are over `WHOLE_MIP_SIDE` (128), so the patch below redraws two
|
||||
// levels by their damage (`mip_damage`) before the chain is redrawn whole: the paths 1791 × 1083 took, at
|
||||
// a sixth of the pixels. The larger driver case stays in `partial_updates_match_a_full_rebuild_at_every_mip_level`.
|
||||
for (w, h) in [(767, 431), (513, 1), (1, 513)] {
|
||||
let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.25, 0.5, 0.75, 1.0]);
|
||||
// Reusing the key also covers replacing textures after a size or depth change.
|
||||
gpu.upload_buffer_full(1, &full, depth);
|
||||
for (level, pixels) in read_mips(gpu, 1).iter().enumerate() {
|
||||
for pixel in pixels {
|
||||
assert!((pixel[3] - 1.0).abs() < 0.001, "{depth:?} {w}x{h} mip {level}: {pixel:?}");
|
||||
for (actual, expected) in pixel.iter().zip([0.25, 0.5, 0.75, 1.0]) {
|
||||
assert!((actual - expected).abs() < 0.005, "{depth:?} {w}x{h} mip {level}: {pixel:?}");
|
||||
}
|
||||
use SampleType::{F32, U8, U16};
|
||||
// 519 is odd and still gives two damage-redrawn levels above WHOLE_MIP_SIDE
|
||||
// (259 and 129), followed by whole levels. Both stored formats use this path
|
||||
// on each backend, and the thin horizontal and vertical cases reach 1 × 1.
|
||||
// U16 and F32 use the same float texture and mip pipeline for these values.
|
||||
let depths_and_sizes: &[(SampleType, u32, u32)] = if photocraft_testkit::full_sweep() {
|
||||
&[(U8, 767, 431), (U8, 513, 1), (U8, 1, 513), (U16, 767, 431), (U16, 513, 1), (U16, 1, 513), (F32, 767, 431), (F32, 513, 1), (F32, 1, 513)]
|
||||
} else {
|
||||
&[(U8, 519, 267), (U16, 519, 267), (F32, 1, 513), (U8, 513, 1)]
|
||||
};
|
||||
for &(depth, w, h) in depths_and_sizes {
|
||||
let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.25, 0.5, 0.75, 1.0]);
|
||||
// Reusing the key also covers replacing textures after a size or depth change.
|
||||
gpu.upload_buffer_full(1, &full, depth);
|
||||
for (level, pixels) in read_mips(gpu, 1).iter().enumerate() {
|
||||
for pixel in pixels {
|
||||
assert!((pixel[3] - 1.0).abs() < 0.001, "{depth:?} {w}x{h} mip {level}: {pixel:?}");
|
||||
for (actual, expected) in pixel.iter().zip([0.25, 0.5, 0.75, 1.0]) {
|
||||
assert!((actual - expected).abs() < 0.005, "{depth:?} {w}x{h} mip {level}: {pixel:?}");
|
||||
}
|
||||
}
|
||||
let patch = Rect::from_xywh((w / 2) as i32, (h / 2) as i32, (w / 3).max(1), (h / 3).max(1));
|
||||
let changed = Buffer::filled(patch, [1.0, 0.0, 0.0, 1.0]);
|
||||
assert!(gpu.upload_buffer_rect(1, &changed));
|
||||
for y in patch.y0..patch.y1 {
|
||||
for x in patch.x0..patch.x1 {
|
||||
full.px[y as usize * w as usize + x as usize] = [1.0, 0.0, 0.0, 1.0];
|
||||
}
|
||||
}
|
||||
let patch = Rect::from_xywh((w / 2) as i32, (h / 2) as i32, (w / 3).max(1), (h / 3).max(1));
|
||||
let changed = Buffer::filled(patch, [1.0, 0.0, 0.0, 1.0]);
|
||||
assert!(gpu.upload_buffer_rect(1, &changed));
|
||||
for y in patch.y0..patch.y1 {
|
||||
for x in patch.x0..patch.x1 {
|
||||
full.px[y as usize * w as usize + x as usize] = [1.0, 0.0, 0.0, 1.0];
|
||||
}
|
||||
gpu.upload_buffer_full(2, &full, depth);
|
||||
let partial = read_mips(gpu, 1);
|
||||
let rebuilt = read_mips(gpu, 2);
|
||||
for (level, (actual, expected)) in partial.iter().zip(&rebuilt).enumerate() {
|
||||
for (a, b) in actual.iter().zip(expected) {
|
||||
assert!((a[3] - 1.0).abs() < 0.001, "partial {depth:?} mip {level}: {a:?}");
|
||||
for (a, b) in a.iter().zip(b) {
|
||||
assert!((a - b).abs() < 0.005, "partial/full mismatch {depth:?} {w}x{h} mip {level}: {a} != {b}");
|
||||
}
|
||||
}
|
||||
gpu.upload_buffer_full(2, &full, depth);
|
||||
let partial = read_mips(gpu, 1);
|
||||
let rebuilt = read_mips(gpu, 2);
|
||||
for (level, (actual, expected)) in partial.iter().zip(&rebuilt).enumerate() {
|
||||
for (a, b) in actual.iter().zip(expected) {
|
||||
assert!((a[3] - 1.0).abs() < 0.001, "partial {depth:?} mip {level}: {a:?}");
|
||||
for (a, b) in a.iter().zip(b) {
|
||||
assert!((a - b).abs() < 0.005, "partial/full mismatch {depth:?} {w}x{h} mip {level}: {a} != {b}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,7 +192,17 @@ fn partial_updates_match_a_full_rebuild_at_every_mip_level() {
|
||||
return;
|
||||
};
|
||||
let gpu = GpuCanvas::new(&rs);
|
||||
for (depth, w, h) in [(SampleType::U8, 255, 255), (SampleType::U8, 1024, 768), (SampleType::F32, 512, 512), (SampleType::F32, 1791, 1083)] {
|
||||
let adapter = rs.adapter.get_info();
|
||||
// Keep the allocation/layout sweep on physical Vulkan devices, where the
|
||||
// scissor regression was observed, and in the full sweep. Software adapters
|
||||
// still exercise both texture formats, whole and partial redraws, and both dabs.
|
||||
let sizes: &[(SampleType, u32, u32)] =
|
||||
if photocraft_testkit::full_sweep() || (adapter.backend == wgpu::Backend::Vulkan && adapter.device_type != wgpu::DeviceType::Cpu) {
|
||||
&[(SampleType::U8, 255, 255), (SampleType::U8, 1024, 768), (SampleType::F32, 512, 512), (SampleType::F32, 1791, 1083)]
|
||||
} else {
|
||||
&[(SampleType::U8, 255, 255), (SampleType::F32, 519, 267)]
|
||||
};
|
||||
for &(depth, w, h) in sizes {
|
||||
let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.0; 4]);
|
||||
for (i, px) in full.px.iter_mut().enumerate() {
|
||||
let (x, y) = (i as u32 % w, i as u32 / w);
|
||||
@@ -232,8 +257,9 @@ fn background_compositor_switch_preserves_pixels(gpu: &GpuCanvas) {
|
||||
}
|
||||
let second = gpu.refresh(key, &doc, Some(damage), None);
|
||||
assert_eq!(second.kind, "gpu-rect", "{:?}", second.fallback);
|
||||
let actual = read_mips(gpu, key).remove(0);
|
||||
let (_, _, actual) = gpu.read_texels(key).expect("read updated canvas");
|
||||
let expected = photocraft_compose::render(&doc, doc.bounds());
|
||||
assert_eq!(actual.len(), expected.px.len());
|
||||
for (got, want) in actual.iter().zip(expected.px.iter()) {
|
||||
for (g, w) in got.iter().zip(want.iter()) {
|
||||
assert!((g - w).abs() < 0.02, "{got:?} != {want:?}");
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
//! #12023 exercises the Hand options and gestures through the application window.
|
||||
|
||||
use craft::ui::canvas::ToolHost;
|
||||
use egui::accesskit::{Role, Toggled};
|
||||
use egui::{Event, Modifiers, PointerButton, Vec2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use serde_json::json;
|
||||
|
||||
use super::CanvasHost;
|
||||
use crate::state::{Tool, ToolOptions};
|
||||
use crate::{PhotocraftApp, Services};
|
||||
|
||||
type Window = Harness<'static, Box<PhotocraftApp>>;
|
||||
|
||||
/// Two shown 3000 × 2000 documents, at 100% and 50%, with the second one active.
|
||||
fn window() -> Window {
|
||||
let mut window = Harness::builder().with_size(vec2(1400.0, 900.0)).with_pixels_per_point(1.0).build_eframe(|cc| {
|
||||
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
|
||||
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Services::default());
|
||||
app.background_jobs = false;
|
||||
for name in ["oracle", "second"] {
|
||||
app.run("file.new", json!({"width": 3000, "height": 2000, "name": name})).unwrap();
|
||||
}
|
||||
app.ui.tool = Tool::Hand;
|
||||
app.session.prefs.edit(|prefs| {
|
||||
prefs.tools.enable_flick_panning = false;
|
||||
prefs.general.animated_zoom = false;
|
||||
});
|
||||
app
|
||||
});
|
||||
window.run_steps(6);
|
||||
let ctx = window.ctx.clone();
|
||||
crate::menus::invoke(window.state_mut(), &ctx, "window.arrange.twoUpVertical", json!({})).unwrap();
|
||||
window.run_steps(6);
|
||||
for (view, zoom) in window.state_mut().ui.views.iter_mut().zip([1.0, 0.5]) {
|
||||
view.zoom = zoom;
|
||||
view.center = [1500.0, 1000.0];
|
||||
view.clear_pending();
|
||||
}
|
||||
window.run_steps(4);
|
||||
assert_eq!(window.state().session.active_index(), Some(1));
|
||||
assert_eq!(window.ctx.pixels_per_point(), 1.0);
|
||||
window
|
||||
}
|
||||
|
||||
fn cameras(window: &Window) -> Vec<(f32, [f32; 2])> {
|
||||
window.state().ui.views.iter().map(|view| (view.zoom, view.center)).collect()
|
||||
}
|
||||
|
||||
fn history_lengths(window: &Window) -> Vec<usize> {
|
||||
window.state().session.documents().iter().map(|state| state.history.entries().len()).collect()
|
||||
}
|
||||
|
||||
fn enable_scroll_all(window: &mut Window) {
|
||||
let checkbox = window.get_by_role_and_label(Role::CheckBox, "Scroll All Windows");
|
||||
assert_eq!(checkbox.accesskit_node().toggled(), Some(Toggled::False));
|
||||
checkbox.click();
|
||||
window.run_steps(3);
|
||||
assert!(window.state().ui.tool_options.hand_scroll_all);
|
||||
assert_eq!(window.get_by_role_and_label(Role::CheckBox, "Scroll All Windows").accesskit_node().toggled(), Some(Toggled::True));
|
||||
}
|
||||
|
||||
/// A fixed screen-space gesture, so following a changing camera cannot add a second movement.
|
||||
fn drag_second(window: &mut Window, modifiers: Modifiers) {
|
||||
let source = ToolHost::shown_space(&window.ctx, CanvasHost::main(1).canvas_id()).expect("the active tile is shown").view;
|
||||
let start = source.rect.center();
|
||||
let delta = vec2(-100.0, -50.0);
|
||||
window.event(Event::ModifiersChanged(modifiers));
|
||||
window.hover_at(start);
|
||||
window.run_steps(2);
|
||||
window.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers });
|
||||
window.run_steps(2);
|
||||
for fraction in [0.25, 0.5, 0.75, 1.0] {
|
||||
window.event(Event::ModifiersChanged(modifiers));
|
||||
window.hover_at(start + delta * fraction);
|
||||
window.run_steps(1);
|
||||
}
|
||||
window.event(Event::PointerButton { pos: start + delta, button: PointerButton::Primary, pressed: false, modifiers });
|
||||
window.run_steps(3);
|
||||
window.event(Event::ModifiersChanged(Modifiers::NONE));
|
||||
window.run_steps(1);
|
||||
}
|
||||
|
||||
fn assert_moved(before: (f32, [f32; 2]), after: (f32, [f32; 2]), expected: Vec2) {
|
||||
assert_eq!(after.0, before.0, "a Hand drag keeps each view's zoom");
|
||||
let delta = vec2(after.1[0] - before.1[0], after.1[1] - before.1[1]);
|
||||
assert!((delta - expected).length() < 1e-3, "expected {expected:?} document pixels, got {delta:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkbox_is_saved_without_history_and_pans_both_views_in_image_pixels() {
|
||||
let mut window = window();
|
||||
assert!(!window.state().ui.tool_options.hand_scroll_all);
|
||||
let history = history_lengths(&window);
|
||||
enable_scroll_all(&mut window);
|
||||
let saved = serde_json::to_value(&*window.state().ui.tool_options).unwrap();
|
||||
let restored: ToolOptions = serde_json::from_value(saved).unwrap();
|
||||
assert!(restored.hand_scroll_all, "the option persists with the other tool options");
|
||||
assert_eq!(history_lengths(&window), history, "ticking the checkbox adds no history state");
|
||||
let before = cameras(&window);
|
||||
drag_second(&mut window, Modifiers::NONE);
|
||||
let after = cameras(&window);
|
||||
assert_moved(before[1], after[1], vec2(200.0, 100.0));
|
||||
assert_moved(before[0], after[0], vec2(200.0, 100.0));
|
||||
assert_eq!(history_lengths(&window), history, "panning adds no history state");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_drag_pans_both_views_by_the_same_image_distance() {
|
||||
let mut window = window();
|
||||
let before = cameras(&window);
|
||||
drag_second(&mut window, Modifiers::SHIFT);
|
||||
let after = cameras(&window);
|
||||
assert_moved(before[1], after[1], vec2(200.0, 100.0));
|
||||
assert_moved(before[0], after[0], vec2(200.0, 100.0));
|
||||
assert!(!window.state().ui.tool_options.hand_scroll_all);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkbox_off_without_shift_pans_only_the_dragged_view() {
|
||||
let mut window = window();
|
||||
let before = cameras(&window);
|
||||
drag_second(&mut window, Modifiers::NONE);
|
||||
let after = cameras(&window);
|
||||
assert_moved(before[1], after[1], vec2(200.0, 100.0));
|
||||
assert_eq!(after[0], before[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hand_zoom_buttons_change_only_the_active_view_with_scroll_all_on() {
|
||||
for label in ["100%", "Fit Screen", "Fill Screen"] {
|
||||
let mut window = window();
|
||||
enable_scroll_all(&mut window);
|
||||
let before = cameras(&window);
|
||||
let history = history_lengths(&window);
|
||||
window.get_by_role_and_label(Role::Button, label).click();
|
||||
window.run_steps(5);
|
||||
let after = cameras(&window);
|
||||
assert_eq!(after[0], before[0], "{label} leaves the other view unchanged");
|
||||
assert_ne!(after[1].0, before[1].0, "{label} changes the active view's zoom");
|
||||
assert_eq!(history_lengths(&window), history, "{label} adds no history state");
|
||||
assert!(window.state().ui.tool_options.hand_scroll_all);
|
||||
}
|
||||
}
|
||||
@@ -867,3 +867,15 @@ pub(crate) fn multiple_color_target(app: &PhotocraftApp) -> bool {
|
||||
&& photocraft_engine::mask_view_cmds::current(st).is_none()
|
||||
&& photocraft_engine::color_channels::selected(&app.session).is_some_and(|colors| colors.len() > 1)
|
||||
}
|
||||
|
||||
/// A real Eraser mode change starts a new sequence of Shift-click strokes.
|
||||
pub(crate) fn set_eraser_mode(app: &mut PhotocraftApp, mode: &str) {
|
||||
if app.ui.tool_options.eraser_mode != mode {
|
||||
app.ui.tool_options.eraser_mode = mode.into();
|
||||
app.last_stroke_end = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "eraser_shift_click_mode_change_tests.rs"]
|
||||
mod eraser_shift_click_mode_change_tests;
|
||||
|
||||
@@ -97,7 +97,7 @@ pub(crate) fn canvas_picture(
|
||||
if proxy == ProxyPreview::Document
|
||||
&& crate::adjust_preview::shown_key(app) == Some(preview_key)
|
||||
&& let Some(st) = app.session.documents().get(idx)
|
||||
&& crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app)) > 1
|
||||
&& crate::proxy::app_factor(app, &st.doc) > 1
|
||||
{
|
||||
(doc, preview_key) = (st.doc.clone(), 0);
|
||||
}
|
||||
|
||||
@@ -164,6 +164,8 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
|
||||
})
|
||||
}),
|
||||
"panels": legacy.get("panels").cloned().unwrap_or_else(|| json!(app.ui.panels)),
|
||||
// Window › Options (#16795): whether the options bar is on.
|
||||
"optionsBar": json!({"enabled": app.ui.panels.options_bar}),
|
||||
// The contextual task bar (#10890): Window › Contextual Task Bar, whether it shows now and
|
||||
// where (screen points), and its place (pinned, dragged-to corner).
|
||||
"taskBar": json!({
|
||||
|
||||
@@ -17,9 +17,9 @@ use craft::behavior::{EditEvent, EditEvents, Mixed};
|
||||
use craft::color_ui::ui::gradient::{ColorStop, GradientStops};
|
||||
use craft::draw::ui::gradient::{GradientGroup, GradientItem, GradientMap, GradientMapEditor, GradientMapOutput};
|
||||
use craft::imaging::ui::adjust::{
|
||||
AdjustDialogCx, AdjustField, AdjustSliders, AdjustWords, BlackWhite, BlackWhiteEditor, BrightnessContrast, BrightnessContrastEditor, ChannelMixer,
|
||||
ChannelMixerEditor, ColorBalance, ColorBalanceEditor, ColorBalanceTone, CurvesPanel, HueSaturation, HueSaturationEditor, Levels, LevelsClip, LevelsPanel,
|
||||
PhotoFilter, PhotoFilterEditor, SelectiveColor, SelectiveColorEditor, ThresholdEditor, ToneChannels, ToneCurves, ToneSpace,
|
||||
AdjustDialogCx, AdjustField, AdjustSliders, AdjustWords, BlackWhite, BrightnessContrast, BrightnessContrastEditor, ChannelMixer, ChannelMixerEditor,
|
||||
ColorBalance, ColorBalanceEditor, ColorBalanceTone, CurvesPanel, HueSaturation, HueSaturationEditor, Levels, LevelsClip, LevelsPanel, PhotoFilter,
|
||||
PhotoFilterEditor, SelectiveColor, SelectiveColorEditor, ThresholdEditor, ToneChannels, ToneCurves, ToneSpace,
|
||||
};
|
||||
use craft::imaging::ui::histogram::{ChannelColor, HistogramData};
|
||||
use craft::theme::Srgba;
|
||||
@@ -35,6 +35,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
|
||||
pub(crate) mod black_white_presets;
|
||||
mod session;
|
||||
pub mod values;
|
||||
|
||||
@@ -320,11 +321,7 @@ fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, c
|
||||
let out = editor.show(ui);
|
||||
AdjustOut { tone: Some(out.tone), ..lifted(out.edit.events, |value| AdjustValue::ColorBalance { value }) }
|
||||
}
|
||||
("blackWhite", AdjustValue::BlackWhite { value }) => {
|
||||
let out = BlackWhiteEditor::new("Black & White", Bind::bound(value)).context(context).show(ui);
|
||||
let ask = if out.auto { Some(AdjustAsk::Auto) } else { out.pick_color.map(AdjustAsk::PickColor) };
|
||||
AdjustOut { ask, edit: out.edit.events.map(|value| AdjustValue::BlackWhite { value }), tone: None }
|
||||
}
|
||||
("blackWhite", AdjustValue::BlackWhite { value }) => black_white_presets::show(ui, value, context),
|
||||
("photoFilter", AdjustValue::PhotoFilter { value }) => {
|
||||
let out = PhotoFilterEditor::new("Photo Filter", Bind::bound(value)).context(context).show(ui);
|
||||
AdjustOut { ask: out.pick_color.map(AdjustAsk::PickColor), edit: out.edit.events.map(|value| AdjustValue::PhotoFilter { value }), tone: None }
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Original Black & White recipes for tonal shifts and the effect of color filters.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::behavior::{EditEvent, EditEvents, Mixed};
|
||||
use craft::imaging::ui::adjust::{AdjustContext, AdjustWords, BlackWhite, BlackWhiteEditor};
|
||||
use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::runtime::env::Env;
|
||||
use egui::Ui;
|
||||
|
||||
use super::{AdjustAsk, AdjustOut, AdjustValue};
|
||||
|
||||
type Mix = [f64; 6];
|
||||
|
||||
/// The presets change the grayscale mix and keep the layer's tint settings.
|
||||
fn entries() -> [Entry<Option<Mix>>; 16] {
|
||||
[
|
||||
Entry::new(Some(BlackWhite::DEFAULT_WEIGHTS), tl!("Default")),
|
||||
Entry::separator(),
|
||||
Entry::new(Some([22.0, 38.0, 25.0, 36.0, 10.0, 50.0]), tl!("Darker")),
|
||||
Entry::new(Some([60.0, 77.0, 64.0, 78.0, 47.0, 92.0]), tl!("Lighter")),
|
||||
Entry::new(Some([8.0; 6]), tl!("Deep Shadows")),
|
||||
Entry::new(Some([92.0; 6]), tl!("Bright Highlights")),
|
||||
Entry::new(Some([48.0; 6]), tl!("Even Color Weights")),
|
||||
Entry::new(Some([86.0, 65.0, 33.0, 23.0, 15.0, 72.0]), tl!("Red Filter")),
|
||||
Entry::new(Some([64.0, 91.0, 64.0, 41.0, 13.0, 53.0]), tl!("Yellow Filter")),
|
||||
Entry::new(Some([28.0, 67.0, 91.0, 74.0, 17.0, 45.0]), tl!("Green Filter")),
|
||||
Entry::new(Some([24.0, 35.0, 45.0, 77.0, 92.0, 53.0]), tl!("Blue Filter")),
|
||||
Entry::new(Some([100.0, 73.0, 24.0, 7.0, 5.0, 64.0]), tl!("Strong Red Filter")),
|
||||
Entry::new(Some([4.0, 12.0, 27.0, 71.0, 100.0, 44.0]), tl!("Strong Blue Filter")),
|
||||
Entry::new(Some([58.0, 89.0, 97.0, 38.0, 8.0, 33.0]), tl!("Infrared Foliage")),
|
||||
Entry::separator(),
|
||||
Entry::new(None, tl!("Custom")),
|
||||
]
|
||||
}
|
||||
|
||||
/// A manual edit can land on exactly the weights of a named recipe. Remember that edit locally
|
||||
/// so its value still shows as Custom. The Properties inspector scopes this memory to its target.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
struct ManualValue {
|
||||
weights: Mix,
|
||||
tint: Option<[u8; 3]>,
|
||||
}
|
||||
|
||||
impl From<BlackWhite> for ManualValue {
|
||||
fn from(value: BlackWhite) -> Self {
|
||||
let [r, g, b, _] = value.tint_color.to_rgba().0;
|
||||
Self { weights: value.weights, tint: value.tint.then_some([r, g, b]) }
|
||||
}
|
||||
}
|
||||
|
||||
fn manual_id(ui: &Ui) -> egui::Id {
|
||||
ui.make_persistent_id("black-white-manual-value")
|
||||
}
|
||||
|
||||
pub(crate) fn clear_custom(ui: &Ui) {
|
||||
ui.data_mut(|d| d.remove::<ManualValue>(manual_id(ui)));
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
|
||||
/// The Properties host applies accepted Color Picker colors and Auto outside the editor's pass.
|
||||
pub(super) fn mark_custom(ui: &Ui, value: &AdjustValue) {
|
||||
if let AdjustValue::BlackWhite { value } = value {
|
||||
ui.data_mut(|d| d.insert_temp(manual_id(ui), ManualValue::from(*value)));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn show(ui: &mut Ui, value: &mut BlackWhite, context: AdjustContext) -> AdjustOut {
|
||||
let id = manual_id(ui);
|
||||
let mut manual = ui.data(|d| d.get_temp::<ManualValue>(id));
|
||||
let entries = entries();
|
||||
let shown = (manual != Some((*value).into()) && entries.iter().any(|entry| entry.value() == Some(&Some(value.weights)))).then_some(value.weights);
|
||||
let label = tl!("Preset");
|
||||
let picked = Field::new(label).show(ui, |ui, _| Select::new(label, Bind::given(shown), &entries).show(ui).events.committed().copied()).inner.flatten();
|
||||
let mut edit = EditEvents::new();
|
||||
if let Some(picked) = picked {
|
||||
manual = picked.is_none().then(|| (*value).into());
|
||||
if let Some(weights) = picked
|
||||
&& weights != value.weights
|
||||
{
|
||||
let before = *value;
|
||||
value.weights = weights;
|
||||
edit.push(EditEvent::set(Mixed::Same(before), *value, Arc::from(label), None));
|
||||
}
|
||||
}
|
||||
|
||||
let out = BlackWhiteEditor::new("Black & White", Bind::bound(&mut *value)).context(context).show(ui);
|
||||
if let Some(after) = out.edit.events.committed() {
|
||||
let words = Env::of(ui).words::<AdjustWords>();
|
||||
let reset = matches!(out.edit.events.ended(), Some(EditEvent::Set { label, .. }) if label.as_ref() == words.default_button.as_str());
|
||||
manual = (!reset).then(|| (*after).into());
|
||||
}
|
||||
ui.data_mut(|d| match manual {
|
||||
Some(value) => {
|
||||
d.insert_temp(id, value);
|
||||
}
|
||||
None => d.remove::<ManualValue>(id),
|
||||
});
|
||||
|
||||
let ask = if out.auto { Some(AdjustAsk::Auto) } else { out.pick_color.map(AdjustAsk::PickColor) };
|
||||
edit.extend(out.edit.events);
|
||||
AdjustOut { ask, edit: edit.map(|value| AdjustValue::BlackWhite { value }), tone: None }
|
||||
}
|
||||
@@ -13,7 +13,7 @@ use photocraft_engine::adjust_params;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::values::{self, ValueCx};
|
||||
use super::{AdjustAsk, AdjustValue, EditorSetup, answer_color, black_white_auto, editor, gradient_presets, is_gray, swatches};
|
||||
use super::{AdjustAsk, AdjustValue, EditorSetup, answer_color, black_white_auto, black_white_presets, editor, gradient_presets, is_gray, swatches};
|
||||
use crate::PhotocraftApp;
|
||||
use crate::color_picker_ui::PickWindow;
|
||||
use crate::theme::Tokens;
|
||||
@@ -192,7 +192,7 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj
|
||||
// put while it shows this layer, replays included.
|
||||
record.session.track(session_target(doc, id), app.properties_hidden, &committed);
|
||||
}
|
||||
follow_color_pick(app, id, &mut record, &committed, &vcx);
|
||||
follow_color_pick(app, ui, id, &mut record, &committed, &vcx);
|
||||
let mut value = match &app.live_adjust {
|
||||
Some((layer, params)) if *layer == id => values::from_params(kind, params, &vcx).unwrap_or_else(|_| committed.clone()),
|
||||
_ => committed.clone(),
|
||||
@@ -246,7 +246,12 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj
|
||||
target.extend(weights);
|
||||
}
|
||||
match values::from_params(kind, ¶ms, &vcx) {
|
||||
Ok(auto) => commit(app, id, &mut record, &committed, &auto, &vcx, None),
|
||||
Ok(auto) => {
|
||||
if auto != committed {
|
||||
black_white_presets::mark_custom(ui, &auto);
|
||||
}
|
||||
commit(app, id, &mut record, &committed, &auto, &vcx, None);
|
||||
}
|
||||
Err(err) => app.ui.status = err,
|
||||
}
|
||||
}
|
||||
@@ -294,7 +299,7 @@ fn commit(
|
||||
|
||||
/// A colour well's Color Picker while it is open: its colour previews on the layer. Once it
|
||||
/// closed, OK's colour is one edit and Cancel (or OK without a colour) leaves the layer as it was.
|
||||
fn follow_color_pick(app: &mut PhotocraftApp, id: LayerId, record: &mut PropertiesAdjust, committed: &AdjustValue, vcx: &ValueCx) {
|
||||
fn follow_color_pick(app: &mut PhotocraftApp, ui: &egui::Ui, id: LayerId, record: &mut PropertiesAdjust, committed: &AdjustValue, vcx: &ValueCx) {
|
||||
let Some(pick) = record.pick.take() else { return };
|
||||
match app.framework.dialogs.get_by_id::<ColorPickerDialog>(pick.dialog).map(ColorPickerDialog::current) {
|
||||
Some(current) => {
|
||||
@@ -310,6 +315,9 @@ fn follow_color_pick(app: &mut PhotocraftApp, id: LayerId, record: &mut Properti
|
||||
Some((key, color)) if key == pick.key && Some(color) != pick.opened => {
|
||||
let mut answered = pick.before;
|
||||
if answer_color(&mut answered, &key, color) {
|
||||
if answered != *committed {
|
||||
black_white_presets::mark_custom(ui, &answered);
|
||||
}
|
||||
commit(app, id, record, committed, &answered, vcx, None);
|
||||
} else {
|
||||
app.live_adjust = None;
|
||||
|
||||
@@ -492,3 +492,154 @@ fn black_white_auto_button_sets_the_weights() {
|
||||
assert_ne!(after, before, "the red and blue are told apart");
|
||||
assert_eq!(history_len(&h), steps + 1);
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn assert_black_white_preset(h: &Harness<'_, Box<PhotocraftApp>>, name: &str) {
|
||||
assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Preset").accesskit_node().value().as_deref(), Some(name));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_white_presets_apply_the_authored_weights_and_keep_tint() {
|
||||
let mut h = app_harness("blackWhite", "rgb", 8);
|
||||
// Leave enough vertical space for the complete dropdown to be visible at once.
|
||||
h.set_size(vec2(1440.0, 1350.0));
|
||||
let (id, _) = layer(&h);
|
||||
h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "tint": true, "tintColor": "#336699"})).unwrap();
|
||||
h.run_steps(4);
|
||||
let (_, original) = layer(&h);
|
||||
let Adjustment::BlackWhite { tint: original_tint, .. } = &original else { panic!("{original:?}") };
|
||||
|
||||
for (name, expected) in [
|
||||
("Darker", [22.0, 38.0, 25.0, 36.0, 10.0, 50.0]),
|
||||
("Lighter", [60.0, 77.0, 64.0, 78.0, 47.0, 92.0]),
|
||||
("Deep Shadows", [8.0; 6]),
|
||||
("Bright Highlights", [92.0; 6]),
|
||||
("Even Color Weights", [48.0; 6]),
|
||||
("Red Filter", [86.0, 65.0, 33.0, 23.0, 15.0, 72.0]),
|
||||
("Yellow Filter", [64.0, 91.0, 64.0, 41.0, 13.0, 53.0]),
|
||||
("Green Filter", [28.0, 67.0, 91.0, 74.0, 17.0, 45.0]),
|
||||
("Blue Filter", [24.0, 35.0, 45.0, 77.0, 92.0, 53.0]),
|
||||
("Strong Red Filter", [100.0, 73.0, 24.0, 7.0, 5.0, 64.0]),
|
||||
("Strong Blue Filter", [4.0, 12.0, 27.0, 71.0, 100.0, 44.0]),
|
||||
("Infrared Foliage", [58.0, 89.0, 97.0, 38.0, 8.0, 33.0]),
|
||||
("Default", [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]),
|
||||
] {
|
||||
let history = history_len(&h);
|
||||
h.get_by_role_and_label(Role::ComboBox, "Preset").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(Role::ListBoxOption, name).click();
|
||||
h.run_steps(4);
|
||||
|
||||
let (_, applied) = layer(&h);
|
||||
let Adjustment::BlackWhite { weights, tint } = applied else { panic!("{applied:?}") };
|
||||
assert_eq!(weights, expected, "{name} applies the authored mix");
|
||||
assert_black_white_preset(&h, name);
|
||||
assert_eq!(&tint, original_tint, "{name} preserves Tint");
|
||||
assert_eq!(history_len(&h), history + 1, "{name} is one history step");
|
||||
assert!(h.state().live_adjust.is_none(), "{name} finishes the preview");
|
||||
}
|
||||
assert_eq!(layer(&h).1, original, "Default restores the original mix");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_white_presets_apply_through_properties_and_undo() {
|
||||
let mut h = app_harness("blackWhite", "rgb", 8);
|
||||
let (id, _) = layer(&h);
|
||||
h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "tint": true, "tintColor": "#336699"})).unwrap();
|
||||
h.run_steps(4);
|
||||
let (_, before) = layer(&h);
|
||||
let Adjustment::BlackWhite { weights: original, tint: original_tint } = &before else { panic!("{before:?}") };
|
||||
let history = history_len(&h);
|
||||
let pixel = h.state_mut().run("document.pixel", json!({"x": 10, "y": 10})).unwrap();
|
||||
assert_black_white_preset(&h, "Default");
|
||||
|
||||
h.get_by_role_and_label(Role::ComboBox, "Preset").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(Role::ListBoxOption, "Darker").click();
|
||||
h.run_steps(4);
|
||||
assert_black_white_preset(&h, "Darker");
|
||||
let (_, after) = layer(&h);
|
||||
let Adjustment::BlackWhite { weights, tint } = &after else { panic!("{after:?}") };
|
||||
assert!(weights.iter().zip(original).all(|(weight, original)| weight < original));
|
||||
assert_eq!(tint, original_tint);
|
||||
assert_ne!(h.state_mut().run("document.pixel", json!({"x": 10, "y": 10})).unwrap(), pixel);
|
||||
assert_eq!(history_len(&h), history + 1);
|
||||
assert!(h.state().live_adjust.is_none());
|
||||
|
||||
let ctx = h.ctx.clone();
|
||||
let picker = open_picker(&mut h, "Tint Color");
|
||||
show_in_picker(&mut h, picker, "#ad632a");
|
||||
h.state_mut().framework.dialogs.cancel_by_id(&ctx, picker);
|
||||
h.run_steps(4);
|
||||
assert_black_white_preset(&h, "Darker");
|
||||
assert_eq!(layer(&h).1, after);
|
||||
assert_eq!(history_len(&h), history + 1);
|
||||
|
||||
let picker = open_picker(&mut h, "Tint Color");
|
||||
show_in_picker(&mut h, picker, "#ad632a");
|
||||
crate::dialogs::confirm(h.state_mut(), &ctx, picker).expect("OK is enabled");
|
||||
h.run_steps(4);
|
||||
assert_black_white_preset(&h, "Custom");
|
||||
assert_eq!(history_len(&h), history + 2);
|
||||
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert_eq!(layer(&h).1, after);
|
||||
assert_black_white_preset(&h, "Darker");
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert_eq!(layer(&h).1, before);
|
||||
assert_black_white_preset(&h, "Default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_white_presets_distinguish_manual_edits_from_named_choices() {
|
||||
let mut h = app_harness("blackWhite", "rgb", 8);
|
||||
// Opening the dropdown on Custom reveals the last row, so leave room for Default too.
|
||||
h.set_size(vec2(1440.0, 1350.0));
|
||||
let (id, defaults) = layer(&h);
|
||||
let Adjustment::BlackWhite { weights, .. } = &defaults else { panic!("{defaults:?}") };
|
||||
let red = weights[0];
|
||||
let type_default = |h: &mut Harness<'_, Box<PhotocraftApp>>| {
|
||||
h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "reds": red + 7.0})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert_black_white_preset(h, "Custom");
|
||||
h.get_by_role_and_label(Role::SpinButton, "Reds").click();
|
||||
h.run_steps(1);
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
|
||||
h.event(egui::Event::Text(red.to_string()));
|
||||
h.run_steps(1);
|
||||
h.key_press(egui::Key::Tab);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layer(h).1, defaults);
|
||||
assert_black_white_preset(h, "Custom");
|
||||
};
|
||||
|
||||
type_default(&mut h);
|
||||
|
||||
h.state_mut().run("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert_black_white_preset(&h, "Default");
|
||||
h.state_mut().run("layer.select", json!({"layer": id.0})).unwrap();
|
||||
// Layer selection can keep the mask targeted. Return to the adjustment's controls.
|
||||
h.state_mut().run("channel.target.composite", json!({})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert_black_white_preset(&h, "Custom");
|
||||
|
||||
let history = history_len(&h);
|
||||
h.get_by_role_and_label(Role::ComboBox, "Preset").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(Role::ListBoxOption, "Default").click();
|
||||
h.run_steps(4);
|
||||
assert_black_white_preset(&h, "Default");
|
||||
assert_eq!(layer(&h).1, defaults);
|
||||
assert_eq!(history_len(&h), history);
|
||||
|
||||
type_default(&mut h);
|
||||
h.get_by_role_and_label(Role::Button, "Reset to defaults").scroll_to_me();
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::Button, "Reset to defaults").click();
|
||||
h.run_steps(4);
|
||||
assert_black_white_preset(&h, "Default");
|
||||
assert_eq!(layer(&h).1, defaults);
|
||||
}
|
||||
|
||||
@@ -254,7 +254,7 @@ pub(crate) fn targets_channel(app: &PhotocraftApp, idx: usize, kind: &str, param
|
||||
fn cheap(app: &PhotocraftApp, doc: &Document) -> bool {
|
||||
match &app.gpu {
|
||||
Some(g) => g.supports(doc),
|
||||
None => crate::proxy::preview_factor(doc, crate::proxy::reduced_previews(app)) <= 1,
|
||||
None => crate::proxy::app_factor(app, doc) <= 1,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,15 +426,16 @@ pub fn gpu_proxy(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option<Proxy
|
||||
}
|
||||
let gpu = app.gpu.clone()?;
|
||||
update(app, idx)?;
|
||||
let p = app.adjust_preview.as_mut()?;
|
||||
p.shown.as_ref()?;
|
||||
let p = app.adjust_preview.as_ref()?;
|
||||
let (_, key) = p.shown.as_ref()?;
|
||||
let key = *key;
|
||||
let base = p.base.clone()?;
|
||||
let key = p.shown.as_ref()?.1;
|
||||
// `ProxyPlan::factor` is 1 for a document too small for a proxy, which `k < 2` refuses with the near views.
|
||||
let k = ProxyPlan::factor(zoom, base.size.area(), true);
|
||||
let k = ProxyPlan::factor(zoom, crate::proxy::planning_area(app, &base), true);
|
||||
if k < 2 || !photocraft_compose::proxy::proxy_faithful(&base) {
|
||||
return None;
|
||||
}
|
||||
let p = app.adjust_preview.as_mut()?;
|
||||
if p.proxy.as_ref().is_none_or(|g| g.k != k) {
|
||||
let d = proxy_base(&base, k);
|
||||
if !gpu.supports(&d) {
|
||||
|
||||
@@ -379,8 +379,7 @@ pub fn quick_export_layer_png(app: &mut PhotocraftApp, layer: LayerId) -> Result
|
||||
pick_and_export(app, f)
|
||||
}
|
||||
|
||||
/// Export each selected layer separately, with one destination prompt for the batch.
|
||||
/// The chosen path names the first file; subsequent files have numbered sibling names.
|
||||
/// Export each selected layer or group to its own PNG, named after the source.
|
||||
pub fn quick_export_selected_layers_png(app: &mut PhotocraftApp) -> Result<Value, String> {
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
let layers = st.selected_layers();
|
||||
@@ -393,28 +392,56 @@ pub fn quick_export_selected_layers_png(app: &mut PhotocraftApp) -> Result<Value
|
||||
// Capture all sources before showing the dialog: changing selection or document while it
|
||||
// is open cannot change which layers get exported.
|
||||
let docs = exportable_layers(&st.doc, layers)?;
|
||||
let suggested = format!("{}.png", export_name(&st.doc.name));
|
||||
app.pick_export(&suggested, move |app, path| {
|
||||
if !path.to_ascii_lowercase().ends_with(".png") {
|
||||
return Err("Quick Export as PNG writes .png files".into());
|
||||
}
|
||||
let paths = batch_paths(&path, &docs);
|
||||
let mut exported = Vec::new();
|
||||
for (doc, path) in docs.iter().zip(paths) {
|
||||
crate::app::ensure_memory_to_save(doc, &path)?;
|
||||
let export = app.services.export.as_ref().ok_or("no exporter configured")?;
|
||||
let (bytes, warnings) = export(doc, &path, &ExportSettings { xmp_all: false, ..Default::default() })?;
|
||||
let write = app.services.write.as_mut().ok_or("no writer configured")?;
|
||||
write(&path, &bytes)?;
|
||||
crate::notices::io_warnings(app, &format!("Exported {}", crate::file_open::display_name(&path)), &warnings);
|
||||
exported.push(json!({"path": path, "bytes": bytes.len(), "warnings": warnings}));
|
||||
}
|
||||
app.ui.status = format!("Exported {} PNG files", exported.len());
|
||||
app.ui.status_error = false;
|
||||
Ok(json!({"files": exported}))
|
||||
if let [only] = docs.as_slice() {
|
||||
let suggested = layer_export_suggestion(&only.name, "png");
|
||||
return app.pick_export(&suggested, move |app, path| {
|
||||
if !path.to_ascii_lowercase().ends_with(".png") {
|
||||
return Err("Quick Export as PNG writes .png files".into());
|
||||
}
|
||||
write_quick_pngs(app, &docs, [path], false)
|
||||
});
|
||||
}
|
||||
let names = layer_file_names(&docs, "png");
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
return write_quick_pngs(app, &docs, names, false);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
app.pick_export_folder(move |app, dir| {
|
||||
let dir = std::path::Path::new(&dir);
|
||||
// When a file already exists, a numbered alternative must also leave every other
|
||||
// selected layer's name available. Resolve each path just before writing it so names
|
||||
// the file system treats as aliases also get distinct destinations.
|
||||
let reserved: std::collections::HashSet<_> = names.iter().flat_map(|name| [name.to_uppercase(), name.to_lowercase()]).collect();
|
||||
let paths = names.iter().map(|name| {
|
||||
let stem = name.strip_suffix(".png").unwrap_or(name);
|
||||
unused_export_path(dir, stem, "png", |candidate| reserved.contains(&candidate.to_uppercase()) || reserved.contains(&candidate.to_lowercase()))
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
});
|
||||
write_quick_pngs(app, &docs, paths, true)
|
||||
})
|
||||
}
|
||||
|
||||
fn write_quick_pngs(app: &mut PhotocraftApp, docs: &[Document], paths: impl IntoIterator<Item = String>, new_files_only: bool) -> Result<Value, String> {
|
||||
let mut exported = Vec::new();
|
||||
for (doc, path) in docs.iter().zip(paths) {
|
||||
crate::app::ensure_memory_to_save(doc, &path)?;
|
||||
let export = app.services.export.as_ref().ok_or("no exporter configured")?;
|
||||
let (bytes, warnings) = export(doc, &path, &ExportSettings { xmp_all: false, ..Default::default() })?;
|
||||
// A file may have appeared at a generated path while the encoder was running.
|
||||
let write = if new_files_only {
|
||||
app.services.write_new.as_mut().ok_or("no exclusive export writer configured")?
|
||||
} else {
|
||||
app.services.write.as_mut().ok_or("no writer configured")?
|
||||
};
|
||||
write(&path, &bytes)?;
|
||||
crate::notices::io_warnings(app, &format!("Exported {}", crate::file_open::display_name(&path)), &warnings);
|
||||
exported.push(json!({"path": path, "bytes": bytes.len(), "warnings": warnings}));
|
||||
}
|
||||
app.ui.status = format!("Exported {} PNG files", exported.len());
|
||||
app.ui.status_error = false;
|
||||
Ok(json!({"files": exported}))
|
||||
}
|
||||
|
||||
/// The first 80 characters of `name`, each control character and each character a file name
|
||||
/// can't hold (`< > : " / \ | ? *`) turned into `_`.
|
||||
fn file_name_chars(name: &str) -> String {
|
||||
@@ -435,6 +462,26 @@ fn layer_export_name(name: &str) -> String {
|
||||
if name.chars().all(|c| c.is_whitespace() || c == '.') { "layer".into() } else { name }
|
||||
}
|
||||
|
||||
fn layer_export_suggestion(name: &str, ext: &str) -> String {
|
||||
generated_export_name(&layer_export_name(&stem_of(name)), ext, None)
|
||||
}
|
||||
|
||||
/// Leave room within a 255-byte filename component for the atomic writer's temporary suffix.
|
||||
const MAX_GENERATED_EXPORT_NAME_BYTES: usize = 200;
|
||||
|
||||
fn generated_export_name(stem: &str, ext: &str, number: Option<u64>) -> String {
|
||||
let suffix = number.map_or_else(String::new, |number| format!("-{number}"));
|
||||
let limit = MAX_GENERATED_EXPORT_NAME_BYTES.saturating_sub(ext.len()).saturating_sub(1 + suffix.len());
|
||||
let name_at = |limit| {
|
||||
let stem = stem.get(..stem.floor_char_boundary(limit)).unwrap_or_default();
|
||||
let stem = if stem.chars().all(|c| c.is_whitespace() || c == '.') { "layer" } else { stem };
|
||||
photocraft_engine::file_cmds::portable_device_name(format!("{stem}{suffix}.{ext}"))
|
||||
};
|
||||
let name = name_at(limit);
|
||||
// Truncation can expose a Windows device name. Its escape adds one byte.
|
||||
if name.len() > MAX_GENERATED_EXPORT_NAME_BYTES { name_at(limit.saturating_sub(1)) } else { name }
|
||||
}
|
||||
|
||||
/// The files a multi-layer export writes: the chosen path, then numbered siblings named after
|
||||
/// each layer, in the chosen path's format.
|
||||
fn batch_paths(path: &str, docs: &[Document]) -> Vec<String> {
|
||||
@@ -448,27 +495,36 @@ fn batch_paths(path: &str, docs: &[Document]) -> Vec<String> {
|
||||
if i == 0 {
|
||||
return path.to_string();
|
||||
}
|
||||
let name = export_name(&doc.name);
|
||||
let candidate = parent.join(format!("{stem}-{}-{name}.{ext}", i + 1));
|
||||
let numbered = format!("{stem}-{}-{}", i + 1, export_name(&doc.name));
|
||||
// The first file's overwrite is handled by the Save dialog; never overwrite sibling
|
||||
// files silently on desktop. Downloads on the web are named by the browser.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let candidate = {
|
||||
let mut candidate = candidate;
|
||||
let mut suffix = 1u64;
|
||||
// A name any entry occupies is taken, a symlink (even a dangling one) included: the writer
|
||||
// follows links, so one planted here would redirect the export.
|
||||
while candidate.symlink_metadata().is_ok() {
|
||||
candidate = parent.join(format!("{stem}-{}-{name}-{suffix}.{ext}", i + 1));
|
||||
suffix = suffix.saturating_add(1);
|
||||
}
|
||||
candidate
|
||||
};
|
||||
let candidate = unused_export_path(parent, &numbered, ext, |_| false);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let candidate = parent.join(format!("{numbered}.{ext}"));
|
||||
candidate.to_string_lossy().into_owned()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Keep existing entries, including links (even dangling ones), when choosing an output path.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn unused_export_path(dir: &std::path::Path, stem: &str, ext: &str, reserved: impl Fn(&str) -> bool) -> std::path::PathBuf {
|
||||
let candidate = dir.join(generated_export_name(stem, ext, None));
|
||||
if candidate.symlink_metadata().is_err() {
|
||||
return candidate;
|
||||
}
|
||||
let mut suffix = 1u64;
|
||||
loop {
|
||||
let name = generated_export_name(stem, ext, Some(suffix));
|
||||
let candidate = dir.join(&name);
|
||||
if !reserved(&name) && candidate.symlink_metadata().is_err() {
|
||||
return candidate;
|
||||
}
|
||||
suffix = suffix.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// The document a dialog exports: the whole image, or one layer (`__layer`).
|
||||
fn source_document_from(doc: Arc<Document>, f: &Map<String, Value>) -> Result<Arc<Document>, String> {
|
||||
match f.get("__layer").and_then(Value::as_u64) {
|
||||
@@ -1073,8 +1129,8 @@ fn export_to(app: &mut PhotocraftApp, f: &Map<String, Value>, path: &str) -> Res
|
||||
/// A layer's name may hold characters a file name can't (#14810): `a/b:c*?` suggests `a_b_c__`.
|
||||
fn pick_and_export(app: &mut PhotocraftApp, f: Map<String, Value>) -> Result<Value, String> {
|
||||
let doc = source_document(app, &f)?;
|
||||
let stem = if f.contains_key("__layer") { layer_export_name(&stem_of(&doc.name)) } else { stem_of(&doc.name) };
|
||||
let suggested = format!("{stem}.{}", s_fmt(&f));
|
||||
let ext = s_fmt(&f);
|
||||
let suggested = if f.contains_key("__layer") { layer_export_suggestion(&doc.name, &ext) } else { format!("{}.{ext}", stem_of(&doc.name)) };
|
||||
app.pick_export(&suggested, move |app, path| export_to(app, &f, &path))
|
||||
}
|
||||
|
||||
@@ -1185,7 +1241,7 @@ pub(crate) fn replay(app: &mut PhotocraftApp, params: &Value) -> Result<Value, S
|
||||
/// layers are skipped (#14806). With several files on the desktop `path` is the folder the dialog
|
||||
/// asked for, and each layer is written there as `<layer name>.<ext>`, replacing a file of that
|
||||
/// name (#14808). One file is written at `path`; the web downloads each file, the first under
|
||||
/// `path` and the others named as Quick Export names a selection's files.
|
||||
/// `path` and the others under numbered names derived from that filename and their layer names.
|
||||
fn export_layers(app: &mut PhotocraftApp, f: &Map<String, Value>, ids: &[LayerId], path: &str) -> Result<Value, String> {
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
let source_profile = effective_source_profile(app, &st.doc);
|
||||
@@ -1239,7 +1295,7 @@ fn write_layer_file(
|
||||
/// can't hold becomes `_` (`a/b:c*?` → `a_b_c__`), spaces are kept.
|
||||
fn layer_file_stem(name: &str) -> String {
|
||||
let stem: String = name.chars().map(|c| if c.is_control() || "<>:\"/\\|?*".contains(c) { '_' } else { c }).collect();
|
||||
if stem.chars().all(|c| c.is_whitespace() || c == '.') { "layer".into() } else { stem }
|
||||
if stem.chars().all(|c| c.is_whitespace() || c == '.') { "layer".into() } else { photocraft_engine::file_cmds::portable_device_name(stem) }
|
||||
}
|
||||
|
||||
/// The names several layers' files get, for `docs` in document order (bottom to top). Equal
|
||||
@@ -1257,10 +1313,10 @@ fn layer_file_names(docs: &[Document], ext: &str) -> Vec<String> {
|
||||
let mut names = vec![String::new(); docs.len()];
|
||||
for (i, doc) in docs.iter().enumerate().rev() {
|
||||
let stem = layer_file_stem(&doc.name);
|
||||
let mut name = format!("{stem}.{ext}");
|
||||
let mut name = generated_export_name(&stem, ext, None);
|
||||
let mut n = 1u64;
|
||||
while taken(&used, &name) {
|
||||
name = format!("{stem}-{n}.{ext}");
|
||||
name = generated_export_name(&stem, ext, Some(n));
|
||||
n = n.saturating_add(1);
|
||||
}
|
||||
used.insert(name.to_uppercase());
|
||||
|
||||
@@ -70,9 +70,11 @@ fn answer(app: &mut PhotocraftApp, files: &ScriptedFiles, path: &std::path::Path
|
||||
fn quick_export_skips_the_same_layers() {
|
||||
let (mut app, l, written, files) = app();
|
||||
*app.session.active_mut().unwrap().selection_mut() = vec![l.empty, l.red, l.adjustment, l.blue, l.gone];
|
||||
app.services.write_new = app.services.write.take();
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
quick_export_selected_layers_png(&mut app).unwrap();
|
||||
answer(&mut app, &files, std::path::Path::new("quick.png"));
|
||||
assert_eq!(*written.borrow(), ["quick.png", "quick-2-Blue.png"]);
|
||||
answer(&mut app, &files, out.path());
|
||||
assert_eq!(*written.borrow(), [out.path().join("Red.png").to_string_lossy(), out.path().join("Blue.png").to_string_lossy()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -89,6 +89,21 @@ mod planted_link {
|
||||
request
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_export_uses_one_folder_and_names_each_file_after_its_layer() {
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut app, ids, _, written, files) = app();
|
||||
app.services.write_new = app.services.write.take();
|
||||
app.session.restore_layer_selection(Some(ids[0]), &ids, None).unwrap();
|
||||
quick_export_selected_layers_png(&mut app).unwrap();
|
||||
assert_eq!(files.requests().last().unwrap().kind, craft::host::PickKind::Folder);
|
||||
files.answer(Picked::Paths(vec![out.path().to_path_buf()])).unwrap();
|
||||
app.poll_file_dialog();
|
||||
let written = written.borrow();
|
||||
let actual: Vec<_> = written.iter().map(|p| std::path::Path::new(p).file_name().unwrap().to_str().unwrap()).collect();
|
||||
assert_eq!(actual, ["a_b_c__.png", "Dup-1.png", "Dup.png"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_planted_link_is_replaced_not_followed() {
|
||||
let guard = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -5,25 +5,45 @@
|
||||
//! export's `export_name`.
|
||||
|
||||
use super::*;
|
||||
use craft::host::ScriptedFiles;
|
||||
use craft::host::{PickKind, ScriptedFiles};
|
||||
|
||||
/// The file name Layer › Quick Export as PNG suggests for a layer named `name` (the Save dialog
|
||||
/// stays open), and the whole save request as text.
|
||||
fn suggested_for(name: &str) -> (String, String) {
|
||||
suggested_for_selection(name, false)
|
||||
}
|
||||
|
||||
fn suggested_for_selection(name: &str, include_empty: bool) -> (String, String) {
|
||||
let files = Arc::new(ScriptedFiles::held());
|
||||
let services = crate::Services { files: Some(files.clone()), ..Default::default() };
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
|
||||
app.run("file.new", json!({"width": 20, "height": 20})).unwrap();
|
||||
app.run("layer.new.layer", json!({"name": "Empty"})).unwrap();
|
||||
let empty = app.session.active().unwrap().active_layer.unwrap();
|
||||
app.run("layer.new.layer", json!({"name": name})).unwrap();
|
||||
app.run("select.rect", json!({"x": 2, "y": 2, "width": 6, "height": 6})).unwrap();
|
||||
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
|
||||
let layer = app.session.active().unwrap().active_layer.unwrap();
|
||||
quick_export_layer_png(&mut app, layer).unwrap();
|
||||
if include_empty {
|
||||
app.session.restore_layer_selection(Some(layer), &[empty, layer], None).unwrap();
|
||||
}
|
||||
crate::menus::invoke(&mut app, &egui::Context::default(), "layer.quickExportAsPng", Value::Null).unwrap();
|
||||
let asked = files.requests();
|
||||
let [request] = asked.as_slice() else { panic!("one Save dialog: {asked:?}") };
|
||||
assert_eq!(request.kind, PickKind::Save);
|
||||
(request.file_name.clone().unwrap_or_default(), format!("{request:?}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_export_suggests_the_same_name_when_an_empty_layer_is_selected() {
|
||||
for name in ["Hero.v2", "a/b:c*?", "CON", &"界".repeat(100)] {
|
||||
let (single, _) = suggested_for(name);
|
||||
let (with_empty, _) = suggested_for_selection(name, true);
|
||||
assert_eq!(with_empty, single, "{name:?}");
|
||||
assert!(single.len() <= MAX_GENERATED_EXPORT_NAME_BYTES);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_named_with_illegal_characters_suggests_underscores() {
|
||||
let (file, path) = suggested_for("a/b:c*?");
|
||||
|
||||
@@ -631,8 +631,8 @@ fn specs(keys: &HashMap<String, String>, user: &Map<String, Value>, light: f32)
|
||||
.filter_map(|(key, _)| {
|
||||
let kind = EffectKind::from_key(key)?;
|
||||
let mut spec = EffectSpec::photoshop(kind).with_blend_keys(keys);
|
||||
if kind == EffectKind::OuterGlow {
|
||||
// #14944: Photoshop groups the Outer Glow rows Structure / Elements / Quality and
|
||||
if matches!(kind, EffectKind::OuterGlow | EffectKind::InnerGlow) {
|
||||
// #14944, #14917: Photoshop groups the glow rows Structure / Elements / Quality and
|
||||
// puts Noise right under Opacity. The hosted page draws the spec's rows in order,
|
||||
// so the host moves the row; the group titles belong to the framework's page.
|
||||
if let Some(noise) = spec.fields.iter().position(|f| f.key == "noise") {
|
||||
|
||||
@@ -766,10 +766,10 @@ fn a_new_satin_in_the_dialog_starts_at_the_factory_values() {
|
||||
/// #14944: the Outer Glow page is grouped Photoshop-style - Noise right under Opacity, the rows of
|
||||
/// the Structure, Elements and Quality blocks. The hosted page draws `specs()` rows in order, so
|
||||
/// the page order is pinned here; the group TITLES belong to the framework's page (craft-libs has
|
||||
/// no header row on an effect page yet) and the other pages keep the framework's order (#14917 is
|
||||
/// the Inner Glow's own ticket).
|
||||
/// no header row on an effect page yet). #14917 groups the Inner Glow page the same way; the
|
||||
/// other pages keep the framework's order.
|
||||
#[test]
|
||||
fn the_outer_glow_page_rows_group_noise_under_opacity() {
|
||||
fn the_glow_page_rows_group_noise_under_opacity() {
|
||||
let row_keys = |want: &str| {
|
||||
specs(&blend_keys(), &Map::new(), 120.0)
|
||||
.into_iter()
|
||||
@@ -781,11 +781,7 @@ fn the_outer_glow_page_rows_group_noise_under_opacity() {
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(row_keys("outerGlow"), ["blend", "opacity", "noise", "color", "technique", "spread", "size", "contour", "range"]);
|
||||
assert_eq!(
|
||||
row_keys("innerGlow"),
|
||||
["blend", "opacity", "color", "technique", "source", "choke", "size", "contour", "range", "noise"],
|
||||
"the Inner Glow page stays as it is"
|
||||
);
|
||||
assert_eq!(row_keys("innerGlow"), ["blend", "opacity", "noise", "color", "technique", "source", "choke", "size", "contour", "range"]);
|
||||
assert_eq!(
|
||||
row_keys("dropShadow"),
|
||||
["blend", "color", "opacity", "angle", "useGlobalLight", "distance", "spread", "size", "contour", "noise", "knocksOut"],
|
||||
@@ -818,6 +814,33 @@ fn a_new_outer_glow_opens_at_the_factory_values_and_ok_keeps_them() {
|
||||
assert_eq!(hex(c), "#ffffff", "OK stored the colour");
|
||||
}
|
||||
|
||||
/// #14917: a new Inner Glow opens at the reference application's factory values, and OK stores
|
||||
/// exactly those.
|
||||
#[test]
|
||||
fn a_new_inner_glow_opens_at_the_factory_values_and_ok_keeps_them() {
|
||||
let mut app = app_with_layer(32);
|
||||
let id = open(&mut app, Some(EffectKind::InnerGlow.key())).unwrap();
|
||||
let glow = first_of(&app, id, EffectKind::InnerGlow);
|
||||
let style = &draft(&app, id).style;
|
||||
assert_eq!(
|
||||
(text(style, glow, "blend").as_deref(), text(style, glow, "technique").as_deref(), text(style, glow, "source").as_deref()),
|
||||
(Some("Screen"), Some("softer"), Some("edge"))
|
||||
);
|
||||
assert_eq!(
|
||||
(num(style, glow, "opacity"), num(style, glow, "noise"), num(style, glow, "choke"), num(style, glow, "size"), num(style, glow, "range")),
|
||||
(Some(35.0), Some(0.0), Some(0.0), Some(7.0), Some(50.0)),
|
||||
"the page's own seed"
|
||||
);
|
||||
assert_eq!(style.effect(glow).and_then(|e| e.params.bool("antiAlias")), Some(false));
|
||||
let Some(StyleValue::Color(c)) = param(style, glow, "color") else { panic!("the colour row loads as a colour") };
|
||||
assert_eq!(color_picker_ui::hex(c.to_rgb_array()), "#ffffff", "the page's own colour");
|
||||
ok(&mut app, id);
|
||||
let Effect::InnerGlow(g) = &layer_effects(&app.session)[0] else { panic!("{:?}", layer_effects(&app.session)) };
|
||||
assert!((g.common.opacity * 100.0 - 35.0).abs() < 1e-4 && (g.size - 7.0).abs() < 1e-4, "OK stored {g:?}");
|
||||
let FxPaint::Color(c) = &g.paint else { panic!("{:?}", g.paint) };
|
||||
assert_eq!(hex(c), "#ffffff", "OK stored the colour");
|
||||
}
|
||||
|
||||
/// #14944: the factory values never reach an Outer Glow the layer already carries: the page shows
|
||||
/// its own values and OK keeps them, as it does for a glow read from a PSD or `.pcraft`.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
use super::{COMMAND, testing};
|
||||
use crate::{PhotocraftApp, Services};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn new_layer_dialog_trims_only_its_name() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
|
||||
app.run("file.new", json!({"width": 16, "height": 16})).unwrap();
|
||||
let ctx = app.ctx().clone();
|
||||
|
||||
for (typed, expected) in [(" sp a ", Some("sp a")), ("", None), (" ", None)] {
|
||||
let default = app.session.active().unwrap().doc.next_layer_name("Layer");
|
||||
crate::menus::invoke(&mut app, &ctx, COMMAND, json!({})).unwrap();
|
||||
let id = testing::top(&app);
|
||||
testing::set(&mut app, id, "name", json!(typed)).unwrap();
|
||||
crate::dialogs::confirm(&mut app, &ctx, id).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.last().unwrap().name, expected.unwrap_or(&default));
|
||||
}
|
||||
|
||||
app.run(COMMAND, json!({"name": "abc "})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.last().unwrap().name, "abc ");
|
||||
}
|
||||
@@ -88,7 +88,7 @@ pub fn params(f: &DialogFields) -> Value {
|
||||
});
|
||||
// An empty name gets the next "Layer N", as the Layers panel button does.
|
||||
if let Some(name) = f.text("name").filter(|n| !n.trim().is_empty()) {
|
||||
p["name"] = json!(name);
|
||||
p["name"] = json!(name.trim_matches(' '));
|
||||
}
|
||||
p
|
||||
}
|
||||
@@ -130,6 +130,10 @@ pub(crate) mod testing {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "new_layer_name_trim_tests.rs"]
|
||||
mod new_layer_name_trim_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user