Merge remote-tracking branch 'upstream/main' into brush-presets-tidy

This commit is contained in:
aiongg committed 2026-11-19 16:05:21 +00:00
commit d25d798e3a
161 files changed
+1294 -452

No files matched your search

+6
View File
@@ -33,6 +33,12 @@ test-group = 'gpu'
fail-fast = false
slow-timeout = { period = "60s", terminate-after = 10 }
failure-output = "immediate-final"
# The gate's shards run the tests from a nextest archive (`cargo xtask ci archive`) and start them
# with the xtask binary the archive carries, so a shard builds nothing. Only one of the two exists.
archive.include = [
{ path = "debug/xtask", relative-to = "target", depth = 0, on-missing = "ignore" },
{ path = "debug/xtask.exe", relative-to = "target", depth = 0, on-missing = "ignore" },
]
# Keep phase timings for the remaining expensive Windows GPU regressions visible. This does
# not relax their timeout, isolate failures differently or remove any test cases.
+80 -30
View File
@@ -2,10 +2,14 @@ name: CI
# Quality gates for every push to main and every pull request. The Linux and Windows tests run
# through the suite's shared gate workflow in craft-common-actions (`cargo xtask ci`, split over the
# gate's jobs); the test variant and the corpus, web and fuzz jobs are PhotoCraft's own.
# gate's jobs); the test variant and the corpus, web and fuzz jobs are PhotoCraft's own. Every night
# the Linux gate alone runs a cold build: the safety net for the workspace crates it keeps between
# runs (`cache-workspace-crates`), and a fresh start for that cache entry.
on:
push:
branches: [main]
schedule:
- cron: "11 3 * * *"
pull_request:
# `labeled` so that adding `full-ci` to an open PR starts a run with Windows in it.
types: [opened, synchronize, reopened, labeled]
@@ -70,7 +74,7 @@ concurrency:
jobs:
# Git dependencies come from github.com/storytold, and Cargo.lock is complete and up to date.
git-sources:
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci')
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main
@@ -86,7 +90,7 @@ jobs:
# `windows_skip`: the platform-neutral packages whose Windows tests a pull request skips because nothing it
# changes reaches them (same script); empty on main and `full-ci`.
platforms:
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci')
timeout-minutes: 10
name: select platforms
runs-on: ubuntu-latest
@@ -145,13 +149,17 @@ jobs:
fi
# The Linux gate (craft-common-actions gate.yml). Its `lint` leg runs the checks that need no test
# build; four test shards each build the tests from the restored cache and run their share
# (scripts/ci-test-shard.sh). Shard 1 runs nextest's `gpu` group alone, on lavapipe, and fails on
# a skipped GPU comparison (scripts/ci-gpu-lavapipe.py); shards 2-4 split the other tests, and
# shard 2 runs the doctests. The `gpu` group is ~2400 test-seconds on 4 slots (~12 min with its
# slowest test, ~8 once the five slow UI tests are fixed); the other ~5900 test-seconds over 3
# shards are ~8 min each, so a fifth shard would not shorten the gate. Its rust-cache entry is
# the one `test (without heif)` restores.
# build. The `build` job builds the tests once into a nextest archive (`cargo xtask ci archive`),
# uploads it and then runs the doctests; four test shards download the archive and run their
# share (scripts/ci-test-shard.sh). Shard 1 runs nextest's `gpu` group alone, on lavapipe, and
# fails on a skipped GPU comparison (scripts/ci-gpu-lavapipe.py); shards 2-4 split the other
# tests. The `gpu` group is ~840 test-seconds on 4 slots (~3.5 min); the other ~6900
# test-seconds over 3 shards are ~8.5-10.5 min each.
# The build keeps the compiled workspace crates between runs (`cache-workspace-crates`), so a
# pull request rebuilds only the crates its changes reach. Each main run's build job saves a
# rolling entry of its own, which `test (without heif)` restores too; `gate-cache-prune` keeps
# the newest one. The lint legs keep no cache (`lint-cache: false`): a cold lint leg costs
# minutes, and their entries (~1 GB per OS) would not fit the 10 GB cache budget.
gate:
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
@@ -175,28 +183,28 @@ jobs:
LPDEST=photocraft-no-such-printer
CARGO_PROFILE_TEST_STRIP=symbols
timeout-minutes: 100
# On main, a `cache warm` leg builds xtask and the tests, as each shard does, and saves the
# dependency cache as soon as the build succeeds; the shards then only restore, so a failing
# test cannot keep the entry from being saved (craft-common-actions#270). The lint leg keeps
# its own entry.
warm-command: cargo xtask ci build
cache-workspace-crates: true
lint-cache: false
cold-build: ${{ github.event_name == 'schedule' }}
# fmt, egui-fork, clippy, layers, panel-commands, scorecard, the wasm32 check and the
# missing-translations report (`cargo xtask ci lint`, xtask/src/main.rs), and the CI scripts'
# own tests.
lint-command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && cargo xtask ci lint
archive-command: cargo xtask ci archive
after-archive-command: cargo xtask ci doctest
test-shards: 4
# The tests and panic_hunt with `--locked --features heif` (TEST_TARGETS in xtask/src/main.rs).
shard-command: bash scripts/ci-test-shard.sh --gpu-shard
# The Windows tests and Clippy on the same gate, when `platforms` says the run needs them: a
# `lint` leg runs Clippy, and six shards each build the tests and run their hash partition;
# shard 1 also runs the doctests. Windows runs the tests ~1.75x slower than Linux: ~55 min on
# one runner, ~9 min per shard. A seventh shard would not shorten the slowest one while its
# slowest test alone takes ~9.6 min (the shortcut-dispatch UI test). The browser apps are wasm
# targets, so their native tests are left out;
# pull requests also leave out photocraft-gpu and the platform-neutral packages nothing they change
# reaches (`windows_gpu`, `windows_skip`). The `cache warm` leg (main only) builds what main's
# build job builds.
# `lint` leg runs Clippy, the `build` job builds the tests once into a nextest archive and then
# runs the doctests, and six shards run their slice of the tests from the archive. Windows runs
# the tests ~1.75x slower than Linux: ~55 min on one runner, ~9 min per shard. A seventh shard
# would not shorten the slowest one while its slowest test alone takes ~9.6 min (the
# shortcut-dispatch UI test). The browser apps are wasm targets, so their native tests are left
# out; pull requests also leave out photocraft-gpu and the platform-neutral packages nothing they
# change reaches (`windows_gpu`, `windows_skip`). Windows keeps a dependency-only cache entry:
# its workspace crates would not fit the repository's cache budget beside Linux's.
windows:
needs: platforms
if: needs.platforms.outputs.windows == 'true'
@@ -204,6 +212,7 @@ jobs:
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["windows-latest"]'
lint-cache: false
# The all-language UI tests shape real Japanese, Chinese, Korean and Devanagari labels with
# kittest's strict `MissingGlyphPolicy::Panic`, and a hosted Windows image has no guaranteed
# Japanese or Simplified Chinese system font. Same pinned central fonts as Linux and release.
@@ -229,17 +238,57 @@ jobs:
CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS=-Clink-arg=/OPT:NOICF -Clink-arg=/DEBUG:NONE
PHOTOCRAFT_CI_EXCLUDE=photocraft-web photocraft-web-boot ${{ needs.platforms.outputs.windows_gpu == 'false' && 'photocraft-gpu' || '' }} ${{ needs.platforms.outputs.windows_skip }}
timeout-minutes: 100
warm-command: cargo xtask ci build
lint-command: cargo xtask ci clippy
archive-command: cargo xtask ci archive
after-archive-command: cargo xtask ci doctest
test-shards: 6
shard-command: bash scripts/ci-test-shard.sh
# The Linux gate's build job saves a rolling cache entry of its own on every main and nightly run
# (`cache-workspace-crates`), about 3.8 GB, and every run restores only the newest. This deletes
# the older ones at once instead of leaving them to the 10 GB budget's eviction, which would
# evict other entries too.
gate-cache-prune:
needs: gate
if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }}
timeout-minutes: 5
runs-on: ubuntu-24.04
permissions:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- name: Delete all but the newest rolling entry of each job and runner
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
run: |
set -euo pipefail
# `<version>-rust-<profile>-<job>-crates-<os>-<arch>-<run>-<attempt>-...`, newest first.
gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \
--jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches"
declare -A kept
while read -r id key; do
[[ "$key" =~ ^.+-rust-[0-9a-f]{64}-(.+-crates-[A-Za-z_]+-[a-z0-9]+)-[0-9]+-[0-9]+- ]] || continue
entry=${BASH_REMATCH[1]}
if [ -n "${kept[$entry]:-}" ]; then
echo "delete $key"
gh cache delete "$id" --repo "$REPO"
else
kept[$entry]=1
echo "keep $key"
fi
done < "$RUNNER_TEMP/caches"
# The same codecs without the optional decoder: HEIC must stay a clear "not in this build" error
# for distributors who leave it out. Runs beside the gate and restores the gate's dependency
# cache without saving one: the dependencies are the same, and the 10 GB cache budget is tight
# (#2688).
# for distributors who leave it out. Runs beside the gate and restores the gate's newest rolling
# cache entry without saving one: the dependencies are the same, and the 10 GB cache budget is
# tight (#2688). Its sources keep their checkout mtimes, so the workspace crates it builds are
# rebuilt.
test-without-heif:
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci')
timeout-minutes: 60
name: test (without heif)
# The gate's runner: its cache entry is keyed on the OS.
@@ -277,11 +326,12 @@ jobs:
# The gate's own key (the shared action computes it), restore only. The toolchain action
# exports CARGO_HOME, which the gate's legs do not have; align-environment leaves it out of
# the key.
# the cache paths.
- uses: storytold/craft-common-actions/actions/rust-cache@main
with:
cache-version: v2
job: gate
cache-workspace-crates: "true"
align-environment: "true"
- uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32
@@ -292,7 +342,7 @@ jobs:
run: cargo nextest run -p photocraft-io --locked --profile ci
corpus:
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci')
timeout-minutes: 30
# Real-file corpus tests (cargo feature `corpus`), on every PR and on main. The corpora are
# pinned in xtask/src/corpus_pins.rs and sha256-verified (xtask/*.sha256) after both a cache
+2
View File
@@ -21,4 +21,6 @@ jobs:
with:
timeout-minutes: 120
fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
# The coverage build's ~1.3 GB cache would not fit the repository's 10 GB cache budget.
build-cache: false
secrets: inherit
Generated
+8
View File
@@ -6677,6 +6677,14 @@ dependencies = [
"craft-ipp",
]
[[package]]
name = "photocraft-oil-round-proof"
version = "0.23.1"
dependencies = [
"photocraft-algo",
"rayon",
]
[[package]]
name = "photocraft-ops"
version = "0.23.1"
+4
View File
@@ -176,6 +176,10 @@ opt-level = 0
[profile.test.package.photocraft-engine]
opt-level = 0
# Only the exhaustive rounding proof needs maximum optimization; algo stays at its usual level.
[profile.test.package.photocraft-oil-round-proof]
opt-level = 3
# Test builds compile the craft UI framework (the `craft` facade and the craft-libs crates behind
# it) below the opt-level 2 of `package."*"` above. The workspace unifies the facade's features, so
# every crate that uses `craft`, photocraft-text included, waits for the whole framework. At 2 the
+4 -1
View File
@@ -10,7 +10,10 @@ const PRINT_ONLY: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"];
/// The built exe names each print-only DLL in its delay-load table, never its import table.
#[test]
fn print_only_system_dlls_are_delay_loaded() {
let exe = std::fs::read(env!("CARGO_BIN_EXE_photocraft")).unwrap();
// The run-time variable first: a run from a nextest archive points it at the extracted exe,
// while the compile-time path names the directory the archive was built in.
let path = std::env::var("CARGO_BIN_EXE_photocraft").unwrap_or_else(|_| env!("CARGO_BIN_EXE_photocraft").to_string());
let exe = std::fs::read(path).unwrap();
let pe = Pe::parse(&exe);
let imports = pe.dll_names(1, 20, 12);
let delayed = pe.dll_names(13, 32, 4);
+5 -1
View File
@@ -255,7 +255,11 @@ fn layer_box_blurs_match_direct_convolution_at_any_radius() {
SampleType::U16 => 1.0 / 65535.0,
_ => 0.0,
} + 2e-5;
for p in &params {
// Each format sees both blur modes; each radius is covered across formats.
for (pi, p) in params.iter().enumerate() {
if pi % 2 != i % 2 {
continue;
}
let boxes = box_widths(p).expect("a box-pass blur");
let reach: i32 = boxes.iter().map(|w| (w / 2) as i32).sum();
let area = crate::output_area(p, s.content_bounds(), canvas, None);
+4 -2
View File
@@ -110,12 +110,14 @@ fn offset_fast_path_matches_the_per_channel_oracle() {
for (mode, n, alpha) in layouts {
let src = image(win, n, alpha);
let ctx = Ctx { bounds: win, mode, alpha };
for radius in [0.1f32, 1.0, 3.0, 12.0, 17.5] {
// Centre only, unit stride, and a coarse stride for both qualities. At 13 the inner
// rectangle still has pixels, so coarse offsets exercise the fast path too.
for radius in [0.1f32, 3.0, 13.0] {
let ri = f32::ceil(radius) as i32;
// The usual tile (the window less the halo), the whole window, and one sticking out of it.
let inner = Rect::new(win.x0 + ri, win.y0 + ri, win.x1 - ri, win.y1 - ri);
for out in [inner, win, Rect::new(-12, -9, 10, 8), Rect::EMPTY] {
// Quality only sets the offset stride: Low a coarse one, High every offset at these radii (#15652).
// Quality selects the offset stride; both paths are compared to the oracle.
for quality in [BlurQuality::Low, BlurQuality::High] {
for sm in [SmartBlurMode::Normal, SmartBlurMode::EdgeOnly, SmartBlurMode::OverlayEdge] {
for threshold in [8.0, 60.0] {
+7 -3
View File
@@ -149,9 +149,13 @@ fn iris_depths_models_selection_tiles_and_cancellation() {
let mut selection = Surface::new(PixelFormat::GRAY8);
selection.fill_rect(bounds, &[0.4]);
selection.fill_rect(Rect::new(3, 19, 35, 44), &[1.0]);
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
for alpha in [false, true] {
// Cover every mode/sample pair and both alpha values for each mode and sample.
for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() {
for (si, sample) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() {
for (ai, alpha) in [false, true].into_iter().enumerate() {
if (mi + si) % 2 != ai {
continue;
}
let fmt = PixelFormat::new(mode, sample, alpha);
let mut surface = Surface::new(fmt);
surface.write_region(bounds, &image(bounds, fmt.channels()).data);
+2 -2
View File
@@ -186,10 +186,10 @@ fn a_hole_is_as_thick_as_it_is_through_not_along() {
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn thin_holes_are_filled_the_same_on_any_number_of_threads() {
let (w, h) = (300, 200);
let (w, h) = (150, 100);
let img = busy(w, h, 3, 5);
// A wavy line 6 px thick across the image.
let hole: Vec<bool> = (0..w * h).map(|i| (((i % w) as f32 * 0.05).sin() * 30.0 + 100.0 - (i / w) as f32).abs() < 3.0).collect();
let hole: Vec<bool> = (0..w * h).map(|i| (((i % w) as f32 * 0.05).sin() * 15.0 + 50.0 - (i / w) as f32).abs() < 3.0).collect();
let px = roles(w, h, &hole);
let run = |threads: usize| {
let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
+2 -30
View File
@@ -30,16 +30,8 @@ fn stroke_len(stylization: f32) -> f32 {
1.5 + stylization.clamp(0.1, 10.0) * 2.0
}
/// `f32::round` (half away from zero) as an integer, without the `roundf` call `f32::round`
/// makes on the baseline x86-64 target. The sum is taken in `f64`, where `v ± 0.5` is exact for
/// every `f32` the cast does not saturate (an `f32` sum is not: `0.49999997 + 0.5` rounds up to
/// `1.0`), so the result equals `v.round() as i32` for every `f32`, NaN (0) and the saturating
/// ends included.
#[inline]
fn round_i32(v: f32) -> i32 {
let v = f64::from(v);
(v + 0.5f64.copysign(v)) as i32
}
mod round;
use round::round_i32;
/// [`round_i32`] clamped into `0..n`.
#[inline]
@@ -250,24 +242,4 @@ mod tests {
assert_eq!(round_index(f32::INFINITY, n), ((n - 1) as f32) as usize);
}
}
/// Every `f32` bit pattern in [-4096, 4096] (both signs, about 2.3e9 values, split across
/// threads) rounds exactly like `f32::round`.
#[test]
fn rounding_matches_the_standard_library_for_every_f32_up_to_4096() {
use rayon::prelude::*;
let last = 4096.0f32.to_bits();
let bad = (0..=last >> 20)
.into_par_iter()
.filter_map(|hi| {
let lo = hi << 20;
let hi_end = (lo | 0xf_ffff).min(last);
(lo..=hi_end).find_map(|bits| {
let v = f32::from_bits(bits);
[v, -v].into_iter().find(|v| round_i32(*v) != v.round() as i32)
})
})
.min_by(|a, b| a.abs().total_cmp(&b.abs()));
assert_eq!(bad, None, "round_i32 differs from f32::round");
}
}
+10
View File
@@ -0,0 +1,10 @@
/// `f32::round` (half away from zero) as an integer, without the `roundf` call `f32::round`
/// makes on the baseline x86-64 target. The sum is taken in `f64`, where `v ± 0.5` is exact for
/// every `f32` the cast does not saturate (an `f32` sum is not: `0.49999997 + 0.5` rounds up to
/// `1.0`), so the result equals `v.round() as i32` for every `f32`, NaN (0) and the saturating
/// ends included.
#[inline]
pub(super) fn round_i32(v: f32) -> i32 {
let v = f64::from(v);
(v + 0.5f64.copysign(v)) as i32
}
+1 -1
View File
@@ -367,7 +367,7 @@ fn multiband_matches_the_serial_code() {
/// none and everything, pass through every split the images can have (#15652; it swept 47 budgets).
#[test]
fn multiband_batches_match_the_serial_code() {
for (n, &(w, h)) in [(40usize, 30usize), (97, 61), (201, 129)].iter().enumerate() {
for (n, &(w, h)) in [(40usize, 30usize), (97, 61)].iter().enumerate() {
for ch in [1usize, 3] {
let (imgs, wts) = rois(w, h, ch, n as u64 * 17 + ch as u64);
for levels in [1usize, 3, 5] {
+14 -6
View File
@@ -127,9 +127,13 @@ fn halftone_unusual_coordinates_and_params_keep_direct_semantics() {
fn tiled_filters_match_scalar_at_all_depths_with_soft_selection() {
use crate::{FilterParams, apply_tiled};
let bounds = Rect::new(-17, -9, 26, 24);
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
for alpha in [false, true] {
// Every mode/depth pair and both alpha values for each mode and depth.
for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() {
for (di, depth) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() {
for (ai, alpha) in [false, true].into_iter().enumerate() {
if (mi + di) % 2 != ai {
continue;
}
let ctx = Ctx { bounds, mode, alpha };
let src = fixture(bounds, &ctx, 2);
let mut surface = Surface::new(PixelFormat::new(mode, depth, alpha));
@@ -198,14 +202,18 @@ fn cell_filters_match_scalar_models_edges_and_fractional_cells() {
// The cell filters see the mode only as a channel count, CMYK's ink direction (`subtractive`) and the native
// background, so Lab adds nothing to RGB; cells of 100 and 300 are both past every `out`, and the seed has no
// branch (0 and u32::MAX keep the wrapping ends) (#15652).
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Multichannel] {
for alpha in [false, true] {
for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Multichannel].into_iter().enumerate() {
for (ai, alpha) in [false, true].into_iter().enumerate() {
let ctx = Ctx { bounds, mode, alpha };
for pattern in 0..5 {
for halo in [0, 7] {
let src = fixture(bounds.inflate(halo), &ctx, pattern);
for out in [bounds, Rect::new(-23, -15, 37, 31), Rect::new(-7, 2, 18, 13)] {
for cell in [2.0, 3.75, 10.0, 300.0] {
// Retain every mode/alpha pair and all four cell sizes for each mode.
for (ci, cell) in [2.0, 3.75, 10.0, 300.0].into_iter().enumerate() {
if ci % 2 != (mi + ai) % 2 {
continue;
}
for seed in [0, u32::MAX] {
let got = cells::crystallize(&src, out, &ctx, cell, seed).unwrap();
assert_bits(&got, &crystallize_direct(&src, out, &ctx, cell, seed));
+23 -15
View File
@@ -150,6 +150,11 @@ fn read_rgba(src: &Image, ctx: &Ctx, x: i32, y: i32) -> [f32; 4] {
/// Relight `out` of `src`. Identity when `intensity` is 0 (or not finite).
pub(crate) fn relight(src: &Image, out: Rect, ctx: &Ctx, p: Params) -> Vec<f32> {
relight_with_luma_budget(src, out, ctx, p, MAX_LUMA_PIXELS)
}
/// Relight with a bound on the luma field allocated by each band.
fn relight_with_luma_budget(src: &Image, out: Rect, ctx: &Ctx, p: Params, max_luma_pixels: usize) -> Vec<f32> {
let n = src.ch;
if out.is_empty() || n == 0 {
return src.crop(out);
@@ -160,14 +165,14 @@ pub(crate) fn relight(src: &Image, out: Rect, ctx: &Ctx, p: Params) -> Vec<f32>
let sig = sigma(p.softness, ctx.bounds);
let step = step_for_sigma(sig);
let reach = read_radius(sig);
if let Some(band_h) = luma_band_rows(out, reach) {
if let Some(band_h) = luma_band_rows(out, reach, max_luma_pixels) {
return relight_bands(src, out, ctx, p, sig, step, band_h);
}
relight_rect(src, out, ctx, p, sig, step)
}
/// Horizontal strip height so the inflated luma field stays within [`MAX_LUMA_PIXELS`].
fn luma_band_rows(out: Rect, reach: i32) -> Option<i32> {
fn luma_band_rows(out: Rect, reach: i32, max_luma_pixels: usize) -> Option<i32> {
let margin = 2usize.saturating_mul(reach.max(0) as usize);
let yw = (out.width() as usize).saturating_add(margin);
let yh = (out.height() as usize).saturating_add(margin);
@@ -179,10 +184,10 @@ fn luma_band_rows(out: Rect, reach: i32) -> Option<i32> {
Some(_) => return None,
None => usize::MAX,
};
if n <= MAX_LUMA_PIXELS {
if n <= max_luma_pixels {
return None;
}
let max_yh = (MAX_LUMA_PIXELS / yw).max(1);
let max_yh = (max_luma_pixels / yw).max(1);
let inner = max_yh.saturating_sub(margin).max(1).min(i32::MAX as usize) as i32;
if inner >= out.height() as i32 { None } else { Some(inner.max(1)) }
}
@@ -534,10 +539,9 @@ mod tests {
}
#[test]
fn layers_above_8mp_are_relit() {
// 4096×2048 = 8.39 MP. A single full-frame kernel call inflates past 8 MP of luma,
// which used to return the input unchanged. Force one tile so that path is taken.
let (w, h) = (4096, 2048);
fn layers_above_the_luma_budget_are_relit() {
// A small budget exercises the same banding path as an 8 MP luma field.
let (w, h) = (256, 128);
let bounds = Rect::new(0, 0, w, h);
let mut s = Surface::new(PixelFormat::RGBA8);
let bytes: Vec<u8> = (0..h)
@@ -550,15 +554,19 @@ mod tests {
})
.collect();
s.write_interleaved(bounds, &bytes);
let p = relight_p(180.0, 30.0, 90.0, 12.0, 0.0, 25.0);
let area = output_area(&p, s.content_bounds(), bounds, None);
let p = Params { angle: 180.0, elevation: 30.0, intensity: 90.0, ambient: 12.0, warmth: 0.0, softness: 25.0 };
let reach = read_radius(sigma(p.softness, bounds));
assert!(luma_band_rows(bounds, reach, 20_000).is_some());
let src = Image::read_clamped(&s, bounds.inflate(reach), bounds);
let ctx = Ctx { bounds, mode: ColorMode::Rgb, alpha: true };
let before = s.pixel(w / 2, h / 2);
let out = apply_tiled(&s, &p, area, bounds, None, 8192, None);
let after = out.pixel(w / 2, h / 2);
let out = relight_with_luma_budget(&src, bounds, &ctx, p, 20_000);
let pixel = |x: i32, y: i32| &out[((y * w + x) * 4) as usize..][..4];
let after = pixel(w / 2, h / 2);
assert!(after.iter().all(|c| c.is_finite()), "{after:?}");
let d = max_diff(&before, &after);
assert!(d > 1e-4, "8 MP+ layer was left unchanged (max diff {d})");
assert!(max_diff(&s.pixel(8, 8), &out.pixel(8, 8)) > 1e-4);
let d = max_diff(&before, after);
assert!(d > 1e-4, "over-budget layer was left unchanged (max diff {d})");
assert!(max_diff(&s.pixel(8, 8), pixel(8, 8)) > 1e-4);
}
#[test]
+4
View File
@@ -273,6 +273,10 @@ mod tests {
let fmt = PixelFormat::new(mode, depth, true);
for (w, h) in [(512, 512), (900, 240), (2400, 1200)] {
for seed in [0, 3, 7, 18916] {
// One seed exercises the large canvas; all seeds still run at both smaller sizes.
if w == 2400 && seed != 0 {
continue;
}
let px = render(fmt, w, h, seed, (BLACK, WHITE), None);
let v: Vec<f32> = px.chunks_exact(fmt.channels()).map(|p| p[0]).collect();
let n = v.len() as f32;
+5 -5
View File
@@ -297,23 +297,23 @@ fn canvas_edges_repeat_instead_of_fading() {
}
}
/// Two tiles in opposite corners of a 100000 px square: the content bounds are huge but
/// Two tiles in opposite corners of a 20096 px square: the content bounds are huge but
/// almost nothing is stored. Shrinking it to one pixel must neither allocate a window
/// proportional to the scale (#713) nor read the empty middle.
#[test]
fn tiny_target_of_a_huge_sparse_source() {
let mut s = Surface::new(PixelFormat::RGBA32F);
s.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 1.0, 1.0, 1.0]);
s.fill_rect(Rect::new(99_840, 99_840, 100_096, 100_096), &[1.0, 1.0, 1.0, 1.0]);
let k = 1.0 / 100_096.0;
s.fill_rect(Rect::new(19_840, 19_840, 20_096, 20_096), &[1.0, 1.0, 1.0, 1.0]);
let k = 1.0 / 20_096.0;
let o = resize_surface(&s, k, k, Resample::Bicubic);
assert_eq!(o.content_bounds(), Rect::new(0, 0, 1, 1));
let p = o.pixel(0, 0);
// Two 256² tiles out of 100096²: nearly transparent, and white where it isn't.
// Two 256² tiles out of 20096²: nearly transparent, and white where it isn't.
assert!(p[3] >= 0.0 && p[3] < 1e-3 && p.iter().all(|v| v.is_finite()), "{p:?}");
// Squashed to one row but kept wide: the whole height feeds one band of output rows,
// which must not hold a full-height intermediate.
let o = resize_surface(&s, 1000.0 / 100_096.0, k, Resample::Bicubic);
let o = resize_surface(&s, 1000.0 / 20_096.0, k, Resample::Bicubic);
let b = o.content_bounds();
assert!(b.height() == 1 && (1000..=1001).contains(&b.width()), "{b:?}");
assert!(o.pixel(0, 0)[3] > 0.0 && o.pixel(500, 0)[3] == 0.0, "{:?} {:?}", o.pixel(0, 0), o.pixel(500, 0));
+8 -7
View File
@@ -82,16 +82,16 @@ fn quick_selection_workflow_release_comparison() {
#[test]
fn quick_selection_preserves_textures_low_contrast_and_thin_features() {
let (w, h) = (360usize, 280usize);
let (w, h) = (180usize, 140usize);
let canvas = Rect::new(0, 0, w as i32, h as i32);
for kind in 0..6 {
let img = RgbImage::from_fn(w, h, |x, y| {
let inside = if kind == 2 {
(x as f32 - 180.0).hypot(y as f32 - 140.0) < 72.0
(x as f32 - 90.0).hypot(y as f32 - 70.0) < 36.0
} else if kind == 3 {
y > 130 && y < 145
y > 65 && y < 73
} else {
x > 60 && x < 300 && y > 60 && y < 220
x > 30 && x < 150 && y > 30 && y < 110
};
let t = ((x * 23 + y * 19) % 101) as f32 / 100.0;
match kind {
@@ -102,7 +102,7 @@ fn quick_selection_preserves_textures_low_contrast_and_thin_features() {
[0.4, 0.3 + t * 0.1, 0.2]
}
}
1 => [0.4 + x as f32 / 1800.0, 0.3 + y as f32 / 1400.0, t * 0.02],
1 => [0.4 + x as f32 / 900.0, 0.3 + y as f32 / 700.0, t * 0.02],
4 => [t, ((x * 7 + y * 31) % 79) as f32 / 78.0, 0.4],
5 => [0.4; 3],
_ => {
@@ -115,8 +115,9 @@ fn quick_selection_preserves_textures_low_contrast_and_thin_features() {
}
});
let sampler = ImageSampler { img: &img, origin: (0, 0) };
for (points, brush) in [(vec![(180.0, 140.0)], 12.0), (vec![(90.0, 140.0), (270.0, 140.0)], 40.0), (vec![(1.0, 1.0), (160.0, 130.0)], 64.0)] {
for direct_px in [10_000, 300_000] {
for (points, brush) in [(vec![(90.0, 70.0)], 6.0), (vec![(45.0, 70.0), (135.0, 70.0)], 20.0), (vec![(1.0, 1.0), (80.0, 65.0)], 32.0)] {
// Scale the coarse-cut threshold with the canvas area; the second case stays direct.
for direct_px in [2_500, 300_000] {
let tune = quick::Tuning { direct_px, ..quick::Tuning::default() };
let old = quick::quick_select_using::<false>(&sampler, canvas, &points, brush, &tune);
let new = quick::quick_select_using::<true>(&sampler, canvas, &points, brush, &tune);
+7 -3
View File
@@ -183,13 +183,17 @@ fn exact_tiled_selected_outputs_and_cancellation() {
let mut sel = Surface::new(PixelFormat::GRAY8);
sel.fill_rect(area, &[0.4]);
sel.fill_rect(Rect::new(250, 250, 270, 265), &[1.0]);
for depth in SampleType::ALL {
for (di, depth) in SampleType::ALL.into_iter().enumerate() {
let surface = source(bounds, PixelFormat::new(ColorMode::Rgb, depth, true));
for radius in [0.6, 3.0, 10.0] {
for (ri, radius) in [0.6, 3.0, 10.0].into_iter().enumerate() {
let p = crate::FilterParams::UnsharpMask { amount: 150.0, radius, threshold: 8.0 };
for extent in [None, Some(bounds)] {
let expected = apply_reference(&surface, &p, area, bounds, Some(&sel), extent, 256);
for tile in [63, 256, 512] {
// Keep every depth/radius, depth/tile and radius/tile pair, with both extents.
for (ti, tile) in [63, 256, 512].into_iter().enumerate() {
if ti != (di + ri) % 3 {
continue;
}
let actual = crate::apply_tiled(&surface, &p, area, bounds, Some(&sel), tile, extent);
assert_eq!(expected.to_interleaved(bounds), actual.to_interleaved(bounds));
}
+5 -2
View File
@@ -44,8 +44,11 @@ fn swept_blocks_match_the_pixel_search_part(part: u64) {
let repeat = !seen.insert((n, alpha, mode == ColorMode::Cmyk));
for kind in 0..5 {
let src = image(bounds.inflate(20), n, kind);
for (size, depth) in [(2.0, 0.0), (2.0, 255.0), (3.5, 190.0), (8.0, 64.0), (22.0, 255.0), (255.0, 100.0)] {
for flags in (0..8).filter(|f| !repeat || f & 1 != 0) {
for (si, (size, depth)) in [(2.0, 0.0), (2.0, 255.0), (3.5, 190.0), (8.0, 64.0), (22.0, 255.0), (255.0, 100.0)].into_iter().enumerate() {
// For distinct channel layouts each kind and size sees every flag
// combination. Repeated layouts keep one level-based case per pair.
let first = (kind + si) % 8;
for flags in (0..8).filter(|f| (!repeat || f & 1 != 0) && (*f == first || *f == (first + 3) % 8)) {
case += 1;
if !sweep.includes(case) {
continue;
@@ -34,6 +34,7 @@ impl BandRenderer for QueuedDiagnosticsRenderer {
#[test]
fn native_save_refuses_previews_rendered_from_unreadable_scratch() {
photocraft_raster::spill::use_test_volume_space();
let dir = std::env::temp_dir().join(format!("photocraft-automation-scratch-save-{}", std::process::id()));
spill::configure(Some(&dir), 1).unwrap();
let mut doc = Document::new("Scratch", Size::new(512, 256), ColorMode::Rgb, SampleType::U8);
+97
View File
@@ -46,7 +46,70 @@ pub enum BlendMode {
PaintNetColorDodge,
}
/// Parse legacy command names and labels, retaining their case and punctuation tolerance.
pub fn parse_blend(s: &str) -> Option<BlendMode> {
fn normalize(value: &str) -> String {
value.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "")
}
static ALIASES: std::sync::OnceLock<std::collections::HashMap<String, BlendMode>> = std::sync::OnceLock::new();
let aliases = ALIASES.get_or_init(|| {
let mut aliases = std::collections::HashMap::new();
for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) {
aliases.entry(normalize(mode.label())).or_insert(mode);
aliases.entry(normalize(&format!("{mode:?}"))).or_insert(mode);
}
aliases
});
aliases.get(&normalize(s)).copied()
}
impl BlendMode {
/// Stable key used by the Layers panel.
pub fn key(self) -> &'static str {
match self {
Self::PassThrough => "passthrough",
Self::Normal => "normal",
Self::Dissolve => "dissolve",
Self::Darken => "darken",
Self::Multiply => "multiply",
Self::ColorBurn => "colorburn",
Self::LinearBurn => "linearburn",
Self::DarkerColor => "darkercolor",
Self::Lighten => "lighten",
Self::Screen => "screen",
Self::ColorDodge => "colordodge",
Self::LinearDodge => "lineardodgeadd",
Self::LighterColor => "lightercolor",
Self::Overlay => "overlay",
Self::SoftLight => "softlight",
Self::HardLight => "hardlight",
Self::VividLight => "vividlight",
Self::LinearLight => "linearlight",
Self::PinLight => "pinlight",
Self::HardMix => "hardmix",
Self::Difference => "difference",
Self::Exclusion => "exclusion",
Self::Subtract => "subtract",
Self::Divide => "divide",
Self::Hue => "hue",
Self::Saturation => "saturation",
Self::Color => "color",
Self::Luminosity => "luminosity",
Self::Reflect => "reflect",
Self::Glow => "glow",
Self::Negation => "negation",
Self::Xor => "xor",
Self::PaintNetColorBurn => "colorburnpaint.net",
Self::PaintNetColorDodge => "colordodgepaint.net",
}
}
/// Resolve a canonical Layers panel key.
pub fn from_key(key: &str) -> Option<Self> {
static MODES: std::sync::OnceLock<std::collections::HashMap<&'static str, BlendMode>> = std::sync::OnceLock::new();
MODES.get_or_init(|| std::iter::once(Self::PassThrough).chain(Self::layer_modes()).map(|mode| (mode.key(), mode)).collect()).get(key).copied()
}
/// Paint.NET modes without an exact Photoshop equivalent.
pub const PAINT_NET_MODES: [BlendMode; 6] = [Self::Reflect, Self::Glow, Self::Negation, Self::Xor, Self::PaintNetColorBurn, Self::PaintNetColorDodge];
@@ -623,3 +686,37 @@ pub fn composite_atop(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opa
#[cfg(test)]
mod tests;
#[cfg(test)]
mod key_tests {
use super::BlendMode;
#[test]
fn parser_preserves_legacy_names_and_normalization() {
let normalize = |s: &str| s.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "");
let legacy = |s: &str| {
let wanted = normalize(s);
std::iter::once(BlendMode::PassThrough)
.chain(BlendMode::layer_modes())
.find(|mode| normalize(mode.label()) == wanted || normalize(&format!("{mode:?}")) == wanted)
};
for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) {
for name in [mode.label().to_owned(), format!("{mode:?}"), mode.label().to_ascii_uppercase().replace(' ', "_-")] {
assert_eq!(super::parse_blend(&name), legacy(&name), "{name}");
}
}
for name in ["", "not a mode", "color.burn", "é"] {
assert_eq!(super::parse_blend(name), legacy(name), "{name}");
}
}
#[test]
fn canonical_keys_match_legacy_panel_names_and_round_trip() {
for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) {
let old = mode.label().to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "");
assert_eq!(mode.key(), old);
assert_eq!(BlendMode::from_key(&old), Some(mode));
}
assert_eq!(BlendMode::from_key("no-such-mode"), None);
}
}
+2 -1
View File
@@ -1704,7 +1704,8 @@ fn normal_onto_nothing_is_exact() {
};
let mut d = doc(4, 6);
d.layers =
vec![build(&LayerSpec::Group { children: vec![shape, inv], pass_through: false, blend: BlendMode::Normal, opacity: 1.0, fill: 1.0, mask: None })];
vec![build(&LayerSpec::Group { children: vec![shape, inv], pass_through: false, blend: BlendMode::Normal, opacity: 1.0, fill: 1.0, mask: None })]
.into();
assert_matches_reference(&d);
assert_eq!(render1(&d, 0, 0)[..4], [0.0; 4]);
}
+2 -2
View File
@@ -170,10 +170,10 @@ fn a_stroked_shapes_mask_applies_to_fill_and_stroke_together() {
assert!(close4(p, [0.0, 1.0, 0.0, 0.5]), "{p:?}");
// With effects too.
l.effects.items = vec![Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), color: Color::rgb(1.0, 1.0, 1.0) }];
d.layers = vec![l.clone()];
d.layers = vec![l.clone()].into();
let p = px(&d, 12, 20);
assert!(close4(p, [0.0, 1.0, 0.0, 0.5]), "without clipped layers: {p:?}");
d.layers = vec![l, clip];
d.layers = vec![l, clip].into();
let p = px(&d, 12, 20);
assert!(close4(p, [0.0, 1.0, 0.0, 0.5]), "{p:?}");
}
+5 -5
View File
@@ -404,7 +404,7 @@ fn every_blend_mode_matches_reference_on_opaque_pixels() {
let mut top = Layer::raster("t", PixelFormat::RGBA32F);
top.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 2), &source);
top.blend = mode;
d.layers = vec![bottom, top];
d.layers = vec![bottom, top].into();
let got = px(&d, 0, 0);
// A 32-bit document: Add / Divide don't clip at 1 (Divide gives 0.6 / 0.2 = 3 in red).
psblend::HDR.with(|h| h.set(true));
@@ -434,7 +434,7 @@ fn full_coverage_adjustment_keeps_its_result_over_huge_hdr_values() {
dither: false,
source: None,
};
d.layers = vec![base, Layer::new("look", LayerContent::Adjustment(look))];
d.layers = vec![base, Layer::new("look", LayerContent::Adjustment(look))].into();
let got = px(&d, 0, 0);
for c in &got[..3] {
assert!((c - 0.5).abs() < 1e-6, "{v}: {got:?}");
@@ -479,7 +479,7 @@ fn blend_px(depth: SampleType, mode: BlendMode, bottom: [f32; 3], top: [f32; 3])
let mut t = Layer::raster("t", fmt);
t.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, [top[0], top[1], top[2], 1.0]));
t.blend = mode;
d.layers = vec![b, t];
d.layers = vec![b, t].into();
px(&d, 0, 0)
}
@@ -3294,7 +3294,7 @@ fn exposure_scales_32_bit_samples_as_stored() {
let mut d = Document::new("e", Size::new(1, 1), ColorMode::Rgb, depth);
let mut l = Layer::raster("px", fmt);
l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &[0.2, 0.2, 0.2, 1.0]);
d.layers = vec![l, Layer::new("exp", LayerContent::Adjustment(plus_one_stop.clone()))];
d.layers = vec![l, Layer::new("exp", LayerContent::Adjustment(plus_one_stop.clone()))].into();
let got = px(&d, 0, 0)[0];
assert!((got - want).abs() < 2e-3, "{depth:?}: {got}");
}
@@ -3384,7 +3384,7 @@ fn float_adjustments_preserve_hdr_range() {
let mut d = Document::new("HDR", Size::new(1, 1), ColorMode::Rgb, SampleType::F32);
let mut l = Layer::raster("pixels", PixelFormat::RGBA32F);
l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &[4.0, 2.0, 0.5, 0.75]);
d.layers = vec![l, Layer::new("adjustment", LayerContent::Adjustment(adj.clone()))];
d.layers = vec![l, Layer::new("adjustment", LayerContent::Adjustment(adj.clone()))].into();
let got = px(&d, 0, 0);
for (a, b) in got[..3].iter().zip(want) {
assert!((a - b).abs() < 1e-5, "{adj:?}: {got:?} vs {want:?}");
+1
View File
@@ -8,6 +8,7 @@ use std::io::{Read, Seek, SeekFrom, Write};
#[test]
fn failed_effect_build_is_not_reused_after_original_pixels_recover() {
photocraft_raster::spill::use_test_volume_space();
let dir = std::env::temp_dir().join(format!("photocraft-compose-scratch-retry-{}", std::process::id()));
spill::configure(Some(&dir), 1).unwrap();
let mut doc = Document::new("Shadow", Size::new(64, 64), ColorMode::Rgb, SampleType::U8);
+227
View File
@@ -0,0 +1,227 @@
//! The document's layer stack with a lazily built id index.
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::sync::OnceLock;
use crate::{Layer, LayerId, LayerPath};
/// Where a layer sits in the stack.
#[derive(Clone, Debug)]
struct Entry {
path: LayerPath,
parent: Option<LayerId>,
}
/// Id to position for every layer, nested ones included.
#[derive(Debug, Default)]
pub struct LayerIndex {
entries: HashMap<LayerId, Entry>,
serial: u64,
}
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
impl LayerIndex {
fn build(layers: &[Layer]) -> Self {
fn rec(layers: &[Layer], parent: Option<LayerId>, path: &mut LayerPath, out: &mut HashMap<LayerId, Entry>) {
for (i, l) in layers.iter().enumerate() {
path.push(i);
out.entry(l.id).or_insert_with(|| Entry { path: path.clone(), parent });
if let Some(ch) = l.children() {
rec(ch, Some(l.id), path, out);
}
path.pop();
}
}
let mut entries = HashMap::with_capacity(layers.len());
rec(layers, None, &mut Vec::new(), &mut entries);
Self { entries, serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) }
}
/// The layer's path from the root. Paths order layers bottom-to-top as the depth-first walk does.
pub fn path(&self, id: LayerId) -> Option<&[usize]> {
self.entries.get(&id).map(|e| e.path.as_slice())
}
/// The group holding the layer; `None` at the root or for an unknown id.
pub fn parent(&self, id: LayerId) -> Option<LayerId> {
self.entries.get(&id)?.parent
}
/// Nesting depth: 0 at the root.
pub fn depth(&self, id: LayerId) -> Option<usize> {
self.entries.get(&id).map(|e| e.path.len() - 1)
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// A number unique to this build: it differs between two builds, so equal serials mean the
/// same index (tests count rebuilds with it).
pub fn serial(&self) -> u64 {
self.serial
}
}
/// The layer stack, bottom-to-top, with an index from layer id to position built on the first
/// lookup.
///
/// The stack is a public vector that code edits in place, nested groups included, so no mutator
/// method can be the place that drops the index. Every route to a `&mut Layer` or `&mut Vec`
/// goes through `DerefMut`, so the reset lives there: any write drops the index, and the next
/// lookup rebuilds it once. `Clone` starts without an index.
#[derive(Default)]
pub struct LayerTree {
layers: Vec<Layer>,
index: OnceLock<LayerIndex>,
}
impl LayerTree {
/// The id index, built on first use after the last write.
pub fn index(&self) -> &LayerIndex {
self.index.get_or_init(|| LayerIndex::build(&self.layers))
}
}
/// `Vec` methods that callers pass `&document` into (`doc.layers.push(make(&doc))`): as methods
/// on the tree the receiver borrow is two-phase, which it is not through `DerefMut`.
impl LayerTree {
pub fn push(&mut self, layer: Layer) {
self.deref_mut().push(layer);
}
pub fn insert(&mut self, at: usize, layer: Layer) {
self.deref_mut().insert(at, layer);
}
}
impl Deref for LayerTree {
type Target = Vec<Layer>;
fn deref(&self) -> &Vec<Layer> {
&self.layers
}
}
impl DerefMut for LayerTree {
fn deref_mut(&mut self) -> &mut Vec<Layer> {
self.index = OnceLock::new();
&mut self.layers
}
}
impl Clone for LayerTree {
fn clone(&self) -> Self {
Self { layers: self.layers.clone(), index: OnceLock::new() }
}
}
impl PartialEq for LayerTree {
fn eq(&self, other: &Self) -> bool {
self.layers == other.layers
}
}
impl std::fmt::Debug for LayerTree {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.layers.fmt(f)
}
}
impl From<Vec<Layer>> for LayerTree {
fn from(layers: Vec<Layer>) -> Self {
Self { layers, index: OnceLock::new() }
}
}
impl<'a> IntoIterator for &'a LayerTree {
type Item = &'a Layer;
type IntoIter = std::slice::Iter<'a, Layer>;
fn into_iter(self) -> Self::IntoIter {
self.layers.iter()
}
}
impl<'a> IntoIterator for &'a mut LayerTree {
type Item = &'a mut Layer;
type IntoIter = std::slice::IterMut<'a, Layer>;
fn into_iter(self) -> Self::IntoIter {
self.deref_mut().iter_mut()
}
}
impl FromIterator<Layer> for LayerTree {
fn from_iter<I: IntoIterator<Item = Layer>>(iter: I) -> Self {
iter.into_iter().collect::<Vec<_>>().into()
}
}
impl IntoIterator for LayerTree {
type Item = Layer;
type IntoIter = std::vec::IntoIter<Layer>;
fn into_iter(self) -> Self::IntoIter {
self.layers.into_iter()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::PixelFormat;
fn layers(n: usize) -> LayerTree {
(0..n).map(|i| Layer::raster(format!("l{i}"), PixelFormat::RGBA8)).collect()
}
#[test]
fn index_builds_once_per_edit() {
let mut t = layers(200);
let id = t[150].id;
let first = t.index().serial();
for _ in 0..100 {
assert_eq!(t.index().path(id), Some(&[150][..]));
}
assert_eq!(t.index().serial(), first, "lookups reuse the index");
t.push(Layer::raster("new", PixelFormat::RGBA8));
let second = t.index().serial();
assert_ne!(second, first, "an edit rebuilds it");
assert_eq!(t.index().serial(), second);
let _ = &mut t[3];
assert_ne!(t.index().serial(), second, "any mutable access drops it");
}
#[test]
fn clone_after_edit_does_not_reuse_the_index() {
let mut t = layers(5);
let old = t.index().serial();
let new_id = {
t.insert(0, Layer::raster("below", PixelFormat::RGBA8));
t[0].id
};
let c = t.clone();
assert_ne!(c.index().serial(), old);
assert_eq!(c.index().path(new_id), Some(&[0][..]));
assert_eq!(t.index().path(new_id), Some(&[0][..]));
}
#[test]
fn nested_edits_reset_and_paths_follow_walk_order() {
let inner = Layer::raster("in", PixelFormat::RGBA8);
let inner_id = inner.id;
let group = Layer::group("g", vec![inner]);
let group_id = group.id;
let mut t: LayerTree = vec![Layer::raster("a", PixelFormat::RGBA8), group].into();
assert_eq!(t.index().path(inner_id), Some(&[1, 0][..]));
assert_eq!(t.index().parent(inner_id), Some(group_id));
assert_eq!(t.index().depth(inner_id), Some(1));
let before = t.index().serial();
t[1].children_mut().unwrap().insert(0, Layer::raster("x", PixelFormat::RGBA8));
assert_eq!(t.index().path(inner_id), Some(&[1, 1][..]));
assert_ne!(t.index().serial(), before);
}
}
+31 -18
View File
@@ -16,6 +16,7 @@ pub mod comps;
pub mod effects;
pub mod frame;
pub mod import_conversion;
pub mod layer_tree;
pub mod mode;
pub mod pattern;
pub mod slices;
@@ -901,7 +902,7 @@ pub struct Document {
pub depth: SampleType,
pub icc_profile: Option<Arc<Vec<u8>>>,
/// Bottom-to-top.
pub layers: Vec<Layer>,
pub layers: layer_tree::LayerTree,
pub channels: Vec<AlphaChannel>,
pub guides: Guides,
/// The rulers' zero point in document pixels (`[x, y]`), dragged from the ruler corner. The
@@ -1004,7 +1005,7 @@ impl Document {
mode,
depth,
icc_profile: None,
layers: Vec::new(),
layers: Default::default(),
channels: Vec::new(),
guides: Guides::default(),
ruler_origin: [0.0, 0.0],
@@ -1161,18 +1162,7 @@ impl Document {
}
pub fn path_of(&self, id: LayerId) -> Option<LayerPath> {
fn rec(layers: &[Layer], id: LayerId, path: &mut LayerPath) -> bool {
for (i, l) in layers.iter().enumerate() {
path.push(i);
if l.id == id || l.children().is_some_and(|ch| rec(ch, id, path)) {
return true;
}
path.pop();
}
false
}
let mut path = Vec::new();
rec(&self.layers, id, &mut path).then_some(path)
self.layers.index().path(id).map(<[usize]>::to_vec)
}
/// The locks in force on the layer at `path`: its own and those of every group around it,
@@ -1211,10 +1201,7 @@ impl Document {
}
pub fn layer(&self, id: LayerId) -> Option<&Layer> {
fn rec(layers: &[Layer], id: LayerId) -> Option<&Layer> {
layers.iter().find_map(|l| if l.id == id { Some(l) } else { l.children().and_then(|ch| rec(ch, id)) })
}
rec(&self.layers, id)
self.layer_at(self.layers.index().path(id)?)
}
pub fn layer_mut(&mut self, id: LayerId) -> Option<&mut Layer> {
@@ -1394,6 +1381,32 @@ mod tests {
assert_eq!(d.unused_link_group(), Some(3));
}
/// Id lookups share one index per document state: 100 lookups on 200 layers build it once,
/// an edit builds it once more, and a clone built after the edit has its own.
#[test]
fn layer_lookups_share_one_index_per_state() {
let mut d = doc();
for i in 0..199 {
d.layers.push(Layer::raster(format!("l{i}"), PixelFormat::RGBA8));
}
let ids: Vec<LayerId> = d.layers.iter().map(|l| l.id).collect();
let first = d.layers.index().serial();
for i in 0..100 {
let id = ids[i * 2];
assert_eq!(d.layer(id).unwrap().id, id);
assert_eq!(d.path_of(id), Some(vec![i * 2]));
}
assert_eq!(d.layers.index().serial(), first);
assert!(d.shift(ids[10], 1));
assert_eq!(d.path_of(ids[10]), Some(vec![11]));
let second = d.layers.index().serial();
assert_ne!(second, first);
d.layer_mut(ids[3]).unwrap().name = "x".into();
let copy = d.clone();
assert_ne!(copy.layers.index().serial(), d.layers.index().serial());
assert_eq!(copy.layer(ids[3]).unwrap().name, "x");
}
#[test]
fn new_document_has_locked_background() {
let d = doc();
+5 -5
View File
@@ -1,6 +1,6 @@
//! The command registry. Ids follow Photoshop's menu structure (see the parity checklist).
use photocraft_color::{BlendMode, Color, ColorMode, SampleType};
use photocraft_color::{Color, ColorMode, SampleType};
use photocraft_doc::{Adjustment, Document, Fill, Layer, LayerContent, LayerId, LayerMask, Size};
use photocraft_geom::{Rect, TILE_SIZE};
use photocraft_raster::Surface;
@@ -189,13 +189,13 @@ use adjust_params::{adjust_mode, destructive_adjust, doc_mode, new_adjustment};
pub use adjust_params::{adjustment_from_params, adjustment_kind};
pub(crate) use enabled::{always, check_all_unlocked, check_pixels_unlocked, has_paintable, is_mask_target, paint_surface};
use enabled::{can_redo, can_undo, has_doc, has_layer, has_pixel_or_channel, has_selection};
pub use layer_params::blend_from_str;
pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, layer_param, mask_at_depth, mask_new_layer, selection_mask};
pub(crate) use layer_references::{recorded_drop, recorded_layer};
use ops::{arrange, merge_group, move_mask, set_mask, set_mask_and_deselect};
pub(crate) use ops::{layer_copy, translate_layer, translate_layer_wrapped};
use params::{bad, set_clipped};
pub(crate) use params::{check_f32_values, cmyk_param, color_param, int, int_i32, parse_hex, u32_id, u32_id_param};
pub use photocraft_color::blend::parse_blend;
pub fn command_specs() -> &'static [CommandSpec] {
&registry().specs
@@ -726,7 +726,7 @@ fn build() -> Vec<CommandSpec> {
// The Background has no opacity, fill or blend mode: like Photoshop, setting
// one that changes its look turns it into a normal layer ("Layer 0") first.
let num = |k: &str| p.get(k).and_then(Value::as_f64).is_some_and(|v| v < 1.0);
let blends = p.get("blend").and_then(Value::as_str).and_then(blend_from_str).is_some_and(|b| b != photocraft_color::BlendMode::Normal);
let blends = p.get("blend").and_then(Value::as_str).and_then(parse_blend).is_some_and(|b| b != photocraft_color::BlendMode::Normal);
for &id in &ids {
if num("opacity") || num("fill") || blends {
crate::extra_cmds::background_to_layer(doc, id);
@@ -745,7 +745,7 @@ fn build() -> Vec<CommandSpec> {
l.fill_opacity = v;
}
if let Some(v) = p.get("blend").and_then(Value::as_str) {
let b = blend_from_str(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?;
let b = parse_blend(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?;
// Pass Through is a group's mode only, as in Photoshop.
if b == photocraft_color::BlendMode::PassThrough && !l.is_group() {
return Err(bad("layer.setProps", format!("Pass Through applies to groups only; layer {} isn't one", l.id.0)));
@@ -894,7 +894,7 @@ fn build() -> Vec<CommandSpec> {
bg.locks.position = true;
*crate::pixels_mut(&mut bg)? = photocraft_compose::flatten_to_surface(doc, fmt, Some([1.0, 1.0, 1.0]));
*active = Some(bg.id);
doc.layers = vec![bg];
doc.layers = vec![bg].into();
Ok(())
})?;
Ok(Value::Null)
+1 -1
View File
@@ -652,7 +652,7 @@ fn hdr_toning(s: &mut Session, p: &Value) -> Result<Value> {
bg.locks.position = true;
crate::pixels_mut(&mut bg)?.write_region(doc.bounds(), &data);
*active = Some(bg.id);
doc.layers = vec![bg];
doc.layers = vec![bg].into();
doc.selection = None;
Ok(())
})?;
+1 -1
View File
@@ -24,7 +24,7 @@ pub(super) fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: &
None | Some(Value::Null) => BlendMode::Normal,
Some(v) => {
let m = v.as_str().ok_or_else(|| bad("`mode` must be a blend mode name".into()))?;
crate::commands::blend_from_str(m).filter(|b| *b != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{m}`")))?
crate::commands::parse_blend(m).filter(|b| *b != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{m}`")))?
}
};
let clip = match p.get("clipToPrevious") {
+1 -1
View File
@@ -643,7 +643,7 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Result<Option<Document>
let mut one = doc.clone();
one.name = l.name.clone();
one.size = Size::new(r.width(), r.height());
one.layers = vec![group];
one.layers = vec![group].into();
one.channels.clear();
one.selection = None;
one.quick_mask = None;
+1 -1
View File
@@ -892,7 +892,7 @@ fn adjustment_layer_to(id: &str, p: &Value) -> Option<Descriptor> {
None | Some(Value::Null) => None,
Some(v) => {
let label = v.as_str()?;
if crate::commands::blend_from_str(label)? == photocraft_doc::BlendMode::PassThrough {
if crate::commands::parse_blend(label)? == photocraft_doc::BlendMode::PassThrough {
return None;
}
Some(blend_ps(label)?)
+1 -1
View File
@@ -56,7 +56,7 @@ pub(super) fn blend_label(ps: &str) -> Option<&'static str> {
}
pub(super) fn blend_ps(label: &str) -> Option<&'static str> {
crate::commands::blend_from_str(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::blend_from_str(v) == Some(m))).map(|(k, _)| *k)
crate::commands::parse_blend(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::parse_blend(v) == Some(m))).map(|(k, _)| *k)
}
/// Photoshop ↔ PhotoCraft value tables; Photoshop codes compare without their space padding.
+1 -1
View File
@@ -69,7 +69,7 @@ fn background_from_layer(s: &mut Session, p: &Value) -> Result<Value> {
only.clipped = false;
let visible = l.visible;
let fmt = doc.pixel_format();
let rest = std::mem::replace(&mut doc.layers, vec![only]);
let rest = std::mem::replace(&mut doc.layers, vec![only].into());
let pixels = photocraft_compose::flatten_to_surface(doc, fmt, Some([bg[0], bg[1], bg[2]]));
doc.layers = rest;
let mut out = Layer::raster("Background", fmt);
+1 -1
View File
@@ -448,7 +448,7 @@ fn with_blend_mode(mut b: BrushSettings, p: &Value) -> BrushSettings {
} else if p.get("mode").and_then(Value::as_str).is_some_and(|m| m.eq_ignore_ascii_case("behind")) {
b.mode = photocraft_color::BlendMode::Normal;
b.behind = true;
} else if let Some(m) = p.get("mode").and_then(Value::as_str).and_then(crate::commands::blend_from_str) {
} else if let Some(m) = p.get("mode").and_then(Value::as_str).and_then(crate::commands::parse_blend) {
b.mode = m;
b.behind = false;
}
+1 -1
View File
@@ -314,7 +314,7 @@ impl Blending {
match name.to_ascii_lowercase().as_str() {
"add" => Ok(Blending::Add { scale, offset }),
"subtract" => Ok(Blending::Subtract { scale, offset }),
other => match crate::commands::blend_from_str(other) {
other => match crate::commands::parse_blend(other) {
Some(m) if m.is_separable() && !matches!(m, BlendMode::Dissolve | BlendMode::PassThrough) => Ok(Blending::Mode(m)),
_ => Err(format!("unsupported blending `{other}`")),
},
+1 -1
View File
@@ -43,7 +43,7 @@ pub(super) fn merge_spot(s: &mut Session, p: &Value) -> Result<Value> {
sf.prune();
}
let id = bg.id;
doc.layers = vec![bg];
doc.layers = vec![bg].into();
doc.channels.remove(i);
*active = Some(id);
Ok(())
+1 -1
View File
@@ -1259,7 +1259,7 @@ fn split_refuses_an_image_with_more_than_one_layer() {
assert_eq!(s.execute("channel.split", json!({})).unwrap()["documents"].as_array().unwrap().len(), 3);
// A lone group is a layer the split would lose.
let mut s = session();
std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layers = vec![Layer::group("Group 1", vec![])];
std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layers = vec![Layer::group("Group 1", vec![])].into();
assert!(!s.is_enabled("channel.split"));
assert!(s.execute("channel.split", json!({})).is_err());
assert_eq!(s.documents().len(), 1);
+1 -1
View File
@@ -1116,7 +1116,7 @@ fn flatten_for_profile(doc: &mut Document, active: &mut Option<photocraft_doc::L
background.locks.position = true;
*crate::pixels_mut(&mut background)? = surface;
*active = Some(background.id);
doc.layers = vec![background];
doc.layers = vec![background].into();
Ok(())
}
+1 -1
View File
@@ -789,7 +789,7 @@ fn merge_visible(s: &mut Session) -> Result<Value> {
out.push(l);
}
}
doc.layers = out;
doc.layers = out.into();
*active = Some(mid);
Ok(())
})?;
+1 -1
View File
@@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::channel_cmds::Target;
use crate::commands::{CommandSpec, blend_from_str, int, layer_param};
use crate::commands::{CommandSpec, int, layer_param, parse_blend};
use crate::{EngineError, Result, Session};
// ------------------------------------------------------------------ state
+2 -2
View File
@@ -1,5 +1,5 @@
use super::{
BlendMode, Document, EngineError, FadeSource, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or,
BlendMode, Document, EngineError, FadeSource, FadeTarget, Rect, Result, Session, Surface, Value, bad, f32_or, from_rgba_into, json, parse_blend, str_or,
surface_of, surface_of_mut, to_rgba,
};
@@ -103,7 +103,7 @@ fn fade_job(s: &Session, p: &Value) -> Result<FadeJob> {
let cmd = "edit.fade";
let src = s.edit_state.fade.clone().ok_or_else(|| bad(cmd, "nothing to fade"))?;
let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0;
let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?;
let mode = parse_blend(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let prev = before_state(st, &src).ok_or_else(|| bad(cmd, "no previous state"))?;
let before = surface_of(&prev, src.target).cloned().ok_or_else(|| EngineError::Other("the layer or channel did not exist before this step".into()))?;
+1 -1
View File
@@ -147,7 +147,7 @@ fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
let picked = s.tools.picked_cmyk([color[0], color[1], color[2]]);
let mode = match p.get("mode") {
None | Some(Value::Null) => photocraft_color::BlendMode::Normal,
Some(Value::String(m)) => crate::commands::blend_from_str(m)
Some(Value::String(m)) => crate::commands::parse_blend(m)
.filter(|m| *m != photocraft_color::BlendMode::PassThrough)
.ok_or_else(|| EngineError::BadParams { cmd: "edit.stroke".into(), msg: format!("unknown blend mode `{m}`") })?,
Some(v) => return Err(EngineError::BadParams { cmd: "edit.stroke".into(), msg: format!("mode must be a blend mode name, not {v}") }),
+1 -1
View File
@@ -77,7 +77,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&
let mut only = l.clone();
only.visible = true;
only.clipped = false;
one.layers = vec![only];
one.layers = vec![only].into();
if trim {
let mut bounds = Rect::EMPTY;
let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> {
@@ -304,9 +304,9 @@ pub(super) fn load_files_into_stack(s: &mut Session, p: &Value) -> Result<Value>
// "Create Smart Object after Loading Layers": the layers go inside one smart object, ready
// for Layer › Smart Objects › Stack Mode. Like Photoshop, they sit at the top level of the
// contents, with no wrapper group.
let layers = std::mem::take(&mut stack.layers);
let layers = std::mem::take(&mut *stack.layers);
let smart = crate::smart_cmds::layers_to_smart(&stack, &smart_name, layers)?;
stack.layers = vec![smart];
stack.layers = vec![smart].into();
}
let i = s.add_document(stack, None);
if align {
@@ -314,10 +314,10 @@ pub(super) fn load_files_into_stack(s: &mut Session, p: &Value) -> Result<Value>
s.execute("edit.autoAlignLayers", json!({"projection": "auto"}))?;
if smart {
s.edit("Convert to Smart Object", |doc, active| {
let layers = std::mem::take(&mut doc.layers);
let layers = std::mem::take(&mut *doc.layers);
let smart = crate::smart_cmds::layers_to_smart(doc, &smart_name, layers)?;
*active = Some(smart.id);
doc.layers = vec![smart];
doc.layers = vec![smart].into();
Ok(())
})?;
if let Some(st) = s.active_mut() {
+1 -1
View File
@@ -312,7 +312,7 @@ pub(super) fn save_a_copy(s: &mut Session, p: &Value) -> Result<Value> {
// "Layers" unchecked in Save a Copy: write the flattened image.
let fmt = doc.pixel_format();
let px = flattened_checked(&doc, fmt, "file.saveACopy")?;
doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))];
doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))].into();
}
let warnings = save_doc(&doc, &path, SaveOpts::from_params(s, p, "file.saveACopy")?)?;
Ok(json!({"path": path, "warnings": warnings}))
+2 -2
View File
@@ -11,7 +11,7 @@ use photocraft_geom::{Rect, TILE_SIZE};
use photocraft_raster::{Surface, from_rgba_into, to_rgba};
use serde_json::{Value, json};
use crate::commands::{blend_from_str, color_param, layer_param};
use crate::commands::{color_param, layer_param, parse_blend};
use crate::{EngineError, Result, Session};
const CMD: &str = "edit.fill";
@@ -66,7 +66,7 @@ fn contents(p: &Value) -> Result<&str> {
fn mode(p: &Value) -> Result<BlendMode> {
match p.get("mode") {
None | Some(Value::Null) => Ok(BlendMode::Normal),
Some(Value::String(m)) => blend_from_str(m).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown blend mode `{m}`"))),
Some(Value::String(m)) => parse_blend(m).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown blend mode `{m}`"))),
Some(v) => Err(bad(format!("`mode` must be a blend mode name, not {v}"))),
}
}
+2 -2
View File
@@ -17,7 +17,7 @@ use photocraft_doc::{Document, Fill, GradientStyle, Layer, LayerContent, LayerId
use photocraft_geom::Rect;
use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str, check_pixels_unlocked, layer_param};
use crate::commands::{CommandSpec, check_pixels_unlocked, layer_param, parse_blend};
use crate::presets::gradients::{GradientPreset, transparency_param};
use crate::{EngineError, Result, Session};
@@ -300,7 +300,7 @@ pub fn new_layer(s: &Session, doc: &Document, p: &Value) -> Result<Layer> {
let opacity = num(p, "opacity").unwrap_or(100.0).clamp(0.0, 100.0) / 100.0;
let blend = match p.get("mode").and_then(Value::as_str) {
None | Some("") => photocraft_color::BlendMode::Normal,
Some(m) => blend_from_str(m).ok_or_else(|| bad(CMD, format!("unknown blend mode `{m}`")))?,
Some(m) => parse_blend(m).ok_or_else(|| bad(CMD, format!("unknown blend mode `{m}`")))?,
};
let canvas = doc.bounds();
if canvas.is_empty() {
+3 -3
View File
@@ -145,7 +145,7 @@ fn new_snapshot(s: &mut Session, p: &Value) -> Result<Value> {
let one_layer = |doc: &Document, layer: Layer| {
let mut doc = doc.clone();
let id = layer.id;
doc.layers = vec![layer];
doc.layers = vec![layer].into();
(Arc::new(doc), LayerTarget { active: Some(id), selected: vec![id] })
};
let (doc, layers) = match from {
@@ -525,7 +525,7 @@ mod tests {
assert_eq!(st.memory_bytes(), base + flat);
// Room for the document's tiles and four fill tiles.
let cur = tile_bytes(&st.doc);
let fill = tile_bytes(&Document { layers: st.doc.layers[1..].to_vec(), ..(*st.doc).clone() });
let fill = tile_bytes(&Document { layers: st.doc.layers[1..].to_vec().into(), ..(*st.doc).clone() });
assert!(flat <= fill, "the flattened tile is no bigger than a fill's");
let budget = cur + 4 * fill;
for s in [&mut with, &mut without] {
@@ -549,7 +549,7 @@ mod tests {
s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
let st = s.active().unwrap();
// The snapshot's green layer tile, now only in it and the last state.
let shared = tile_bytes(&Document { layers: st.snapshots.last().unwrap().doc.layers[1..].to_vec(), ..(*st.doc).clone() });
let shared = tile_bytes(&Document { layers: st.snapshots.last().unwrap().doc.layers[1..].to_vec().into(), ..(*st.doc).clone() });
let all = st.history.unique_bytes(&st.doc);
let r = s.execute("edit.purge.histories", json!({})).unwrap();
assert_eq!(r["bytes"], json!(all - shared), "the green tile stays with the snapshot");
+1 -1
View File
@@ -1213,7 +1213,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let mut merged = Layer::new(if has_background { "Background" } else { "Layer 1" }, LayerContent::Raster(surf));
merged.locks.transparency = has_background;
merged.locks.position = has_background;
doc.layers = vec![merged];
doc.layers = vec![merged].into();
// A merged-only copy has no original layers for saved comps to restore.
// Don't carry dangling comp state into a single-layer flattened document.
doc.layer_comps.clear();
+6 -4
View File
@@ -798,16 +798,18 @@ fn crop_at_a_small_angle_keeps_the_frame_size_in_every_mode() {
#[test]
fn turned_crop_deleting_pixels_matches_turning_the_whole_canvas() {
use photocraft_color::PixelFormat;
let pixels = || (0..500).flat_map(|y| (0..700).map(move |x| (x, y)));
for depth in [8, 16, 32] {
for angle in [3.0, -7.5, 33.0, 181.0] {
let (w, h) = if depth == 8 && angle == 33.0 { (700, 500) } else { (140, 100) };
let scale = w / 140;
let pixels = || (0..h).flat_map(|y| (0..w).map(move |x| (x, y)));
let mut sessions = [true, false].map(|delete| {
let mut s = Session::new();
s.execute("file.new", json!({"width": 700, "height": 500, "depth": depth, "background": "white"})).unwrap();
s.execute("file.new", json!({"width": w, "height": h, "depth": depth, "background": "white"})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.edit("paint", |doc, active| {
let wave = |x: i32, y: i32, k: i32| ((x * 7 + y * 13 + k * 31) % 97) as f32 / 96.0;
let all = Rect::new(0, 0, 700, 500);
let all = Rect::new(0, 0, w, h);
let rgba: Vec<f32> = pixels().flat_map(|(x, y)| [wave(x, y, 0), wave(x, y, 1), wave(x, y, 2), wave(y, x, 3)]).collect();
let gray: Vec<f32> = pixels().map(|(x, y)| wave(y, x, 4)).collect();
let l = doc.layer_mut(active.unwrap()).unwrap();
@@ -824,7 +826,7 @@ fn turned_crop_deleting_pixels_matches_turning_the_whole_canvas() {
Ok(())
})
.unwrap();
let p = json!({"x": 150, "y": 120, "width": 330, "height": 290, "angle": angle, "deleteCroppedPixels": delete});
let p = json!({"x": 30 * scale, "y": 24 * scale, "width": 66 * scale, "height": 58 * scale, "angle": angle, "deleteCroppedPixels": delete});
s.execute("image.crop", p).unwrap();
s
});
@@ -21,7 +21,7 @@ fn fixture(depth: u8) -> (Session, [LayerId; 4]) {
let outer_id = outer.id;
let other = Layer::raster("Other", doc.pixel_format());
let other_id = other.id;
doc.layers = vec![outer, other];
doc.layers = vec![outer, other].into();
Ok([outer_id, inner_id, leaf_id, other_id])
})
.unwrap();
+3 -3
View File
@@ -525,7 +525,7 @@ fn blending_options(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "layer.layerStyle.blendingOptions";
let id = layer_param(s, p)?;
let blend = match p.get("blend").and_then(Value::as_str) {
Some(b) => Some(crate::commands::blend_from_str(b).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?),
Some(b) => Some(crate::commands::parse_blend(b).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?),
None => None,
};
let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0));
@@ -876,7 +876,7 @@ fn create_layer(s: &mut Session, p: &Value) -> Result<Value> {
let mut tmp = Document::new("fx", doc.size, doc.mode, doc.depth);
tmp.global_light = light;
tmp.patterns = doc.patterns.clone();
tmp.layers = vec![alone];
tmp.layers = vec![alone].into();
let buf = photocraft_compose::render(&tmp, area);
let mut surf = Surface::new(fmt);
let data: Vec<f32> = buf.px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect();
@@ -952,7 +952,7 @@ pub fn layer_document(doc: &Document, id: LayerId) -> Result<Document> {
alone.blend = if alone.is_group() { BlendMode::PassThrough } else { BlendMode::Normal };
alone.clipped = false;
let mut tmp = doc.clone();
tmp.layers = vec![alone];
tmp.layers = vec![alone].into();
tmp.selection = None;
let area = doc.bounds();
let buf = photocraft_compose::render(&tmp, area);
@@ -548,7 +548,7 @@ fn stack_modes_render_from_the_nested_layers() {
let g = Layer::new("stack", LayerContent::Group(photocraft_doc::Group { children: kids, expanded: true, artboard: None, frame_stroke: None }));
let smart = crate::smart_cmds::layer_to_smart(doc, &g)?;
let id = smart.id;
doc.layers = vec![smart];
doc.layers = vec![smart].into();
*active = Some(id);
Ok(())
})
+1 -7
View File
@@ -1,5 +1,5 @@
use super::params::bad;
use super::{BlendMode, Document, EngineError, Layer, LayerId, LayerMask, Result, SampleType, Session, Value};
use super::{Document, EngineError, Layer, LayerId, LayerMask, Result, SampleType, Session, Value};
/// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that
/// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays
@@ -72,12 +72,6 @@ pub(crate) fn layer_param(s: &Session, p: &Value) -> Result<LayerId> {
}
}
pub fn blend_from_str(s: &str) -> Option<BlendMode> {
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "");
let want = norm(s);
std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()).find(|m| norm(m.label()) == want || norm(&format!("{m:?}")) == want)
}
/// The active selection as the mask of a layer being created, or None without a selection.
/// Photoshop masks a new adjustment or fill layer with the selection, so the adjustment acts on
/// the selected area only (#1250). [`mask_new_layer`] then drops the selection (#8801).
@@ -11,7 +11,7 @@ fn fixture(depth: u8) -> (Session, LayerId, LayerId) {
let a = Layer::raster("A", doc.pixel_format());
let b = Layer::group("B", vec![Layer::raster("Child", doc.pixel_format())]);
let ids = (a.id, b.id);
doc.layers = vec![a, b];
doc.layers = vec![a, b].into();
Ok(ids)
})
.unwrap();
+7 -2
View File
@@ -241,7 +241,7 @@ fn single_layer_surface(doc: &mut Document, active: &mut Option<LayerId>, mode:
*surf = pixels;
}
*active = Some(l.id);
doc.layers = vec![l];
doc.layers = vec![l].into();
for ch in doc.channels.iter_mut() {
let f = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false);
ch.surface = ch.surface.convert(PixelFormat { alpha: ch.surface.format().alpha, ..f });
@@ -600,6 +600,11 @@ fn custom_pattern_map(s: &Session, cmd: &str, p: &Value) -> Result<(Vec<f32>, us
}
fn bitmap(s: &mut Session, p: &Value) -> Result<Value> {
bitmap_in_bands(s, p, 0)
}
/// Convert with the requested compositor band height (zero chooses its normal budget).
fn bitmap_in_bands(s: &mut Session, p: &Value, band_rows: i32) -> Result<Value> {
const CMD: &str = "image.mode.bitmap";
let d = s.active().ok_or(EngineError::NoDocument)?;
let input = f64::from(d.doc.resolution_dpi.max(1.0));
@@ -674,7 +679,7 @@ fn bitmap(s: &mut Session, p: &Value) -> Result<Value> {
let n = fmt.channels();
let mut out = Surface::new(fmt);
let (mut gray, mut data) = (Vec::new(), Vec::new());
let _ = photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> std::result::Result<(), std::convert::Infallible> {
let _ = photocraft_compose::render_bands(doc, doc.bounds(), band_rows, |band| -> std::result::Result<(), std::convert::Infallible> {
gray.clear();
gray.extend(band.px.iter().map(|q| {
// Over white, as the flattened image.
+8 -5
View File
@@ -860,13 +860,13 @@ fn bitmap_pixels(d: &Document) -> Vec<f32> {
#[test]
fn bitmap_in_bands_matches_one_full_canvas_conversion() {
// #8477: the composite is converted in bands (32768 px wide: 256 rows each, so 300 rows are
// two). Diffusion carries its error across the band edge, and pattern, halftone and custom
// #8477: 300 rows cross a 256-row compositor band. Diffusion carries its error across the
// band edge, and pattern, halftone and custom
// pattern stay anchored to the image's rows: the result equals one full-canvas conversion.
let (w, h) = (32_768u32, 300u32);
let (w, h) = (64u32, 300u32);
let mut s = session(w, h, 8, "grayscale");
paint(&mut s, |x, y| {
let v = ((x % 509) as f32 / 509.0 * 0.6 + (y as f32 / 300.0) * 0.4).fract();
let v = ((x % 61) as f32 / 61.0 * 0.6 + (y as f32 / 300.0) * 0.4).fract();
[v, v, v, 1.0]
});
add_pattern(&mut s, "Cells", 3, 2, &[10, 200, 90, 250, 150, 40]);
@@ -888,7 +888,7 @@ fn bitmap_in_bands_matches_one_full_canvas_conversion() {
if method == "customPattern" {
p["pattern"] = json!("Cells");
}
s.execute("image.mode.bitmap", p.clone()).unwrap();
bitmap_in_bands(&mut s, &p, 256).unwrap();
let want = match method {
"halftone" => {
let cell = (before.resolution_dpi / 53.0).max(2.0);
@@ -902,6 +902,9 @@ fn bitmap_in_bands_matches_one_full_canvas_conversion() {
};
// Grayscale stores 0/1 the way `from_rgba` turns the old RGBA output into gray.
let want: Vec<f32> = want.iter().map(|g| photocraft_raster::from_rgba(&storage_format(ColorMode::Bitmap), [*g, *g, *g, 1.0])[0]).collect();
if method == "threshold" {
assert!(want.contains(&0.0) && want.contains(&1.0), "the gradient crosses the threshold");
}
let got = bitmap_pixels(doc(&s));
let diff = got.iter().zip(&want).filter(|(a, b)| (**a - **b).abs() > 1e-6).count();
assert_eq!(diff, 0, "{method}: {diff} of {} pixels differ", got.len());
+1 -1
View File
@@ -246,7 +246,7 @@ pub(crate) fn convert_from(s: &mut Session, mode: ColorMode, _p: &Value) -> Resu
bg.locks.transparency = true;
bg.locks.position = true;
*active = Some(bg.id);
doc.layers = vec![bg];
doc.layers = vec![bg].into();
doc.channels = others;
Ok(if reinterpret { "channels" } else { "appearance" })
})?;
+1 -1
View File
@@ -246,7 +246,7 @@ pub(super) fn merge_group(s: &mut Session, id: LayerId) -> Result<Value> {
solo.blend = photocraft_doc::BlendMode::Normal;
solo.clipped = false;
let mut tmp = doc.clone();
tmp.layers = vec![solo];
tmp.layers = vec![solo].into();
let mut merged = Layer::new(group.name.clone(), LayerContent::Raster(pixels::composite_layers_uncropped(&tmp, fmt)));
merged.id = group.id;
merged.opacity = group.opacity;
+3 -3
View File
@@ -3,7 +3,7 @@
use photocraft_algo::paint::{FillMode, GradientShape, bucket_fill_inks, bucket_fill_region_inks, paint_gradient};
use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str};
use crate::commands::{CommandSpec, parse_blend};
use crate::presets::gradients;
use crate::{EngineError, Result, Session};
@@ -47,7 +47,7 @@ fn fill_mode(p: &Value) -> Result<FillMode> {
match p.get("mode") {
None | Some(Value::Null) => Ok(FillMode::Blend(photocraft_color::BlendMode::Normal)),
Some(Value::String(m)) if m.eq_ignore_ascii_case("clear") => Ok(FillMode::Clear),
Some(Value::String(m)) => blend_from_str(m)
Some(Value::String(m)) => parse_blend(m)
.filter(|m| *m != photocraft_color::BlendMode::PassThrough)
.map(FillMode::Blend)
.ok_or_else(|| bad(format!("unknown blend mode `{m}`"))),
@@ -186,7 +186,7 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
};
let reverse = b(p, "reverse", false);
let opacity = opacity(p, "paint.gradient")?;
let blend = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(photocraft_color::BlendMode::Normal);
let blend = p.get("mode").and_then(Value::as_str).and_then(parse_blend).unwrap_or(photocraft_color::BlendMode::Normal);
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("Gradient", |doc, _| {
+18 -8
View File
@@ -325,6 +325,12 @@ pub fn default_name(s: &Session) -> String {
const MAX_DEFINE_EDGE: u32 = 8000;
fn define(s: &mut Session, p: &Value) -> Result<Value> {
let sample = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format().sample;
define_with_max_pixels(s, p, photocraft_doc::pattern::max_paint_pixels(sample))
}
/// Define a pattern with a bound on its pixel count.
fn define_with_max_pixels(s: &mut Session, p: &Value, max_px: u64) -> Result<Value> {
let cmd = "edit.definePattern";
let st = s.active().ok_or(EngineError::NoDocument)?;
let doc = &st.doc;
@@ -345,7 +351,6 @@ fn define(s: &mut Session, p: &Value) -> Result<Value> {
// A pattern the compositor could not hold would define but paint nothing: 8 bits go to the
// edge limit, 16-bit documents to 33,554,432 px in all, float to 16,777,216 (4096 × 4096).
let sample = doc.pixel_format().sample;
let max_px = photocraft_doc::pattern::max_paint_pixels(sample);
if u64::from(r.width()) * u64::from(r.height()) > max_px {
return Err(bad(cmd, format!("patterns in a {}-bit document are limited to {max_px} px in all", sample.bytes() * 8)));
}
@@ -762,17 +767,22 @@ mod tests {
assert!(e.contains("16-bit") && e.contains("33554432"), "{e}");
}
/// A pattern of the largest area Define Pattern accepts at 8 bits is paintable: held at 4
/// bytes a pixel, 256 MB, as the compositor's cap allows, and it renders.
/// A pattern at the area limit is paintable and renders; production permits 8000×8000 at 8 bits.
#[test]
fn an_8000_by_8000_pattern_is_defined_and_paints() {
fn a_pattern_at_the_area_limit_is_defined_and_paints() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8000, "height": 8000, "depth": 8})).unwrap();
assert_eq!(MAX_DEFINE_EDGE, 8000);
assert!(photocraft_doc::pattern::max_paint_pixels(SampleType::U8) >= 8000 * 8000);
assert_eq!(photocraft_doc::pattern::working_bytes_for(8000 * 8000, SampleType::U8), 8000 * 8000 * 4);
let (side, max_px) = (80, 80 * 80);
s.execute("file.new", json!({"width": side, "height": side, "depth": 8})).unwrap();
s.execute("edit.fill", json!({"color": "#336699"})).unwrap();
s.execute("edit.definePattern", json!({"name": "Largest"})).unwrap();
assert!(define_with_max_pixels(&mut s, &json!({"name": "Too large"}), max_px - 1).is_err());
define_with_max_pixels(&mut s, &json!({"name": "Largest"}), max_px).unwrap();
let p = s.patterns.items.iter().find(|p| p.name == "Largest").unwrap();
assert_eq!((p.width, p.height), (8000, 8000));
assert!(p.is_paintable() && p.working_bytes() == 256_000_000);
assert_eq!((p.width, p.height), (side, side));
// A small pattern uses the expanded float representation, unlike the largest 8-bit one.
assert!(p.is_paintable() && p.working_bytes() == max_px * 16);
s.execute("file.new", json!({"width": 40, "height": 30, "depth": 8})).unwrap();
s.execute("layer.newFillLayer.pattern", json!({"pattern": "Largest"})).unwrap();
let [r, g, b, a] = pixel(&s, 5, 5);
@@ -64,7 +64,7 @@ fn bake_one(s: &mut Session, id: LayerId, key: &str) -> Result<bool> {
if !area.is_empty() {
// Render the layer on its own with the document's settings (mode, depth, global
// light, patterns), then put the real stack back.
let stack = std::mem::replace(&mut doc.layers, vec![alone]);
let stack = std::mem::replace(&mut doc.layers, vec![alone].into());
let buf = photocraft_compose::render(doc, area);
doc.layers = stack;
let n = fmt.channels();
+4 -2
View File
@@ -22,7 +22,7 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba};
use rayon::prelude::*;
use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str};
use crate::commands::{CommandSpec, parse_blend};
use crate::{EngineError, Result, Session};
mod art_history;
@@ -35,7 +35,9 @@ pub use pattern_stamp::{
};
mod periodic;
mod remove;
pub use content_aware_move::{ContentAwarePreview, preview as content_aware_move_preview};
pub use content_aware_move::{
ContentAwarePreview, preview as content_aware_move_preview, preview_with_pixel_budget as content_aware_move_preview_with_pixel_budget,
};
pub use patch::preview as patch_preview;
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+2 -2
View File
@@ -3,7 +3,7 @@ use super::heal::history_source;
use super::sampling::{SampleLayers, sample_layers};
use super::{
BlendMode, BrushSettings, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Stroke, StrokePoint, Surface, Value,
alpha_index, apply_coverage, bad, blend_from_str, coverage, damage_json, flag, has_pixel_layer, json, parse_brush, pattern_stamp, periodic, point,
alpha_index, apply_coverage, bad, coverage, damage_json, flag, has_pixel_layer, json, parse_blend, parse_brush, pattern_stamp, periodic, point,
reject_huge_stroke, run_stroke, to_rgba,
};
@@ -212,7 +212,7 @@ pub(super) fn clone_result(dmg: Rect, off: (i32, i32), aligned: bool, p: &Value,
pub(super) fn blend_param(p: &Value, cmd: &str) -> Result<BlendMode> {
match p.get("mode").and_then(Value::as_str) {
None => Ok(BlendMode::Normal),
Some(m) => blend_from_str(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))),
Some(m) => parse_blend(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))),
}
}
@@ -696,12 +696,18 @@ impl ContentAwarePreview {
/// Prepare the preview of `paint.contentAwareMove` with params `p` on the active document. Errors
/// as the command does (bad params, nothing to move, a selection larger than the command takes).
pub fn preview(s: &Session, p: &Value) -> Result<ContentAwarePreview> {
preview_with_pixel_budget(s, p, PREVIEW_MAX_PIXELS)
}
/// Prepare a preview with a bound on the number of pixels solved at full resolution.
pub fn preview_with_pixel_budget(s: &Session, p: &Value, max_pixels: u64) -> Result<ContentAwarePreview> {
let captured = crate::channel_cmds::inject_target(s, CMD, p.clone());
let p = &captured;
let plan = plan(s, p, PREVIEW_MARGIN)?;
let px = |r: Rect| u64::from(r.width()) * u64::from(r.height());
let pixels = px(plan.area).max(px(plan.dest));
let scale = if pixels > PREVIEW_MAX_PIXELS { (PREVIEW_MAX_PIXELS as f64 / pixels as f64).sqrt() } else { 1.0 };
let max_pixels = max_pixels.max(1);
let scale = if pixels > max_pixels { (max_pixels as f64 / pixels as f64).sqrt() } else { 1.0 };
let d = s.active().ok_or(EngineError::NoDocument)?;
Ok(ContentAwarePreview { colors: crate::color_channels::target(s, p)?, doc: d.doc.clone(), plan, params: p.clone(), scale })
}
+3 -3
View File
@@ -1,8 +1,8 @@
use super::sampling::{AllLayers, sample_all_layers};
use super::{
BlendMode, BrushSettings, Document, EngineError, Footprint, IndexedParallelIterator, LayerId, ParallelIterator, ParallelSliceMut, PixelFormat, Rect,
Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, blend_from_str, damage_json,
dodge_burn, flag, from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_brush, run_stroke, sponge, string, to_rgba,
Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, damage_json, dodge_burn, flag,
from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_blend, parse_brush, run_stroke, sponge, string, to_rgba,
};
// ---------------------------------------------------------------------------------------------
@@ -206,7 +206,7 @@ pub(super) enum DabTool {
fn smudge_mode(p: &Value, cmd: &str) -> Result<BlendMode> {
use BlendMode::{Color, Darken, Hue, Lighten, Luminosity, Normal, Saturation};
let Some(v) = p.get("mode") else { return Ok(Normal) };
let named = v.as_str().and_then(blend_from_str).filter(|m| matches!(m, Normal | Darken | Lighten | Hue | Saturation | Color | Luminosity));
let named = v.as_str().and_then(parse_blend).filter(|m| matches!(m, Normal | Darken | Lighten | Hue | Saturation | Color | Luminosity));
named.ok_or_else(|| {
let given = v.as_str().map_or_else(|| v.to_string(), str::to_owned);
bad(cmd, format!("unknown mode `{given}` (normal|darken|lighten|hue|saturation|color|luminosity)"))
+16 -12
View File
@@ -1650,10 +1650,11 @@ fn large_move(depth: u64) -> Session {
}
#[test]
fn content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths() {
fn content_aware_move_previews_large_selections_coarse_then_exact() {
use crate::jobs::JobCtx;
let p = json!({"offset": [250, 60]});
for depth in DEPTHS {
// The small move test covers all depths; the preview sequence needs one.
for depth in [8] {
let mut s = large_move(depth);
let before = s.active().unwrap().revision;
let job = content_aware_move_preview(&s, &p).unwrap();
@@ -1684,9 +1685,6 @@ fn content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths(
let fine = job.refine().unwrap();
assert!(!fine.is_coarse() && fine.refine().is_none());
assert!(matches!(fine.run(&ctx), Err(EngineError::Cancelled)), "depth {depth}");
if depth != 8 {
continue;
}
// The refined preview is the command's result, bit for bit.
let (exact, _) = fine.run(&JobCtx::new()).unwrap();
assert_eq!(s.active().unwrap().revision, before);
@@ -1700,15 +1698,21 @@ fn content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths(
#[test]
fn content_aware_move_coarse_preview_handles_transform_extend_and_limits() {
use crate::jobs::JobCtx;
let s = large_move(8);
let mut s = session(128, 64, 8, "rgb");
paint_layer(&mut s, with_object(20, 26));
s.execute("select.rect", json!({"x": 16, "y": 22, "width": 20, "height": 20})).unwrap();
let px = |d: &Document, x, y| d.layers[0].surface().unwrap().rgba(x, y);
// Transform On Drop: turned 90° about the selection's centre (210, 160), then moved; the
// object sits at the centre, so it lands at (460, 220) either way.
let (turned, _) = content_aware_move_preview(&s, &json!({"offset": [250, 60], "rotate": 90})).unwrap().run(&JobCtx::new()).unwrap();
assert!(is_object(px(&turned, 460, 220)) && !is_object(px(&turned, 210, 160)));
// A 400-pixel selection is just over the preview budget. It turns about its centre and moves.
let preview = |p: &Value| content_aware_move::preview_with_pixel_budget(&s, p, 399);
let job = preview(&json!({"offset": [70, 0], "rotate": 90})).unwrap();
assert!(job.is_coarse());
let (turned, _) = job.run(&JobCtx::new()).unwrap();
assert!(is_object(px(&turned, 96, 32)) && !is_object(px(&turned, 26, 32)));
// Extend keeps the original.
let (extended, _) = content_aware_move_preview(&s, &json!({"offset": [250, 60], "mode": "extend"})).unwrap().run(&JobCtx::new()).unwrap();
assert!(is_object(px(&extended, 460, 220)) && is_object(px(&extended, 210, 160)));
let job = preview(&json!({"offset": [70, 0], "mode": "extend"})).unwrap();
assert!(job.is_coarse());
let (extended, _) = job.run(&JobCtx::new()).unwrap();
assert!(is_object(px(&extended, 96, 32)) && is_object(px(&extended, 26, 32)));
// Off the canvas, or past the command's own limit, is still an error.
assert!(content_aware_move_preview(&s, &json!({"offset": [400, 0]})).is_err());
let mut big = session(5000, 4000, 8, "rgb");
+1 -1
View File
@@ -158,7 +158,7 @@ fn sampled_document(doc: &Document, active: Option<LayerId>, which: SampleLayers
layer.fill_opacity = 1.0;
layer.blend = photocraft_color::BlendMode::Normal;
let mut solo = doc.clone();
solo.layers = vec![layer];
solo.layers = vec![layer].into();
return Some(Cow::Owned(solo));
}
_ => {}
+1 -1
View File
@@ -34,7 +34,7 @@ use photocraft_raster::Surface;
use serde_json::{Value, json};
use stack_cache::{Stage, StageKey};
use crate::commands::{CommandSpec, blend_from_str, layer_param};
use crate::commands::{CommandSpec, layer_param, parse_blend};
use crate::jobs::JobCtx;
use crate::{EngineError, Result, Session};
+3 -3
View File
@@ -1,8 +1,8 @@
use super::rendering::{refresh_or_fail, refresh_or_fail_in};
use super::source::source_bytes;
use super::{
BlendMode, Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, SmartObject, Surface, Value, bad, blend_from_str, json,
layer_param, other,
BlendMode, Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, SmartObject, Surface, Value, bad, json, layer_param, other,
parse_blend,
};
pub(super) fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> {
@@ -241,7 +241,7 @@ pub(super) fn set_filter_params(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn blending_options(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "layer.smartFilter.blendingOptions";
let blend = match p.get("blend").and_then(Value::as_str) {
Some(b) => Some(blend_from_str(b).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?),
Some(b) => Some(parse_blend(b).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?),
None => None,
};
let opacity = p.get("opacity").and_then(Value::as_f64).map(|o| if o > 1.0 { o / 100.0 } else { o } as f32);
+1 -1
View File
@@ -236,7 +236,7 @@ pub fn layers_to_smart(doc: &Document, name: &str, layers: Vec<Layer>) -> Result
}
let has_fx = layers.iter().any(|l| any_layer(l, &|x| x.effects.enabled && !x.effects.items.is_empty()));
let region = layers.iter().map(|l| subtree_bounds(l, canvas)).fold(canvas, |a, b| a.union(&b)).inflate(if has_fx { 256 } else { 0 });
sub.layers = layers;
sub.layers = layers.into();
let buf = photocraft_compose::render(&sub, region);
let w = region.width() as usize;
+1 -1
View File
@@ -285,7 +285,7 @@ fn convert_source(src: &Document, fmt: PixelFormat, raster: impl FnOnce(PixelFor
}
let mut doc = Document::new(src.name.clone(), src.size, src.mode, src.depth);
doc.icc_profile = src.icc_profile.clone();
doc.layers = vec![Layer::new("source", LayerContent::Raster(raster(src.pixel_format())))];
doc.layers = vec![Layer::new("source", LayerContent::Raster(raster(src.pixel_format())))].into();
if gray {
let gray_profile = crate::color_cmds::working_profile(ColorMode::Grayscale);
crate::color_cmds::convert_document(&mut doc, &gray_profile, craft_cms::Intent::RelativeColorimetric, true)?;
@@ -45,7 +45,7 @@ fn selected_pixels_become_one_editable_smart_object_in_every_mode_and_depth() {
let mut hidden = pixel(&doc, "Hidden", Rect::new(50, 40, 58, 44), [0.2, 0.9, 0.3, 1.0]);
hidden.visible = false;
let ids = [a.id, b.id, hidden.id];
doc.layers = vec![a, b, hidden];
doc.layers = vec![a, b, hidden].into();
let mut selection = Surface::new(PixelFormat::GRAY8);
selection.fill_rect(Rect::new(0, 0, 12, 12), &[0.5]);
doc.selection = Some(selection);
@@ -99,7 +99,7 @@ fn selected_group_and_descendant_are_embedded_once() {
let group_id = group.id;
let b = pixel(&doc, "Outside", Rect::new(16, 0, 32, 16), [0.0, 0.0, 1.0, 1.0]);
let b_id = b.id;
doc.layers = vec![group, b];
doc.layers = vec![group, b].into();
let mut s = selected_session(doc, &[group_id, a_id, b_id]);
convert(&mut s);
assert_eq!(s.active().unwrap().doc.layers.len(), 1);
@@ -120,7 +120,7 @@ fn mixed_parent_selection_keeps_unselected_siblings_and_uses_the_top_selected_pa
let lower = Layer::group("Lower parent", vec![a, keep_a.clone()]);
let upper = Layer::group("Upper parent", vec![b, keep_b.clone()]);
let (lower_id, upper_id) = (lower.id, upper.id);
doc.layers = vec![lower, upper];
doc.layers = vec![lower, upper].into();
let original = doc.clone();
let mut s = selected_session(doc, &[b_id, a_id]);
let before = flat(&s);
@@ -144,7 +144,7 @@ fn explicit_layer_converts_only_that_layer_despite_multi_selection() {
let a = pixel(&doc, "A", Rect::new(0, 0, 8, 8), [1.0, 0.0, 0.0, 1.0]);
let b = pixel(&doc, "B", Rect::new(8, 0, 16, 8), [0.0, 0.0, 1.0, 1.0]);
let (a_id, b_id) = (a.id, b.id);
doc.layers = vec![a, b.clone()];
doc.layers = vec![a, b.clone()].into();
let mut s = selected_session(doc, &[a_id, b_id]);
s.execute("layer.smartObjects.convertToSmartObject", json!({"layer": a_id.0})).unwrap();
assert_eq!(s.active().unwrap().doc.layers.len(), 2);
@@ -160,7 +160,7 @@ fn combined_contents_survive_native_and_psd_save_open() {
let a = pixel(&doc, "Bottom", Rect::new(-2, 4, 20, 20), [1.0, 0.0, 0.0, 1.0]);
let b = pixel(&doc, "Top", Rect::new(10, 8, 24, 24), [0.0, 0.0, 1.0, 1.0]);
let ids = [a.id, b.id];
doc.layers = vec![a, b];
doc.layers = vec![a, b].into();
let mut s = selected_session(doc, &ids);
let id = LayerId(convert(&mut s));
let original = s.active().unwrap().doc.clone();
@@ -189,7 +189,7 @@ fn selected_ancestor_in_another_parent_cannot_remove_the_new_smart_object() {
let lower = Layer::group("Selected parent", vec![a]);
let upper = Layer::group("Unselected parent", vec![b, keep]);
let (lower_id, upper_id) = (lower.id, upper.id);
doc.layers = vec![lower, upper];
doc.layers = vec![lower, upper].into();
let mut s = selected_session(doc, &[lower_id, a_id, b_id]);
let so = LayerId(convert(&mut s));
let outer = &s.active().unwrap().doc;
@@ -210,7 +210,7 @@ fn an_all_hidden_selection_is_rejected_without_changing_document_selection_or_hi
a.visible = false;
b.visible = false;
let ids = [a.id, b.id];
doc.layers = vec![a, b];
doc.layers = vec![a, b].into();
let original = doc.clone();
let mut s = selected_session(doc, &ids);
let err = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap_err();
@@ -4,7 +4,7 @@ use crate::cmd::smart_cmds::source::{flattened_source, source_surface_from_buffe
/// A source document of `mode`/`depth` with a textured, partly transparent block on a layer.
fn source(mode: ColorMode, depth: SampleType) -> Document {
let mut doc = Document::new("source", Size::new(W as u32, H as u32), mode, depth);
doc.layers = vec![Layer::new("block", LayerContent::Raster(block(&doc.pixel_format(), Rect::new(4, 3, 50, 40))))];
doc.layers = vec![Layer::new("block", LayerContent::Raster(block(&doc.pixel_format(), Rect::new(4, 3, 50, 40))))].into();
doc
}
@@ -127,7 +127,7 @@ fn effects_across_block_edges_match() {
let mut mask = LayerMask::reveal_all();
mask.surface.fill_rect(Rect::new(0, 240, width as i32, 270), &[0.3]);
base.mask = Some(mask);
doc.layers = vec![base];
doc.layers = vec![base].into();
same(&format!("blocks {width} {depth:?}"), &doc, fmt);
}
}
@@ -173,7 +173,7 @@ fn svg_smart_render_cache_tracks_destination_profile_and_transform() {
assert!(warnings.is_empty());
assert_eq!(reported.unwrap(), warped, "warning-bearing warp parity");
assert!((warped.pixel(10, 8)[0] - corrected.pixel(3, 3)[0]).abs() < 0.01, "warp must keep corrected colours");
linear.layers = vec![Layer::new("Saved SVG", LayerContent::Smart(smart.clone()))];
linear.layers = vec![Layer::new("Saved SVG", LayerContent::Smart(smart.clone()))].into();
let saved = encode_source(&linear).unwrap();
let reopened = decode_source("saved.pcraft", &saved).unwrap();
let LayerContent::Smart(restored) = &reopened.layers[0].content else { panic!("smart object lost on save") };
+1 -1
View File
@@ -33,7 +33,7 @@ fn contents(s: &Session, doc: &Document, sm: &SmartObject, intent: Intent, bpc:
crate::image_cmds::convert_layers_depth(&mut src.layers, doc.depth);
}
let background_id = src.background().map(|l| l.id);
let mut layers = std::mem::take(&mut src.layers);
let mut layers = std::mem::take(&mut *src.layers);
for l in &mut layers {
if Some(l.id) == background_id {
l.name = "Layer 0".into();
+1 -1
View File
@@ -130,7 +130,7 @@ fn stamp_down(s: &mut Session, p: &Value) -> Result<Value> {
let mut tmp = doc.clone();
let mut base = lower.clone();
base.visible = true;
tmp.layers = vec![base, upper];
tmp.layers = vec![base, upper].into();
let fmt = doc.pixel_format();
let fmt = if lower.locks.transparency { fmt } else { PixelFormat::new(fmt.mode, fmt.sample, true) };
let surf = photocraft_compose::flatten_to_surface(&tmp, fmt, None);
+2 -2
View File
@@ -217,11 +217,11 @@ pub(super) fn paste(s: &mut Session, p: &Value, mode: Mode) -> Result<Value> {
copies.layers = if mode == Mode::Shape {
let layer = shape(&copies)?;
shape_budget(layer, &destination, dx, dy)?;
vec![layer.duplicate()]
vec![layer.duplicate()].into()
} else {
let image = crate::smart_cmds::svg_source_image(&bytes, PixelFormat::new(ColorMode::Rgb, SampleType::F32, true), 1.0)?;
copies.depth = SampleType::F32;
vec![Layer::new("Pasted SVG", LayerContent::Raster((*image.surface).clone()))]
vec![Layer::new("Pasted SVG", LayerContent::Raster((*image.surface).clone()))].into()
};
crate::layer_copy_cmds::adapt_copies(s, &mut copies, &destination)?;
crate::layer_copy_cmds::translate_copies(&mut copies, &destination, dx, dy);
+1 -1
View File
@@ -26,7 +26,7 @@ use photocraft_geom::{Affine, Point, Rect};
use photocraft_vector as vector;
use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str};
use crate::commands::{CommandSpec, parse_blend};
use crate::{EngineError, Result, Session};
/// Keys PSD uses for a shape layer's vector data; dropped when a shape is rasterized.
+2 -2
View File
@@ -2,7 +2,7 @@ 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,
blend_from_str, json, sel, vector,
json, parse_blend, sel, vector,
};
// ---------------------------------------------------------------------------
@@ -444,7 +444,7 @@ pub(super) fn path_fill(s: &mut Session, p: &Value) -> Result<Value> {
let rgb = c.to_rgb();
let src = [rgb[0], rgb[1], rgb[2], c.alpha];
let opacity = (f64p(p, "opacity").unwrap_or(100.0) / 100.0).clamp(0.0, 1.0) as f32;
let mode = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(BlendMode::Normal);
let mode = p.get("mode").and_then(Value::as_str).and_then(parse_blend).unwrap_or(BlendMode::Normal);
let feather = f64p(p, "feather").unwrap_or(0.0) as f32;
let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true);
let id = layer_id(s, p)?;
+2 -2
View File
@@ -881,7 +881,7 @@ fn image_assets_keep_full_artboards() {
let board =
photocraft_doc::Artboard { rect: Rect::new(4, 6, 44, 36), background: photocraft_doc::ArtboardBackground::Transparent, preset: String::new() };
let group = photocraft_doc::Group { children: vec![logo], expanded: true, artboard: Some(board), frame_stroke: None };
doc.layers = vec![Layer::new("board.png", LayerContent::Group(group))];
doc.layers = vec![Layer::new("board.png", LayerContent::Group(group))].into();
Ok(())
})
.unwrap();
@@ -920,7 +920,7 @@ fn image_assets_refuse_empty_artboards() {
};
let empty = photocraft_doc::Group { children: vec![], expanded: true, artboard: Some(board(0)), frame_stroke: None };
let off = photocraft_doc::Group { children: vec![outside], expanded: true, artboard: Some(board(24)), frame_stroke: None };
doc.layers = vec![Layer::new("empty.png", LayerContent::Group(empty)), Layer::new("off.png", LayerContent::Group(off))];
doc.layers = vec![Layer::new("empty.png", LayerContent::Group(empty)), Layer::new("off.png", LayerContent::Group(off))].into();
Ok(())
})
.unwrap();
+8 -3
View File
@@ -263,8 +263,8 @@ mod tests {
space: ToneSpace::Lab,
},
];
for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
for (mi, mode) in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() {
for (si, sample) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() {
let fmt = PixelFormat::new(mode, sample, true);
let mut source = Surface::with_default(fmt, &vec![0.3; fmt.channels()]);
// 256 x 256 is exactly the U16 table's area threshold (`use_table`), so the table path still runs (#15652).
@@ -281,7 +281,12 @@ mod tests {
let mut holes = Surface::with_default(mask.format(), &[0.63]);
holes.fill_rect(Rect::from_xywh(2, 8, 7, 5), &[0.0]);
let colors = ColorChannels::from_indices([0, mode.color_channels() - 1], mode.color_channels()).unwrap();
for selection in [None, Some(&mask), Some(&holes)] {
// Every mode/sample, mode/selection and sample/selection pair remains. RGB/U16
// also needs no selection: the sparse mask alone is below the table threshold.
for (ti, selection) in [None, Some(&mask), Some(&holes)].into_iter().enumerate() {
if ti != (mi + si) % 3 && !(mode == ColorMode::Rgb && sample == SampleType::U16 && selection.is_none()) {
continue;
}
for adjustment in &adjustments {
let mut expected = source.clone();
let mut actual = source.clone();
+64 -2
View File
@@ -322,9 +322,71 @@ pub struct CopiedStyle {
pub const PRECHECKED: &[&str] = &["layer.new.layer", "layer.new.group", "layer.new.groupFromLayers", "layer.new.layerFromBackground"];
/// The selected layers of `doc` whose active layer is `active` and whose selection set is `selected`, in bottom-to-top
/// order ([`DocState::selected_layers`]), for a reader that holds the document without its editing state.
/// order ([`DocState::selected_layers`]), taken from the document's layer index rather than a walk, for a reader that holds the document without its editing state.
pub fn selected_in(doc: &Document, active: Option<LayerId>, selected: &[LayerId]) -> Vec<LayerId> {
let Some(active) = active else { return Vec::new() };
let set: &[LayerId] = if selected.contains(&active) { selected } else { std::slice::from_ref(&active) };
doc.walk().into_iter().map(|(_, _, l)| l.id).filter(|id| set.contains(id)).collect()
// Paths from the document's layer index order layers as the walk does (depth-first, bottom-to-top).
let index = doc.layers.index();
let mut ids: Vec<LayerId> = set.iter().copied().filter(|id| index.path(*id).is_some()).collect();
ids.sort_unstable_by(|a, b| index.path(*a).cmp(&index.path(*b)));
ids.dedup();
ids
}
#[cfg(test)]
mod selected_tests {
use super::selected_in;
use photocraft_doc::{ColorMode, Document, Layer, LayerId, PixelFormat, SampleType, Size};
fn raster(name: &str) -> Layer {
Layer::raster(name, PixelFormat::RGBA8)
}
/// The answer before the layer index: filter the depth-first walk by the selection set.
fn by_walk(doc: &Document, active: Option<LayerId>, selected: &[LayerId]) -> Vec<LayerId> {
let Some(active) = active else { return Vec::new() };
let set: &[LayerId] = if selected.contains(&active) { selected } else { std::slice::from_ref(&active) };
doc.walk().into_iter().map(|(_, _, l)| l.id).filter(|id| set.contains(id)).collect()
}
/// `a`, group `g` (`b`, group `h` (`c`), `d`), `e`: nested groups mixed with root layers.
fn mixed() -> (Document, Vec<LayerId>) {
let mut doc = Document::new("t", Size::new(4, 4), ColorMode::Rgb, SampleType::U8);
let (a, b, c, d, e) = (raster("a"), raster("b"), raster("c"), raster("d"), raster("e"));
let h = Layer::group("h", vec![c.clone()]);
let g = Layer::group("g", vec![b.clone(), h.clone(), d.clone()]);
let ids = [&a, &g, &b, &h, &c, &d, &e].map(|l| l.id).to_vec();
doc.layers = vec![a, g, e].into();
(doc, ids)
}
#[test]
fn selection_order_matches_the_walk_through_edits() {
let (mut doc, ids) = mixed();
let stale = LayerId::fresh();
let sets: Vec<Vec<LayerId>> =
vec![vec![ids[6], ids[4], ids[0]], vec![ids[5], ids[2], ids[1], ids[3]], vec![ids[4], ids[4], ids[0], stale], vec![ids[0]], vec![]];
let check = |doc: &Document| {
let first = doc.layers.index().serial();
for set in &sets {
for active in [None, Some(ids[0]), Some(ids[4]), Some(ids[6]), Some(stale)] {
assert_eq!(selected_in(doc, active, set), by_walk(doc, active, set));
}
}
assert_eq!(doc.layers.index().serial(), first, "no rebuild while the document is unchanged");
};
check(&doc);
// Reorder: move `e` to the bottom, then a layer inside a group.
doc.shift(ids[6], -2);
check(&doc);
doc.shift(ids[5], -1);
check(&doc);
// Add and delete.
doc.insert_above(Some(ids[4]), raster("new"));
check(&doc);
doc.remove(ids[3]);
check(&doc);
assert_eq!(selected_in(&doc, Some(ids[0]), &[ids[0], ids[3], ids[4]]), vec![ids[0]], "deleted layers are skipped");
}
}
+1 -3
View File
@@ -37,9 +37,7 @@ impl GroupOptions {
let blend = match get("mode") {
None => None,
Some(v) => Some(
v.as_str()
.and_then(crate::commands::blend_from_str)
.ok_or_else(|| bad("`mode` must be a blend mode such as \"passThrough\" or \"multiply\""))?,
v.as_str().and_then(crate::commands::parse_blend).ok_or_else(|| bad("`mode` must be a blend mode such as \"passThrough\" or \"multiply\""))?,
),
};
let opacity = match get("opacity") {
+1 -1
View File
@@ -344,7 +344,7 @@ mod tests {
roots.push(Layer::group("Outer", vec![group]));
session
.edit("Mask fixtures", |doc, _| {
doc.layers = roots;
doc.layers = roots.into();
Ok(())
})
.unwrap();
+1 -1
View File
@@ -64,7 +64,7 @@ pub fn insertion_point(doc: &Document, anchor: Option<LayerId>, layer: &Layer, p
pub fn insert_new(doc: &mut Document, anchor: Option<LayerId>, mut layer: Layer, place: Place) -> LayerId {
let id = layer.id;
let (parent, index) = insertion_point(doc, anchor, &layer, place);
let sib = if parent.is_empty() { Some(&mut doc.layers) } else { doc.layer_at_mut(&parent).and_then(Layer::children_mut) };
let sib = if parent.is_empty() { Some(&mut *doc.layers) } else { doc.layer_at_mut(&parent).and_then(Layer::children_mut) };
if let Some(sib) = sib {
let mut index = index.min(sib.len());
if layer.artboard().is_some() {
+4 -4
View File
@@ -9,7 +9,7 @@ use photocraft_doc::{
};
use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str};
use crate::commands::{CommandSpec, parse_blend};
use crate::presets::{always, bad};
use crate::{EngineError, Result, Session};
@@ -714,7 +714,7 @@ fn overlay_common(c: &mut FxCommon, p: &Value) {
if let Some(x) = b_of(p, "enabled") {
c.enabled = x;
}
if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(blend_from_str) {
if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(parse_blend) {
c.blend = x;
}
if let Some(x) = f_of(p, "opacity") {
@@ -883,10 +883,10 @@ fn overlay_bevel(bv: &mut Bevel, p: &Value) {
}
overlay_contour(p, "glossContour", &mut bv.gloss_contour);
overlay_bool(p, "glossAntiAlias", &mut bv.gloss_anti_alias);
if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(blend_from_str) {
if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(parse_blend) {
bv.highlight.blend = blend;
}
if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(blend_from_str) {
if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(parse_blend) {
bv.shadow.blend = blend;
}
overlay_color(p, "highlightColor", &mut bv.highlight_color);
+1
View File
@@ -201,6 +201,7 @@ pub(crate) fn active_layer_of(s: &Session) -> std::result::Result<&photocraft_do
#[derive(Default)]
pub struct Session {
docs: Vec<DocState>,
documents_generation: u64,
/// Override Open belongs only to one Batch scratch session, never to caller preferences.
pub(crate) batch_open: Option<file_cmds::BatchOpen>,
/// Import diagnostics retained by a Batch scratch that suppresses only profile prompts.
+1 -1
View File
@@ -74,7 +74,7 @@ pub(crate) fn parse(p: &Value) -> Result<NewLayer> {
None | Some(Value::Null) => BlendMode::Normal,
Some(v) => {
let name = v.as_str().ok_or_else(|| bad("`mode` must be a blend mode name"))?;
crate::commands::blend_from_str(name).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{name}`")))?
crate::commands::parse_blend(name).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{name}`")))?
}
};
let opacity = match p.get("opacity") {
+1 -1
View File
@@ -558,7 +558,7 @@ pub fn merge_down(doc: &Document, lower: &Layer, upper: &Layer) -> Layer {
let mut tmp = Document::new("merge", doc.size, format.mode, format.sample);
// The pair is read (and a CMYK one separated again) through the document's own profile.
tmp.icc_profile = doc.icc_profile.clone();
tmp.layers = stack;
tmp.layers = stack.into();
// A Background stays canvas-sized; any other layer keeps the pixels outside the canvas (#5067).
let s = if doc.is_background(lower.id) { composite_layers(&tmp, format, None) } else { composite_layers_uncropped(&tmp, format) };
let mut merged = Layer::new(lower.name.clone(), LayerContent::Raster(s));
+61 -1
View File
@@ -8,6 +8,8 @@ use super::{Deserialize, Map, Preferences, Serialize, Value};
pub struct PrefsStore {
values: Preferences,
rev: u64,
catalog_rev: u64,
section_revs: std::collections::BTreeMap<String, u64>,
}
impl PrefsStore {
@@ -16,8 +18,29 @@ impl PrefsStore {
}
/// Change preferences; bumps the revision.
pub fn edit<R>(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R {
let before = (&self.values.shortcuts, &self.values.alternate_shortcuts, &self.values.toolbar);
let before = (before.0.clone(), before.1.clone(), before.2.clone());
let sections = self.values.sections.clone();
self.rev += 1;
f(&mut self.values)
let result = f(&mut self.values);
if (&before.0, &before.1, &before.2) != (&self.values.shortcuts, &self.values.alternate_shortcuts, &self.values.toolbar) {
self.catalog_rev = self.catalog_rev.wrapping_add(1);
}
for key in sections.keys().chain(self.values.sections.keys()).collect::<std::collections::BTreeSet<_>>() {
if sections.get(key) != self.values.sections.get(key) {
let revision = self.section_revs.entry(key.clone()).or_default();
*revision = revision.wrapping_add(1);
}
}
result
}
/// Revision of catalog-affecting preferences.
pub fn catalog_rev(&self) -> u64 {
self.catalog_rev
}
/// Revision of a framework preference section.
pub fn section_rev(&self, key: &str) -> u64 {
self.section_revs.get(key).copied().unwrap_or_default()
}
pub fn rev(&self) -> u64 {
self.rev
@@ -131,3 +154,40 @@ fn lay_over(
fn object_at<'a>(root: &'a mut Value, path: &[String]) -> Option<&'a mut Map<String, Value>> {
path.iter().try_fold(root, |cur, k| cur.get_mut(k.as_str()))?.as_object_mut()
}
#[cfg(test)]
mod revision_tests {
use super::PrefsStore;
use serde_json::json;
#[test]
fn unrelated_preference_edits_do_not_invalidate_the_catalog() {
let mut prefs = PrefsStore::default();
let before = prefs.catalog_rev();
prefs.edit(|p| p.selected_tool = json!("brush"));
assert_eq!(prefs.catalog_rev(), before);
prefs.edit(|p| {
p.shortcuts.insert("example".into(), "A".into());
});
assert_eq!(prefs.catalog_rev(), before.wrapping_add(1));
}
#[test]
fn section_revisions_change_independently() {
let mut prefs = PrefsStore::default();
prefs.edit(|p| {
p.sections.insert("one".into(), json!({"value": 1}));
});
let one = prefs.section_rev("one");
let two = prefs.section_rev("two");
prefs.edit(|p| {
p.sections.insert("two".into(), json!({"value": 2}));
});
assert_eq!(prefs.section_rev("one"), one);
assert_eq!(prefs.section_rev("two"), two.wrapping_add(1));
prefs.edit(|p| {
p.sections.remove("one");
});
assert_eq!(prefs.section_rev("one"), one.wrapping_add(1));
}
}
+1 -1
View File
@@ -280,7 +280,7 @@ fn new_preset(s: &mut Session, p: &Value) -> Result<Value> {
}
}
},
blend: p.get("blend").and_then(Value::as_str).and_then(crate::commands::blend_from_str).or_else(|| with_blend.then_some(l.blend)),
blend: p.get("blend").and_then(Value::as_str).and_then(crate::commands::parse_blend).or_else(|| with_blend.then_some(l.blend)),
fill_opacity: p.get("fillOpacity").and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0) as f32).or_else(|| with_blend.then_some(l.fill_opacity)),
opacity: p.get("opacity").and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0) as f32).or_else(|| with_blend.then_some(l.opacity)),
};
+30
View File
@@ -24,6 +24,11 @@ impl Session {
&self.docs
}
/// Changes whenever a document is opened or closed.
pub fn documents_generation(&self) -> u64 {
self.documents_generation
}
pub fn active_index(&self) -> Option<usize> {
self.active
}
@@ -182,6 +187,7 @@ impl Session {
st.snapshots.clear();
}
self.docs.push(st);
self.documents_generation = self.documents_generation.wrapping_add(1);
let i = self.docs.len() - 1;
self.active = Some(i);
self.note_active_change();
@@ -222,6 +228,7 @@ impl Session {
self.link_scan = None;
}
let d = self.docs.remove(index);
self.documents_generation = self.documents_generation.wrapping_add(1);
self.open_document_order.retain(|&id| id != d.doc.id);
self.active = if self.docs.is_empty() {
None
@@ -244,3 +251,26 @@ pub(super) fn fix_active(st: &mut DocState) {
fix_selection(st);
channel_cmds::fix_view(st);
}
#[cfg(test)]
mod document_generation_tests {
use super::Session;
use photocraft_color::SampleType;
use photocraft_doc::{ColorMode, Document};
use photocraft_geom::Size;
#[test]
fn document_generation_tracks_open_and_close_but_not_selection() {
let mut session = Session::new();
let before = session.documents_generation();
session.add_document(Document::new("test", Size::new(2, 2), ColorMode::Rgb, SampleType::U8), None);
let opened = session.documents_generation();
assert_eq!(opened, before.wrapping_add(1));
session.set_active(0);
assert_eq!(session.documents_generation(), opened);
session.close(0);
assert_eq!(session.documents_generation(), opened.wrapping_add(1));
session.close(0);
assert_eq!(session.documents_generation(), opened.wrapping_add(1));
}
}
@@ -9,6 +9,7 @@ use std::sync::Arc;
#[test]
fn scratch_pixels_history_and_failed_save_are_transactional() {
photocraft_raster::spill::use_test_volume_space();
let _scratch = crate::lock(&crate::PROCESS);
let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-{}", std::process::id()));
let mut session = Session::new();
@@ -9,6 +9,7 @@ use serde_json::json;
#[test]
fn paused_scratch_disk_restores_the_history_limit() {
photocraft_raster::spill::use_test_volume_space();
let _scratch = crate::lock(&crate::PROCESS);
let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-pause-{}", std::process::id()));
let mut session = Session::new();
+1 -1
View File
@@ -468,7 +468,7 @@ fn artboard_fixture() -> Session {
}
let group = Layer::group("Group", vec![child]);
let id = group.id;
doc.layers = vec![group];
doc.layers = vec![group].into();
s.restore_layer_selection(Some(id), &[id], Some(id)).unwrap();
s
}
+1 -1
View File
@@ -134,7 +134,7 @@ fn stack(depth: u32) -> Session {
let group = Layer::new("Stack", LayerContent::Group(Group { children, expanded: true, artboard: None, frame_stroke: None }));
let smart = photocraft_engine::smart_cmds::layer_to_smart(doc, &group)?;
*active = Some(smart.id);
doc.layers = vec![smart];
doc.layers = vec![smart].into();
Ok(())
})
.unwrap();
@@ -196,7 +196,7 @@ fn smart_scene(children: Vec<Layer>) -> Session {
doc.icc_profile = Some(Builtin::Srgb.profile().to_bytes());
let ordinary = Layer::raster("Ordinary", PixelFormat::RGBA32F);
let active = ordinary.id;
doc.layers = vec![Layer::group("Outer", vec![Layer::group("Inner", children)]), ordinary];
doc.layers = vec![Layer::group("Outer", vec![Layer::group("Inner", children)]), ordinary].into();
from_document(doc, Some(active))
}
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff. Show more