Merge origin/main into automation/shared-live-client

# Conflicts:
#	Cargo.lock
#	Cargo.toml
#	crates/engine/Cargo.toml
This commit is contained in:
David Mann committed 2026-11-19 17:40:46 +01:00
commit 810f4cb7eb
136 files changed
+1809 -461

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
@@ -6697,6 +6697,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);
}
}
+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);
+1 -1
View File
@@ -52,7 +52,7 @@ fn library_tip_bytes(s: &Session) -> (usize, u64, u64) {
previews += g.data.len() as u64 * 2;
}
};
for p in &s.tools.presets {
for p in s.tools.presets.iter() {
let b = &p.brush;
for t in [&b.tip, &b.dual_brush.tip] {
match t {
+4 -4
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)));
+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
@@ -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.
+8 -5
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;
}
@@ -980,9 +980,9 @@ fn name_param(p: &Value, cmd: &str) -> Result<String> {
/// Replace the preset of that name, or append it at the end of the list.
fn upsert(s: &mut Session, preset: BrushPreset) {
match s.tools.presets.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&preset.name)) {
match std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|x| x.name.eq_ignore_ascii_case(&preset.name)) {
Some(x) => *x = preset,
None => s.tools.presets.push(preset),
None => std::sync::Arc::make_mut(&mut s.tools.presets).push(preset),
}
s.brush_presets_changed();
}
@@ -1010,7 +1010,7 @@ fn presets_delete(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "brush.presets.delete";
let name = name_param(p, cmd)?;
let before = s.tools.presets.len();
s.tools.presets.retain(|x| !x.name.eq_ignore_ascii_case(&name));
std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| !x.name.eq_ignore_ascii_case(&name));
if s.tools.presets.len() == before {
return Err(bad(cmd, format!("no brush preset named `{name}`")));
}
@@ -1043,7 +1043,10 @@ fn presets_update(s: &mut Session, p: &Value) -> Result<Value> {
Some(patch) => merge_brush(&s.tools.brush, patch, cmd)?,
None => s.tools.brush.clone(),
};
let pr = s.tools.presets.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no brush preset named `{name}`")))?;
let pr = std::sync::Arc::make_mut(&mut s.tools.presets)
.iter_mut()
.find(|x| x.name.eq_ignore_ascii_case(&name))
.ok_or_else(|| bad(cmd, format!("no brush preset named `{name}`")))?;
pr.brush = brush;
pr.builtin = false;
let (name, group) = (pr.name.clone(), pr.group.clone());
+2 -2
View File
@@ -263,7 +263,7 @@ mod tests {
#[test]
fn previous_and_next_brush_walk_the_presets_and_wrap() {
let mut s = Session::new();
s.tools.presets = vec![preset("One", "", &[], 11.0), preset("Two", "", &[], 22.0), preset("Three", "", &[], 33.0)];
s.tools.presets = std::sync::Arc::new(vec![preset("One", "", &[], 11.0), preset("Two", "", &[], 22.0), preset("Three", "", &[], 33.0)]);
s.tools.current_preset = None;
let picked = |s: &Session| (s.tools.current_preset.clone().unwrap_or_default(), s.tools.brush.size);
s.execute("tools.nextBrush", Value::Null).unwrap();
@@ -284,7 +284,7 @@ mod tests {
[Some(","), Some("."), Some("Shift+,"), Some("Shift+.")]
);
// No presets: an error, and the brush and the current preset stay as they were.
s.tools.presets.clear();
std::sync::Arc::make_mut(&mut s.tools.presets).clear();
let (brush, current) = (s.tools.brush.clone(), s.tools.current_preset.clone());
for id in ["tools.previousBrush", "tools.nextBrush", "tools.firstBrush", "tools.lastBrush"] {
assert!(s.execute(id, Value::Null).is_err(), "{id}");
+11 -11
View File
@@ -120,7 +120,7 @@ pub(crate) fn rename_at(s: &mut Session, i: usize, new: &str, cmd: &str) -> Resu
if index_of(&s.tools.presets, new).is_some_and(|j| j != i) {
return Err(bad(cmd, format!("a brush preset named `{new}` already exists")));
}
let pr = s.tools.presets.get_mut(i).ok_or_else(|| bad(cmd, "no such preset"))?;
let pr = std::sync::Arc::make_mut(&mut s.tools.presets).get_mut(i).ok_or_else(|| bad(cmd, "no such preset"))?;
if pr.name != new {
let was_current = s.tools.current_preset.as_ref().is_some_and(|c| c.eq_ignore_ascii_case(&pr.name));
pr.name = new.to_string();
@@ -153,7 +153,7 @@ fn move_preset(s: &mut Session, p: &Value) -> Result<Value> {
};
let folder = folder_param(p, cmd)?;
let group = group_param(p, "group", cmd)?;
let lib = &mut s.tools.presets;
let lib = std::sync::Arc::make_mut(&mut s.tools.presets);
let (Some(moving), before_pr) = (lib.get(i), before.and_then(|b| lib.get(b))) else {
return Err(bad(cmd, "no such preset"));
};
@@ -233,7 +233,7 @@ fn move_folder(s: &mut Session, p: &Value, g: String, f: Vec<String>, cmd: &str)
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().ok_or_else(|| bad(cmd, "`index` must be a non-negative integer"))?),
};
let lib = std::mem::take(&mut s.tools.presets);
let lib = std::sync::Arc::unwrap_or_clone(std::mem::take(&mut s.tools.presets));
// Where the block sits among the other presets (its place when nothing else is in the parent).
let start = lib.iter().position(|x| in_folder(x, &g, &f)).unwrap_or(0);
let (block, mut rest): (Vec<BrushPreset>, Vec<BrushPreset>) = lib.into_iter().partition(|x| in_folder(x, &g, &f));
@@ -252,7 +252,7 @@ fn move_folder(s: &mut Session, p: &Value, g: String, f: Vec<String>, cmd: &str)
let tail = rest.split_off(pos.min(rest.len()));
rest.extend(block);
rest.extend(tail);
s.tools.presets = rest;
s.tools.presets = std::sync::Arc::new(rest);
s.brush_presets_changed();
let at = subfolder_order(&s.tools.presets, &g, parent).iter().position(|x| x == leaf).unwrap_or(0);
Ok(json!({ "group": g, "folder": f, "index": at }))
@@ -332,7 +332,7 @@ fn move_into(s: &mut Session, p: &Value, g: String, f: Vec<String>, dest: Dest,
if deepest > MAX_FOLDER_DEPTH {
return Err(bad(cmd, format!("folders can be nested at most {MAX_FOLDER_DEPTH} deep")));
}
let lib = std::mem::take(&mut s.tools.presets);
let lib = std::sync::Arc::unwrap_or_clone(std::mem::take(&mut s.tools.presets));
let (mut block, mut rest): (Vec<BrushPreset>, Vec<BrushPreset>) = lib.into_iter().partition(|x| in_folder(x, &g, &f));
for x in &mut block {
let tail = rest_of(x);
@@ -352,7 +352,7 @@ fn move_into(s: &mut Session, p: &Value, g: String, f: Vec<String>, dest: Dest,
let tail = rest.split_off(pos.unwrap_or(rest.len()).min(rest.len()));
rest.extend(block);
rest.extend(tail);
s.tools.presets = rest;
s.tools.presets = std::sync::Arc::new(rest);
s.brush_presets_changed();
let folder = new_prefix.get(..new_prefix.len().saturating_sub(1)).unwrap_or_default();
let at = match &dest {
@@ -382,7 +382,7 @@ fn move_group(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().ok_or_else(|| bad(cmd, "`index` must be a non-negative integer"))?),
};
let lib = std::mem::take(&mut s.tools.presets);
let lib = std::sync::Arc::unwrap_or_clone(std::mem::take(&mut s.tools.presets));
let (block, mut rest): (Vec<BrushPreset>, Vec<BrushPreset>) = lib.into_iter().partition(|x| x.group == g);
let order = group_order(&rest);
let first = |name: &str, rest: &[BrushPreset]| rest.iter().position(|x| x.group == name).unwrap_or(rest.len());
@@ -394,7 +394,7 @@ fn move_group(s: &mut Session, p: &Value) -> Result<Value> {
let tail = rest.split_off(pos.min(rest.len()));
rest.extend(block);
rest.extend(tail);
s.tools.presets = rest;
s.tools.presets = std::sync::Arc::new(rest);
s.brush_presets_changed();
let at = group_order(&s.tools.presets).iter().position(|x| *x == g).unwrap_or(0);
Ok(json!({ "group": g, "index": at }))
@@ -410,7 +410,7 @@ fn rename_group(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, format!("a folder named `{new}` already exists there")));
}
let depth = parent.len();
for x in s.tools.presets.iter_mut().filter(|x| in_folder(x, &g, &f)) {
for x in std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().filter(|x| in_folder(x, &g, &f)) {
if let Some(n) = x.folder.get_mut(depth) {
n.clone_from(&new);
}
@@ -426,7 +426,7 @@ fn rename_group(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, format!("a group named `{new}` already exists")));
}
if new != g {
for x in s.tools.presets.iter_mut().filter(|x| x.group == g) {
for x in std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().filter(|x| x.group == g) {
x.group = new.clone();
x.builtin = false;
}
@@ -439,7 +439,7 @@ fn delete_group(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "brush.presets.deleteGroup";
let (g, f) = target_folder(s, p, cmd)?;
let before = s.tools.presets.len();
s.tools.presets.retain(|x| !in_folder(x, &g, &f));
std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| !in_folder(x, &g, &f));
if s.tools.current_preset.as_ref().is_some_and(|c| !s.tools.presets.iter().any(|x| x.name.eq_ignore_ascii_case(c))) {
s.tools.current_preset = None;
s.tools.brush_changed();
@@ -7,7 +7,7 @@ fn names(s: &Session, g: &str) -> Vec<String> {
fn with_groups() -> Session {
let mut s = Session::new();
for (n, g) in [("A1", "Alpha"), ("A2", "Alpha"), ("A3", "Alpha"), ("B1", "Beta"), ("B2", "Beta")] {
s.tools.presets.push(BrushPreset {
std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset {
name: n.into(),
brush: Default::default(),
builtin: false,
@@ -119,7 +119,7 @@ fn with_folders() -> Session {
let mut s = Session::new();
for (n, f) in [("S0", &[][..]), ("I1", &["Ink"][..]), ("F1", &["Ink", "Fine"][..]), ("I2", &["Ink"][..]), ("D1", &["Dry"][..])] {
let folder = f.iter().map(|x| x.to_string()).collect();
s.tools.presets.push(BrushPreset {
std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset {
name: n.into(),
brush: Default::default(),
builtin: false,
@@ -226,7 +226,7 @@ fn with_two_groups() -> Session {
let mut s = with_folders();
for (n, f) in [("O1", &[][..]), ("B1", &["Box"][..])] {
let folder = f.iter().map(|x| x.to_string()).collect();
s.tools.presets.push(BrushPreset {
std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset {
name: n.into(),
brush: Default::default(),
builtin: false,
@@ -266,7 +266,7 @@ fn bad_moves_into_folders_fail_without_changes() {
let mut s = with_two_groups();
// A chain 31 deep under Set/Deep.
let deep: Vec<String> = std::iter::once("Deep".to_string()).chain((0..30).map(|i| format!("d{i}"))).collect();
s.tools.presets.push(BrushPreset {
std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset {
name: "Z".into(),
brush: Default::default(),
builtin: false,
@@ -274,7 +274,7 @@ fn bad_moves_into_folders_fail_without_changes() {
folder: deep.clone(),
captures: Default::default(),
});
s.tools.presets.push(BrushPreset {
std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset {
name: "Y".into(),
brush: Default::default(),
builtin: false,
@@ -314,7 +314,7 @@ fn bad_moves_into_folders_fail_without_changes() {
s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "into": {"group": "Set"}})).unwrap();
assert_eq!(folder_of(&s, "F1"), ["Fine"]);
// An ungrouped preset's group can't move.
s.tools.presets.push(BrushPreset {
std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset {
name: "U".into(),
brush: Default::default(),
builtin: 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}`")),
},
+3 -3
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
@@ -314,9 +314,9 @@ fn export_import(s: &mut Session, p: &Value) -> Result<Value> {
// absurd tree).
b.folder.retain(|f| !f.trim().is_empty());
b.folder.truncate(crate::brush_preset_cmds::MAX_FOLDER_DEPTH);
match s.tools.presets.iter_mut().find(|x| x.name == b.name) {
match std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|x| x.name == b.name) {
Some(x) => *x = b,
None => s.tools.presets.push(b),
None => std::sync::Arc::make_mut(&mut s.tools.presets).push(b),
}
nb += 1;
}
+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()))?;
@@ -114,7 +114,7 @@ pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result<Value> {
}
"delete" => match kind.as_str() {
"brushes" => {
let gone = s.tools.presets.remove(i);
let gone = std::sync::Arc::make_mut(&mut s.tools.presets).remove(i);
crate::brush_cmds::forget_deleted_preset(s, &gone.name);
}
"patterns" => drop(s.patterns.items.remove(i)),
@@ -123,7 +123,7 @@ pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result<Value> {
"move" => {
let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `to`"))? as usize;
match kind.as_str() {
"brushes" => crate::move_item(&mut s.tools.presets, i, to),
"brushes" => crate::move_item(std::sync::Arc::make_mut(&mut s.tools.presets), i, to),
"patterns" => crate::move_item(&mut s.patterns.items, i, to),
_ => crate::move_item(&mut s.edit_state.custom_shapes, i, to),
};
+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}") }),
+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() {
+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
});
+1 -1
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));
+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).
+6 -1
View File
@@ -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());
+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);
+4 -4
View File
@@ -155,7 +155,7 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io
// in Photoshop, unless `replace` asks to drop that group's own presets first: the group name
// is only the file name, and the library is outside document history (#10640).
let group = if p.get("replace").and_then(Value::as_bool).unwrap_or(false) {
s.tools.presets.retain(|x| x.builtin || x.group != group);
std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| x.builtin || x.group != group);
group
} else {
// One pass over the library, not one per numbered candidate.
@@ -168,7 +168,7 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io
preset.group.clone_from(&group);
preset.name = taken.unique(&preset.name);
names.push(preset.name.clone());
s.tools.presets.push(preset);
std::sync::Arc::make_mut(&mut s.tools.presets).push(preset);
}
s.brush_presets_changed();
if p.get("select").and_then(Value::as_bool).unwrap_or(false)
@@ -262,7 +262,7 @@ fn import_image(s: &mut Session, p: &Value) -> Result<Value> {
let (v, w, h) = image_paint(&doc, cmd)?;
let (brush, tw, th) = crate::brush_cmds::sampled_brush(cmd, &v, w, h)?;
let name = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())).unique(&name);
s.tools.presets.push(photocraft_paint::BrushPreset {
std::sync::Arc::make_mut(&mut s.tools.presets).push(photocraft_paint::BrushPreset {
name: name.clone(),
brush: brush.clone(),
builtin: false,
@@ -541,7 +541,7 @@ mod tests {
// The user's own brush moved into the group.
let mut own = s.tools.presets.iter().find(|p| p.group == "Kit").unwrap().clone();
own.name = "My Ink".into();
s.tools.presets.push(own);
std::sync::Arc::make_mut(&mut s.tools.presets).push(own);
let r = s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit"})).unwrap();
assert_eq!(r["group"], "Kit (2)");
let in_group = |s: &Session, g: &str| s.tools.presets.iter().filter(|p| p.group == g).count();
+1 -1
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;
+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(crate) 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
@@ -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
@@ -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)?;
+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();
+2 -2
View File
@@ -183,7 +183,7 @@ pub struct ToolState {
pub background: [f32; 4],
pub brush: photocraft_paint::BrushSettings,
/// Brush presets (built-ins plus user presets; see `brush.presets.*`).
pub presets: Vec<photocraft_paint::BrushPreset>,
pub presets: Arc<Vec<photocraft_paint::BrushPreset>>,
/// Bumped whenever `presets` changes ([`Session::brush_presets_changed`]); the preset store
/// syncs when it moves.
pub presets_rev: u64,
@@ -284,7 +284,7 @@ impl Default for ToolState {
smoothing: photocraft_paint::brush::Smoothing { amount: 0.1, ..Default::default() },
..Default::default()
},
presets: photocraft_paint::presets::builtin(),
presets: photocraft_paint::presets::builtin_shared(),
presets_rev: 0,
mixer: Default::default(),
brush_gesture: None,
+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") {
+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") {
+6
View File
@@ -1946,6 +1946,12 @@ impl Session {
self.prefs.get()
}
/// Revision of the framework preference section `key`: it moves when an edit changes that
/// section.
pub fn section_rev(&self, key: &str) -> u64 {
self.prefs.section_rev(key)
}
/// Change preferences and apply the engine-side ones.
pub fn edit_prefs<R>(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R {
let r = self.prefs.edit(f);
+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));
}
}
+16 -9
View File
@@ -879,7 +879,7 @@ impl PresetStore {
/// Bring the files in line with `presets` (built-ins skipped): write changed groups, delete
/// removed ones and their unreferenced tips, update the index. The bitmaps of every group
/// written become stored tiles (#1843): the files hold them, so the presets keep previews only.
pub fn sync(&mut self, presets: &mut [BrushPreset]) {
pub fn sync(&mut self, presets: &mut std::sync::Arc<Vec<BrushPreset>>) {
// User presets by group, in first-appearance order.
let mut order: Vec<(String, Vec<usize>)> = Vec::new();
for (i, p) in presets.iter().enumerate().filter(|(_, p)| !p.builtin) {
@@ -906,7 +906,7 @@ impl PresetStore {
));
continue;
}
let mut items: Vec<&mut BrushPreset> = presets.iter_mut().filter(|p| !p.builtin && p.group == *group).collect();
let mut items: Vec<&mut BrushPreset> = std::sync::Arc::make_mut(presets).iter_mut().filter(|p| !p.builtin && p.group == *group).collect();
if let Err(e) = self.write_group(&file, group, &mut items) {
self.warnings.push(format!("Couldn't save brush presets `{}`: {e}", if group.is_empty() { "(ungrouped)" } else { group }));
}
@@ -1103,7 +1103,7 @@ impl PresetStore {
fn builtin_names() -> &'static [String] {
static NAMES: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
NAMES.get_or_init(|| photocraft_paint::presets::builtin().into_iter().map(|p| p.name).collect())
NAMES.get_or_init(|| photocraft_paint::presets::builtin_shared().iter().map(|p| p.name.clone()).collect())
}
impl Session {
@@ -1141,19 +1141,26 @@ impl Session {
}
}
}
let lib = &mut self.tools.presets;
lib.retain(|p| !(p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name))));
// The list stays shared (`make_mut` is taken at the first write) when the store changes nothing.
let hide = |p: &BrushPreset| p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name));
if self.tools.presets.iter().any(hide) {
std::sync::Arc::make_mut(&mut self.tools.presets).retain(|p| !hide(p));
}
for p in presets {
match lib.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&p.name)) {
Some(x) if x.builtin => *x = p,
let found = self.tools.presets.iter().position(|x| x.name.eq_ignore_ascii_case(&p.name));
match found {
Some(i) if self.tools.presets[i].builtin && self.tools.presets[i] != p => std::sync::Arc::make_mut(&mut self.tools.presets)[i] = p,
Some(_) => {}
None => lib.push(p),
None => std::sync::Arc::make_mut(&mut self.tools.presets).push(p),
}
}
// The saved panel order (stable: presets it doesn't name keep their order, at the end).
if !order.is_empty() {
let pos: HashMap<String, usize> = order.iter().enumerate().map(|(i, n)| (n.to_lowercase(), i)).collect();
lib.sort_by_key(|p| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX));
let key = |p: &BrushPreset| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX);
if !self.tools.presets.iter().map(key).is_sorted() {
std::sync::Arc::make_mut(&mut self.tools.presets).sort_by_key(key);
}
}
self.preset_store = Some(store);
// Clear All, Reset or Replace before the store loaded made the session's list the whole
+38 -8
View File
@@ -52,6 +52,20 @@ fn user(s: &Session) -> Vec<BrushPreset> {
s.tools.presets.iter().filter(|p| !p.builtin).cloned().collect()
}
#[test]
fn empty_stores_preserve_shared_builtin_presets() {
let first_dir = TempDir::new("shared-first");
let second_dir = TempDir::new("shared-second");
let (mut first, warnings) = session(&first_dir);
assert!(warnings.is_empty(), "{warnings:?}");
let (second, warnings) = session(&second_dir);
assert!(warnings.is_empty(), "{warnings:?}");
assert!(std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets));
first.execute("brush.presets.save", json!({"name": "Only first"})).unwrap();
assert!(second.tools.presets.iter().all(|p| p.name != "Only first"));
assert!(!std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets));
}
#[test]
fn sessions_have_no_store_by_default() {
let mut s = Session::new();
@@ -119,7 +133,7 @@ fn group_with_sampled_8_and_16_bit_tips_round_trips() {
let b = sampled("Sixteen", "Inks", tip16(50, 70, 2));
let mut c = sampled("Shared tip", "Other", tip8(64, 48, 1));
c.brush.size = 9.0;
s.tools.presets.extend([a, b, c]);
std::sync::Arc::make_mut(&mut s.tools.presets).extend([a, b, c]);
s.brush_presets_changed();
s.sync_preset_store();
let files = dir.files();
@@ -243,7 +257,7 @@ fn startup_with_many_groups_loads_them_all() {
let (mut s, _) = session(&dir);
for g in 0..25 {
for i in 0..4 {
s.tools.presets.push(sampled(&format!("P{g}-{i}"), &format!("Group {g}"), tip8(16 + i, 16, g)));
std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("P{g}-{i}"), &format!("Group {g}"), tip8(16 + i, 16, g)));
}
}
s.brush_presets_changed();
@@ -267,7 +281,7 @@ fn reordering_presets_and_groups_persists() {
let (mut s, _) = session(&dir);
for (n, g) in [("Ink 1", "Inks"), ("Ink 2", "Inks"), ("Wash", "Washes")] {
s.execute("brush.presets.save", json!({"name": n})).unwrap();
s.tools.presets.iter_mut().find(|p| p.name == n).unwrap().group = g.into();
std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|p| p.name == n).unwrap().group = g.into();
}
s.brush_presets_changed();
s.sync_preset_store();
@@ -295,12 +309,28 @@ fn reordering_presets_and_groups_persists() {
assert!(t.tools.presets.iter().all(|p| p.group != "Washes" && p.group != "Inks"));
}
#[test]
fn reordering_only_built_in_presets_persists() {
let names = |s: &Session| s.tools.presets.iter().map(|p| p.name.clone()).collect::<Vec<_>>();
let dir = TempDir::new("reorder-builtin");
let (mut s, _) = session(&dir);
let group = s.tools.presets[0].group.clone();
let last = s.tools.presets.iter().rfind(|p| p.builtin && p.group == group).unwrap().name.clone();
let first = s.tools.presets[0].name.clone();
assert_ne!(last, first);
s.execute("brush.presets.move", json!({"name": last, "before": first})).unwrap();
assert_eq!(s.tools.presets[0].name, last);
let (t, w) = session(&dir);
assert!(w.is_empty(), "{w:?}");
assert_eq!(names(&t), names(&s), "the new built-in order survives a restart");
}
#[test]
fn corrupt_and_oversized_files_are_skipped_with_a_warning() {
let dir = TempDir::new("corrupt");
let (mut s, _) = session(&dir);
s.tools.presets.push(sampled("Good", "Fine", tip8(8, 8, 1)));
s.tools.presets.push(sampled("Lost", "Broken tip", tip16(9, 9, 2)));
std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled("Good", "Fine", tip8(8, 8, 1)));
std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled("Lost", "Broken tip", tip16(9, 9, 2)));
s.brush_presets_changed();
s.sync_preset_store();
let be = DirBackend::new(&dir.0);
@@ -370,7 +400,7 @@ fn bench_load_500_sampled_presets() {
// A mix of 8-bit (most .abr tips) and 16-bit tips, 64..319 px.
let side = 64 + (i * 37) % 256;
let t = if i % 4 == 0 { tip16(side, side, i) } else { tip8(side, side, i) };
s.tools.presets.push(sampled(&format!("Brush {i}"), &format!("Set {}", i / 50), t));
std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("Brush {i}"), &format!("Set {}", i / 50), t));
}
s.brush_presets_changed();
let t0 = std::time::Instant::now();
@@ -411,7 +441,7 @@ fn library(n: u32, side: u32) -> (Session, MemBackend) {
let mut s = Session::new();
s.attach_preset_store(open(Box::new(mem.clone())));
for i in 0..n {
s.tools.presets.push(sampled(&format!("Big {i}"), "Big Set", tip8(side, side, i)));
std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("Big {i}"), "Big Set", tip8(side, side, i)));
}
s.brush_presets_changed();
s.sync_preset_store();
@@ -519,7 +549,7 @@ fn missing_corrupt_or_unknown_tips_fail_when_used_without_panicking() {
let k0 = key(&t, "Big 0");
mem.remove(&tip_file(&k0)).unwrap();
t.execute("tools.setBrush", json!({"preset": "Hard Round"})).unwrap();
let broken = t.tools.presets.iter_mut().find(|p| p.name == "Big 0").unwrap();
let broken = std::sync::Arc::make_mut(&mut t.tools.presets).iter_mut().find(|p| p.name == "Big 0").unwrap();
broken.captures.color = true;
broken.brush.color = [1.0, 0.0, 0.0, 1.0];
t.tools.foreground = [0.0, 0.0, 1.0, 1.0];
+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));
}
}
+13
View File
@@ -2063,3 +2063,16 @@ fn the_active_layer_marker_advances_for_a_new_document_and_not_for_a_same_layer_
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
assert!(s.active_layer_changes() > before, "a new active document advances the marker");
}
#[test]
fn sessions_share_builtin_brushes_until_edited() {
let mut first = Session::new();
let second = Session::new();
assert!(std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets));
let count = second.tools.presets.len();
first.execute("brush.presets.save", serde_json::json!({"name": "Session-only test brush"})).unwrap();
assert_eq!(second.tools.presets.len(), count);
assert!(second.tools.presets.iter().all(|preset| preset.name != "Session-only test brush"));
assert!(first.tools.presets.iter().any(|preset| preset.name == "Session-only test brush"));
assert!(!std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets));
}
@@ -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();
@@ -134,8 +134,8 @@ fn undo_redo(s: &mut Session, before: &Document) {
/// Matches the three measured rows: bounds and sample points, at half the measured size.
#[test]
fn measured_straight_rows_fill_background_and_only_the_active_raster() {
let (mut s, ids) = scene();
for row in 0..3 {
let (mut s, ids) = scene();
let active = if row == 1 { ids.edge } else { ids.quads };
if row == 2 {
s.edit("Layer 0", |d, _| {
@@ -172,6 +172,8 @@ fn measured_straight_rows_fill_background_and_only_the_active_raster() {
unchanged(d, &plain, &untouched);
named_one_step(&s, past, "Content-aware Crop");
undo_redo(&mut s, &before);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(doc(&s), &before);
}
}
@@ -179,8 +181,9 @@ fn measured_straight_rows_fill_background_and_only_the_active_raster() {
#[test]
fn turned_rows_sample_each_target_and_leave_other_layers_at_plain_crop() {
let (x, y) = extension_sample();
let (mut s, ids) = scene();
let original = doc(&s).clone();
for row in 0..3 {
let (mut s, ids) = scene();
// Uniform donors isolate target selection from the existing turned-fill sampling policy.
s.edit("Uniform Quads", |d, _| {
let fmt = d.pixel_format();
@@ -213,15 +216,20 @@ fn turned_rows_sample_each_target_and_leave_other_layers_at_plain_crop() {
unchanged(d, &plain, &untouched);
named_one_step(&s, past, "Content-aware Crop");
undo_redo(&mut s, &before);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(doc(&s), &before);
s.execute("edit.undo", json!({})).unwrap(); // Restore the scene before the uniform edit.
assert_eq!(doc(&s), &original);
}
}
/// Selecting the Background leaves each other layer identical to its plain crop.
#[test]
fn background_active_is_not_a_second_target() {
let (mut s, ids) = scene();
let original = doc(&s).clone();
for turned in [false, true] {
let (x, y) = extension_sample();
let (mut s, ids) = scene();
select(&mut s, ids.background);
let p = frame(turned);
let plain = plain_control(&mut s, &p);
@@ -230,6 +238,8 @@ fn background_active_is_not_a_second_target() {
pixel(doc(&s), ids.background, x, y, WHITE);
unchanged(doc(&s), &plain, &[ids.quads, ids.small, ids.edge, ids.hidden, ids.text]);
named_one_step(&s, past, "Content-aware Crop");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(doc(&s), &original);
}
}
+7 -3
View File
@@ -237,9 +237,13 @@ fn gray_tone_records_do_not_leak_from_rgb_channels() {
for (target, panel) in
[(json!("mask"), ChannelTarget::LayerMask), (json!({"channel":0}), ChannelTarget::Alpha(0)), (json!("quickMask"), ChannelTarget::Composite)]
{
for style in ["levels", "points", "pencil"] {
for sampled in [false, true] {
for explicit in [false, true] {
// Each style sees both flags; all four flag pairs occur across the styles.
for (si, style) in ["levels", "points", "pencil"].into_iter().enumerate() {
for (ai, sampled) in [false, true].into_iter().enumerate() {
for (ei, explicit) in [false, true].into_iter().enumerate() {
if (si + ai) % 2 != ei {
continue;
}
let mut clean = session(mode, depth);
clean.active_mut().unwrap().channel_view.target = panel;
clean
+1
View File
@@ -8,6 +8,7 @@ use std::io::{Read, Seek, SeekFrom, Write};
#[test]
fn retry_after_failed_hashing_never_reuses_placeholder_hashes() {
photocraft_raster::spill::use_test_volume_space();
let dir = std::env::temp_dir().join(format!("photocraft-format-scratch-retry-{}", std::process::id()));
spill::configure(Some(&dir), 1).unwrap();
let mut doc = Document::new("Retry", Size::new(512, 256), ColorMode::Rgb, SampleType::U8);
+16 -13
View File
@@ -170,10 +170,6 @@ fn image(w: usize, h: usize, depth: Depth) -> Vec<[f32; 4]> {
}
/// Develops `p` both ways and returns the largest channel difference.
fn compare(g: &mut Gpu, p: &Case, depth: Depth) -> f32 {
compare_at(g, p, depth, (171, 113))
}
fn compare_at(g: &mut Gpu, p: &Case, depth: Depth, (w, h): (usize, usize)) -> f32 {
compare_image(g, p, depth, &image(w, h, depth), (w, h))
}
@@ -207,10 +203,14 @@ fn compare_image(g: &mut Gpu, p: &Case, depth: Depth, src: &[[f32; 4]], (w, h):
}
fn check(name: &str, sets: &[Case]) {
check_at(name, sets, (171, 113));
}
fn check_at(name: &str, sets: &[Case], size: (usize, usize)) {
let Some(mut g) = gpu() else { return };
for p in sets {
for depth in DEPTHS {
let d = compare(&mut g, p, depth);
let d = compare_at(&mut g, p, depth, size);
eprintln!("{name} {depth:?}: max |GPU - CPU| = {d:.2e}");
}
}
@@ -424,7 +424,8 @@ fn shadows_and_highlights() {
cr! { shadows: 35.0, highlights: -45.0, encoding_gamma: 1.8},
];
assert_moves(&sets);
check("shadows/highlights", &sets);
// The long side preserves the spatial filter scale; 48 rows keep several pyramid levels.
check_at("shadows/highlights", &sets, (171, 48));
}
#[test]
@@ -476,7 +477,7 @@ fn shadows_and_highlights_with_per_pixel_stages() {
vignette_amount: -30.0,
grain_amount: 20.0,
pixel_scale: 0.2};
check(
check_at(
"shadows/highlights + per pixel",
&[
all.clone(),
@@ -485,10 +486,11 @@ fn shadows_and_highlights_with_per_pixel_stages() {
cr! { highlights: -60.0, whites: -60.0, blacks: 50.0, exposure: -0.4},
cr! { shadows: 30.0, highlights: -30.0, whites: 40.0, blacks: -30.0, encoding_gamma: 1.8},
],
(171, 48),
);
// At the dialog's proxy width, at one depth: the depth only changes how the input is
// quantized (8 and 16 bits both develop with `float = false`), and every depth already ran
// above at 171×113. The long side is what matters here (subsampled pyramid levels); the short
// above at 171×48. The long side is what matters here (subsampled pyramid levels); the short
// one only needs to keep several levels, so the frame is a strip.
let Some(mut g) = gpu() else { return };
let d = compare_at(&mut g, &all, Depth::Sixteen, (858, 120));
@@ -499,9 +501,9 @@ fn shadows_and_highlights_with_per_pixel_stages() {
/// with the CPU can't pass trivially.
fn assert_moves(sets: &[Case]) {
for p in sets {
let src = image(171, 113, Depth::Sixteen);
let src = image(171, 48, Depth::Sixteen);
let mut out = src.clone();
develop(&mut out, 171, 113, p, false);
develop(&mut out, 171, 48, p, false);
let moved = out.iter().zip(&src).flat_map(|(a, b)| (0..3).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max);
assert!(moved > 0.02, "{p:?} moves pixels by at most {moved}");
}
@@ -523,7 +525,8 @@ fn clarity_texture_and_dehaze() {
cr! { dehaze: -30.0, clarity: -25.0, texture: 60.0, encoding_gamma: 1.8},
];
assert_moves(&sets);
check("clarity/texture/dehaze", &sets);
// Match the movement check while retaining several pyramid levels.
check_at("clarity/texture/dehaze", &sets, (171, 48));
}
#[test]
@@ -563,11 +566,11 @@ fn clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages() {
cr! { clarity: 50.0, whites: -50.0, blacks: 45.0, exposure: -0.3},
cr! { texture: -60.0, whites: 30.0, blacks: -60.0},
];
check("clarity/texture/dehaze + shadows/highlights + per pixel", &sets);
check_at("clarity/texture/dehaze + shadows/highlights + per pixel", &sets, (171, 48));
let Some(mut g) = gpu() else { return };
// At the dialog's proxy width (Dehaze and Clarity on a copy subsampled twice), and wider (three
// times). One depth per size: the depth only changes how the input is quantized (8 and 16
// bits both develop with `float = false`), and every depth already ran above at 171×113. The
// bits both develop with `float = false`), and every depth already ran above at 171×48. The
// long side sets the subsampling; the short one only needs to keep several pyramid levels, so
// the frames are strips.
for (size, depth) in [((858, 120), Depth::Eight), ((1600, 120), Depth::Float)] {
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "photocraft-oil-round-proof"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[lints]
workspace = true
[dev-dependencies]
photocraft-algo = { workspace = true }
rayon = { workspace = true }
+34
View File
@@ -0,0 +1,34 @@
//! Exhaustive proof for the rounding implementation used by the oil filter.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
// Compile the same source that the oil filter uses, with this package's test profile.
#[cfg(test)]
#[path = "../../algo/src/oil/round.rs"]
mod round;
#[cfg(test)]
mod tests {
use super::round::round_i32;
// Keep the proof in the algorithm crate's dependent test graph.
use photocraft_algo as _;
use rayon::prelude::*;
/// 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() {
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");
}
}
+31 -2
View File
@@ -438,8 +438,10 @@ impl Texture {
}
}
/// The built-in preset set, in display order (grouped by [`GROUPS`]).
pub fn builtin() -> Vec<BrushPreset> {
#[cfg(test)]
static BUILTIN_INITIALIZATIONS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn build_builtin() -> Vec<BrushPreset> {
let base = BrushSettings { pressure_size: false, spacing: 0.25, ..Default::default() };
let mut v = general(&base);
v.extend(dry_media(&base));
@@ -448,6 +450,23 @@ pub fn builtin() -> Vec<BrushPreset> {
v
}
/// An owned copy of the built-in preset set, in display order (grouped by [`GROUPS`]).
pub fn builtin() -> Vec<BrushPreset> {
builtin_shared().as_ref().clone()
}
/// The built-in set shared by new sessions until one is edited.
pub fn builtin_shared() -> std::sync::Arc<Vec<BrushPreset>> {
static BUILTIN: std::sync::OnceLock<std::sync::Arc<Vec<BrushPreset>>> = std::sync::OnceLock::new();
BUILTIN
.get_or_init(|| {
#[cfg(test)]
BUILTIN_INITIALIZATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
std::sync::Arc::new(build_builtin())
})
.clone()
}
/// Find a preset by name (case-insensitive).
pub fn find<'a>(presets: &'a [BrushPreset], name: &str) -> Option<&'a BrushPreset> {
presets.iter().find(|p| p.name.eq_ignore_ascii_case(name))
@@ -457,6 +476,16 @@ pub fn find<'a>(presets: &'a [BrushPreset], name: &str) -> Option<&'a BrushPrese
mod tests {
use super::*;
#[test]
fn builtins_initialize_once_across_owned_and_shared_calls() {
let first = builtin_shared();
let owned = builtin();
let second = builtin_shared();
assert!(std::sync::Arc::ptr_eq(&first, &second));
assert_eq!(*first, owned);
assert_eq!(BUILTIN_INITIALIZATIONS.load(std::sync::atomic::Ordering::Relaxed), 1);
}
#[test]
fn builtins_are_grouped_and_unique() {
let v = builtin();
+86 -7
View File
@@ -309,13 +309,35 @@ impl PruneCursor {
}
}
#[derive(Clone, Debug)]
pub struct Surface {
/// 0 means no number assigned yet; see [`Surface::generation`].
generation: std::sync::atomic::AtomicU64,
format: PixelFormat,
default_pixel: Box<[u8]>,
tiles: BTreeMap<TileCoord, Arc<Tile>>,
}
impl Clone for Surface {
fn clone(&self) -> Self {
// Read first so the clone and the original share one number: they hold the same pixels.
let generation = self.generation();
Self {
generation: std::sync::atomic::AtomicU64::new(generation),
format: self.format,
default_pixel: self.default_pixel.clone(),
tiles: self.tiles.clone(),
}
}
}
impl std::fmt::Debug for Surface {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// The generation identifies an edit history. Independently opened copies of the same
// document should retain the same content representation.
f.debug_struct("Surface").field("format", &self.format).field("default_pixel", &self.default_pixel).field("tiles", &self.tiles).finish()
}
}
/// Use stack storage when it fits, otherwise reuse a dynamically sized sample buffer.
fn sample_buffer<'a>(channels: usize, stack: &'a mut [f32], heap: &'a mut Vec<f32>) -> &'a mut [f32] {
if let Some(samples) = stack.get_mut(..channels) {
@@ -585,7 +607,38 @@ fn decode_tile_row_rgba(fmt: &PixelFormat, t: &[u8], base: usize, dst: &mut [[f3
}
}
// Tokens identify a particular pixel state across surfaces and copy-on-write clones.
static NEXT_SURFACE_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
fn fresh_surface_generation() -> u64 {
NEXT_SURFACE_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
/// A generation slot with no number yet; the first [`Surface::generation`] read assigns one.
fn unassigned_generation() -> std::sync::atomic::AtomicU64 {
std::sync::atomic::AtomicU64::new(0)
}
impl Surface {
/// Equal generations identify the same pixel state, including across clones. Numbers are
/// assigned on first read after a mutation, so writes never touch the shared counter.
pub fn generation(&self) -> u64 {
use std::sync::atomic::Ordering::Relaxed;
let current = self.generation.load(Relaxed);
if current != 0 {
return current;
}
let fresh = fresh_surface_generation();
match self.generation.compare_exchange(0, fresh, Relaxed, Relaxed) {
Ok(_) => fresh,
Err(assigned) => assigned,
}
}
fn note_mutation(&mut self) {
*self.generation.get_mut() = 0;
}
/// Reads a region into a newly allocated buffer, returning an error instead of aborting if
/// the requested pixel buffer cannot be represented or reserved.
pub fn try_read_region(&self, r: Rect) -> Result<Vec<f32>, AllocationError> {
@@ -647,7 +700,7 @@ impl Surface {
/// Transparent/zero surface.
pub fn new(format: PixelFormat) -> Self {
Self { format, default_pixel: vec![0u8; format.bytes_per_pixel()].into_boxed_slice(), tiles: BTreeMap::new() }
Self { generation: unassigned_generation(), format, default_pixel: vec![0u8; format.bytes_per_pixel()].into_boxed_slice(), tiles: BTreeMap::new() }
}
/// Surface whose untouched pixels read as `pixel` (normalised channel values).
@@ -687,6 +740,12 @@ impl Surface {
/// Mutable access to a tile, allocating it (filled with the default pixel) or un-sharing it.
pub fn tile_mut(&mut self, c: TileCoord) -> &mut Tile {
self.note_mutation();
self.tile_for_write(c)
}
// Region writers already advanced the generation before entering their tile loop.
fn tile_for_write(&mut self, c: TileCoord) -> &mut Tile {
let fmt = self.format;
let dp = &self.default_pixel;
let arc = self.tiles.entry(c).or_insert_with(|| Arc::new(Tile::filled(&fmt, dp)));
@@ -696,6 +755,11 @@ impl Surface {
/// Fallible counterpart to [`Surface::tile_mut`]. Pixel storage is reserved before changing
/// the surface, and a shared tile is copied only after its replacement has been allocated.
pub fn try_tile_mut(&mut self, c: TileCoord) -> Result<&mut Tile, AllocationError> {
self.note_mutation();
self.try_tile_for_write(c)
}
fn try_tile_for_write(&mut self, c: TileCoord) -> Result<&mut Tile, AllocationError> {
if let Some(tile) = self.tiles.get(&c) {
drop(tile.try_bytes().map_err(AllocationError::ScratchRead)?);
}
@@ -723,6 +787,7 @@ impl Surface {
/// Writes a region using fallible pixel-tile allocations. Callers that need transactional
/// document updates should perform this on their staged document copy and commit on success.
pub fn try_write_region(&mut self, r: Rect, data: &[f32]) -> Result<(), AllocationError> {
self.note_mutation();
let n = self.channels();
let sample = self.format.sample;
let expected = (r.width() as usize).checked_mul(r.height() as usize).and_then(|v| v.checked_mul(n)).ok_or(AllocationError::SizeOverflow)?;
@@ -731,7 +796,7 @@ impl Surface {
}
for tc in r.tiles() {
let tr = tc.rect().intersect(&r);
let t = self.try_tile_mut(tc)?;
let t = self.try_tile_for_write(tc)?;
let mut target = t.bytes_mut();
let span = tr.width() as usize * n;
for y in tr.y0..tr.y1 {
@@ -804,6 +869,7 @@ impl Surface {
/// large it is, and across every surface that shares `interner`. Tiles are copy-on-write, so
/// editing one splits it off again. Returns the bytes no longer held by this surface alone.
pub fn share_uniform_tiles(&mut self, interner: &mut TileInterner) -> usize {
self.note_mutation();
let bpp = self.format.bytes_per_pixel();
let mut saved = 0;
for t in self.tiles.values_mut() {
@@ -826,6 +892,7 @@ impl Surface {
/// Drop tiles that are entirely the default pixel.
pub fn prune(&mut self) {
self.note_mutation();
let dp = self.default_pixel.as_ref();
let bpp = dp.len();
self.tiles.retain(|_, t| t.bytes().chunks_exact(bpp).any(|px| px != dp));
@@ -844,6 +911,7 @@ impl Surface {
/// before the last visited coordinate is not visited, one inserted after it is (and dropped
/// when it holds only the default pixel, which reads the same as an absent tile).
pub fn prune_batch(&mut self, cursor: &mut PruneCursor, max: usize) -> bool {
self.note_mutation();
if cursor.done {
return true;
}
@@ -1099,12 +1167,13 @@ impl Surface {
/// section that must not run another Rayon job on its stack. [`Surface::write_region_par`]
/// writes the same bytes on all cores.
pub fn write_region(&mut self, r: Rect, data: &[f32]) {
self.note_mutation();
let n = self.channels();
let w = r.width() as usize;
assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch");
let sample = self.format.sample;
for tc in r.tiles() {
write_tile(self.tile_mut(tc), tc, r, data, w, n, sample);
write_tile(self.tile_for_write(tc), tc, r, data, w, n, sample);
}
}
@@ -1114,6 +1183,7 @@ impl Surface {
/// queued Rayon job. Callers inside a `OnceLock` initializer or another section that must
/// not do that use [`Surface::write_region`].
pub fn write_region_par(&mut self, r: Rect, data: &[f32]) {
self.note_mutation();
let n = self.channels();
let w = r.width() as usize;
assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch");
@@ -1130,6 +1200,7 @@ impl Surface {
/// pixel), so they can be edited elsewhere, e.g. in parallel: `Arc::unwrap_or_clone` copies a
/// tile only if an undo snapshot still shares it. Give them back with [`Surface::put_tiles`].
pub fn take_tiles(&mut self, r: Rect) -> Vec<(TileCoord, Arc<Tile>)> {
self.note_mutation();
let fmt = self.format;
let mut blank: Option<Arc<Tile>> = None;
r.tiles()
@@ -1143,6 +1214,7 @@ impl Surface {
/// Fallible counterpart to [`Surface::take_tiles`]. Reserves the complete result and any
/// default tile before removing a tile, so a reservation failure leaves the surface intact.
pub fn try_take_tiles(&mut self, r: Rect) -> Result<Vec<(TileCoord, Arc<Tile>)>, AllocationError> {
self.note_mutation();
// Counted in u64 and checked before narrowing: on 32-bit targets the grid of a sparse
// surface's bounds can pass `usize` (and visiting it to count it takes just as long).
let count = usize::try_from(r.tile_count()).map_err(|_| AllocationError::SizeOverflow)?;
@@ -1162,6 +1234,7 @@ impl Surface {
/// Put tiles back (see [`Surface::take_tiles`]); each replaces the tile at its coordinate.
pub fn put_tiles(&mut self, tiles: impl IntoIterator<Item = (TileCoord, Arc<Tile>)>) {
self.note_mutation();
for (c, t) in tiles {
self.tiles.insert(c, t);
}
@@ -1187,6 +1260,7 @@ impl Surface {
/// Fill a rectangle with one pixel value.
pub fn fill_rect(&mut self, r: Rect, px: &[f32]) {
self.note_mutation();
let n = self.channels();
let mut enc = vec![0u8; self.format.bytes_per_pixel()];
encode_pixel(&self.format, &px[..n], &mut enc);
@@ -1202,7 +1276,7 @@ impl Surface {
self.tiles.insert(tc, t.clone());
continue;
}
let mut t = self.tile_mut(tc).bytes_mut();
let mut t = self.tile_for_write(tc).bytes_mut();
for y in tr.y0..tr.y1 {
let ly = (y - tc.ty * TILE_SIZE) as usize;
let lx0 = (tr.x0 - tc.tx * TILE_SIZE) as usize;
@@ -1224,12 +1298,13 @@ impl Surface {
/// Write interleaved encoded bytes (same format as the surface) into `r`.
pub fn write_interleaved(&mut self, r: Rect, bytes: &[u8]) {
self.note_mutation();
let bpp = self.format.bytes_per_pixel();
let w = r.width() as usize;
assert_eq!(bytes.len(), w * r.height() as usize * bpp, "interleaved length mismatch");
for tc in r.tiles() {
let tr = tc.rect().intersect(&r);
let mut t = self.tile_mut(tc).bytes_mut();
let mut t = self.tile_for_write(tc).bytes_mut();
let span = tr.width() as usize * bpp;
for y in tr.y0..tr.y1 {
let src = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * bpp;
@@ -1246,6 +1321,7 @@ impl Surface {
///
/// This enters Rayon, as [`Surface::write_region_par`] does.
pub fn try_write_interleaved(&mut self, r: Rect, bytes: &[u8]) -> Result<(), AllocationError> {
self.note_mutation();
let bpp = self.format.bytes_per_pixel();
let w = r.width() as usize;
let expected = w.checked_mul(r.height() as usize).and_then(|v| v.checked_mul(bpp)).ok_or(AllocationError::SizeOverflow)?;
@@ -1273,6 +1349,7 @@ impl Surface {
where
F: Fn(i32, i32, &mut [u8]) + Sync,
{
self.note_mutation();
self.try_prepare_rows(r, |tiles, format, default_pixel| fill_tiles(tiles, r, format, default_pixel, &fill, &|| Ok(())))
}
@@ -1282,6 +1359,7 @@ impl Surface {
where
F: Fn(i32, i32, &mut [u8]) + Sync,
{
self.note_mutation();
self.try_prepare_rows(r, |tiles, format, default_pixel| {
fill_tiles(tiles, r, format, default_pixel, &fill, &|| ctl.check().map_err(RowWriteError::Cancelled))
})
@@ -1347,7 +1425,7 @@ impl Surface {
/// `content` must hold every pixel that isn't the default one (`content_bounds`, say): only
/// tiles it reaches are kept.
pub fn translated(&self, dx: i32, dy: i32, content: Rect) -> Surface {
let mut out = Surface { format: self.format, default_pixel: self.default_pixel.clone(), tiles: BTreeMap::new() };
let mut out = Surface { generation: unassigned_generation(), format: self.format, default_pixel: self.default_pixel.clone(), tiles: BTreeMap::new() };
let sources = || self.tiles.iter().filter(move |(c, _)| !c.rect().intersect(&content).is_empty());
if dx % TILE_SIZE == 0 && dy % TILE_SIZE == 0 {
let (tx, ty) = (dx / TILE_SIZE, dy / TILE_SIZE);
@@ -1375,6 +1453,7 @@ impl Surface {
/// Applies `f` to every colour sample (not alpha), including the default pixel: a tone-curve
/// change such as linearising when a document becomes 32-bit.
pub fn map_color(&mut self, f: impl Fn(f32) -> f32) {
self.note_mutation();
let format = self.format;
let color = format.mode.color_channels();
let n = format.channels();
+8 -2
View File
@@ -221,7 +221,8 @@ impl TranslateSteps {
let builder = ShiftBuilder::new(&src, dx, dy, content);
let tiles: Vec<(TileCoord, Arc<Tile>)> =
if whole_tiles { Vec::new() } else { ShiftBuilder::sources(&src, content).map(|(c, t)| (*c, Arc::clone(t))).collect() };
let out = Surface { format: src.format, default_pixel: src.default_pixel.clone(), tiles: Default::default() };
let out =
Surface { generation: super::unassigned_generation(), format: src.format, default_pixel: src.default_pixel.clone(), tiles: Default::default() };
Self {
sources: tiles.len(),
scan: tiles.into_iter(),
@@ -274,7 +275,12 @@ impl TranslateSteps {
} else {
return Some(std::mem::replace(
&mut self.out,
Surface { format: self.src.format, default_pixel: self.src.default_pixel.clone(), tiles: Default::default() },
Surface {
generation: super::unassigned_generation(),
format: self.src.format,
default_pixel: self.src.default_pixel.clone(),
tiles: Default::default(),
},
));
}
if !more() {
+36 -5
View File
@@ -256,6 +256,7 @@ struct Registry {
}
struct Config {
query_space: fn(&Path) -> Option<(u64, u64)>,
dir: Option<PathBuf>,
/// Opened at configuration time; startup also reaps abandoned Unix files.
file: Option<Arc<ScratchFile>>,
@@ -341,7 +342,17 @@ static M: Manager = Manager {
recovering: AtomicBool::new(false),
space_unmeasured: AtomicBool::new(false),
registry: Mutex::new(Registry { cells: Vec::new(), hand: 0 }),
config: Mutex::new(Config { dir: None, file: None, last_error: None, budget: 0, paused: None, backoff: RETRY_FIRST, size_cap: None, room: None }),
config: Mutex::new(Config {
query_space: free_space,
dir: None,
file: None,
last_error: None,
budget: 0,
paused: None,
backoff: RETRY_FIRST,
size_cap: None,
room: None,
}),
evictions: AtomicU64::new(0),
reloads: AtomicU64::new(0),
written: AtomicU64::new(0),
@@ -609,11 +620,15 @@ impl Manager {
/// Record a volume's answer (`None` = it didn't say) and derive the growth limit from it.
fn apply_space(c: &mut Config, used: u64, space: Option<(u64, u64)>) {
M.space_unmeasured.store(space.is_none(), Ordering::Relaxed);
c.room = space.map(|(available, total)| used.saturating_add(available.saturating_sub(RESERVE_MIN.max(total / 20))));
c.room = space.map(|(available, total)| growth_limit(used, available, total));
store_limit(c);
M.next_space_check.store(used.saturating_add(SPACE_CHECK_EVERY), Ordering::Relaxed);
}
fn growth_limit(used: u64, available: u64, total: u64) -> u64 {
used.saturating_add(available.saturating_sub(RESERVE_MIN.max(total / 20)))
}
/// Publish the scratch size the volume and the size limit allow.
fn store_limit(c: &Config) {
let room = c.room.unwrap_or(u64::MAX);
@@ -664,13 +679,13 @@ fn run_query(dir: PathBuf, prepare: bool, done: Arc<QueryDone>) {
}
// Before measuring: writes made during the query come off the free space and must not be
// counted again on top of it. Another folder's file says nothing about this one.
let (open, used) = {
let (open, used, query_space) = {
let c = M.config();
let current = c.file.as_ref().filter(|_| c.dir.as_deref() == Some(dir.as_path()));
(prepare && current.is_none(), current.map_or(0, |f| f.used()))
(prepare && current.is_none(), current.map_or(0, |f| f.used()), c.query_space)
};
let file = open.then(|| std::fs::create_dir_all(&dir).and_then(|()| ScratchFile::create(&dir)));
let space = free_space(&dir);
let space = query_space(&dir);
// Forget it first: a caller that joined it can rely on the answer, and a later caller asks anew.
QUERIES.lock().unwrap_or_else(PoisonError::into_inner).retain(|q| !Arc::ptr_eq(&q.done, &done));
M.settle(&dir, prepare, file, used, space, &done);
@@ -1122,6 +1137,12 @@ pub fn scratch_handle_for_tests() -> Option<std::fs::File> {
M.config().file.as_ref().and_then(|f| f.duplicate_handle().ok())
}
/// Use a volume with ample space for scratch tests. Missing folders still report unknown space.
#[doc(hidden)]
pub fn use_test_volume_space() {
M.config().query_space = |dir| dir.is_dir().then_some((32 << 30, 64 << 30));
}
/// Runs at the start of every folder query, off every lock: tests stall it to simulate a dead mount.
#[doc(hidden)]
pub fn set_query_hook_for_tests(hook: Option<fn(&Path)>) {
@@ -1156,6 +1177,15 @@ fn log_error(msg: &str) {
mod tests {
use super::*;
#[test]
fn scratch_growth_preserves_the_larger_of_one_gib_or_five_percent() {
const GIB: u64 = 1 << 30;
let used = 3 * GIB;
assert_eq!(growth_limit(used, 2 * GIB, 10 * GIB), used + GIB);
assert_eq!(growth_limit(used, 7 * GIB, 100 * GIB), used + 2 * GIB);
assert_eq!(growth_limit(used, 3 * GIB, 100 * GIB), used);
}
#[cfg(windows)]
#[test]
fn free_space_keeps_a_trailing_dot_folder() {
@@ -1329,6 +1359,7 @@ mod tests {
space_unmeasured: AtomicBool::new(false),
registry: Mutex::new(Registry { cells: Vec::new(), hand: 0 }),
config: Mutex::new(Config {
query_space: free_space,
dir: Some(base.join("growth")),
file: None,
last_error: None,
+27
View File
@@ -1341,3 +1341,30 @@ fn benchmark_u16_rgba_reads() {
}
}
}
#[test]
fn generations_follow_mutations_and_remain_shared_by_unmodified_clones() {
let mut original = Surface::new(PixelFormat::RGBA8);
let initial = original.generation();
let copy = original.clone();
assert_eq!(copy.generation(), initial);
let region = Rect::new(0, 0, 1, 1);
let _ = original.read_region(region);
assert_eq!(original.generation(), initial);
original.write_pixel(0, 0, &[1.0, 0.0, 0.0, 1.0]);
assert_ne!(original.generation(), initial);
assert_eq!(copy.generation(), initial);
assert_ne!(original.read_region(region), copy.read_region(region));
let changed = original.generation();
original.map_color(|v| v * 0.5);
assert_ne!(original.generation(), changed);
let mapped = original.generation();
original.prune();
assert_ne!(original.generation(), mapped);
let before_tile = original.generation();
let old_copy = original.clone();
original.tile_mut(TileCoord { tx: 0, ty: 0 }).bytes_mut()[0] ^= 0xff;
assert_ne!(original.generation(), before_tile);
assert_eq!(old_copy.generation(), before_tile);
assert_ne!(original.read_region(region), old_copy.read_region(region));
}
+3 -1
View File
@@ -14,5 +14,7 @@ pub(crate) static SCRATCH: Mutex<()> = Mutex::new(());
/// Takes one of the locks above; a failed test that held it does not fail the next.
pub(crate) fn lock(lock: &'static Mutex<()>) -> MutexGuard<'static, ()> {
lock.lock().unwrap_or_else(PoisonError::into_inner)
let guard = lock.lock().unwrap_or_else(PoisonError::into_inner);
photocraft_raster::spill::use_test_volume_space();
guard
}
+2
View File
@@ -228,6 +228,8 @@ impl PhotocraftApp {
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
live_tokens: theme::live::LiveTokens::from_env(),
};
#[cfg(all(test, not(target_arch = "wasm32")))]
photocraft_raster::spill::use_test_volume_space();
// Saved preferences are in place before the first frame; recovery starts in upkeep.
prefs_ui::load(&mut app);
// The workspace set reads the loaded preferences (and moves the earlier saves into it).
+88 -17
View File
@@ -10,7 +10,7 @@
//! The `craft` facade features PhotoCraft enables for this: `text`, `text-font-picker`,
//! `font-manager`, `menu`, `timeline` and `print`, plus `dialogs` on native targets.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex, PoisonError};
use craft::host::target::{Backend, ShellInfo};
@@ -603,27 +603,53 @@ struct PrefSections(Mutex<Tables>);
#[derive(Default)]
struct Tables {
tables: BTreeMap<String, toml::Table>,
/// A component wrote since the last sync.
written: bool,
/// The preferences' sections as last synced, to notice a change from elsewhere (a reset,
/// the control channel).
seen: BTreeMap<String, Value>,
/// The sections a component wrote since the last sync.
written: BTreeSet<String>,
/// Each section's preference revision as last synced, to notice a change from elsewhere (a
/// reset, the control channel) without comparing the sections.
seen: BTreeMap<String, u64>,
/// How many sections a sync has read from the preferences.
#[cfg(test)]
loaded: usize,
}
impl PrefSections {
/// Writes the components' changes into the preferences, or takes a change made there.
/// Writes the sections the components wrote into the preferences, and takes the sections whose
/// preference revision moved.
fn sync(&self, session: &mut Session) {
let mut t = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if std::mem::take(&mut t.written) {
let json: BTreeMap<String, Value> = t.tables.iter().filter_map(|(key, table)| Some((key.clone(), serde_json::to_value(table).ok()?))).collect();
if session.prefs().sections != json {
session.edit_prefs(|p| p.sections = json.clone());
let written = std::mem::take(&mut t.written);
if !written.is_empty() {
let changed: Vec<(String, Value)> = written
.iter()
.filter_map(|key| Some((key.clone(), serde_json::to_value(t.tables.get(key)?).ok()?)))
.filter(|(key, value)| session.prefs().sections.get(key) != Some(value))
.collect();
if !changed.is_empty() {
session.edit_prefs(|p| p.sections.extend(changed));
}
t.seen = json;
} else if session.prefs().sections != t.seen {
let seen = session.prefs().sections.clone();
t.tables = seen.iter().filter_map(|(key, value)| Some((key.clone(), serde_json::from_value(value.clone()).ok()?))).collect();
t.seen = seen;
for key in written {
let rev = session.section_rev(&key);
t.seen.insert(key, rev);
}
}
let sections = &session.prefs().sections;
let moved: Vec<&String> = sections.keys().filter(|key| t.seen.get(*key) != Some(&session.section_rev(key))).collect();
let gone: Vec<String> = t.seen.keys().filter(|key| !sections.contains_key(*key)).cloned().collect();
for key in moved {
match serde_json::from_value(sections[key].clone()) {
Ok(table) => t.tables.insert(key.clone(), table),
Err(_) => t.tables.remove(key),
};
t.seen.insert(key.clone(), session.section_rev(key));
#[cfg(test)]
{
t.loaded += 1;
}
}
for key in gone {
t.tables.remove(&key);
t.seen.remove(&key);
}
}
}
@@ -636,7 +662,7 @@ impl SectionStore for PrefSections {
fn write(&self, key: &str, table: toml::Table) {
let mut t = self.0.lock().unwrap_or_else(PoisonError::into_inner);
t.tables.insert(key.to_owned(), table);
t.written = true;
t.written.insert(key.to_owned());
}
}
@@ -689,6 +715,51 @@ pub(crate) fn keys_pass(app: &mut PhotocraftApp, ctx: &egui::Context, input: egu
#[cfg(test)]
mod tests {
use super::*;
fn table(n: i64) -> toml::Table {
let mut t = toml::Table::new();
t.insert("n".into(), toml::Value::Integer(n));
t
}
/// A sync reads and writes only the sections that changed, one revision per section.
#[test]
fn section_sync_touches_only_changed_sections() {
let store = PrefSections::default();
let mut session = Session::new();
store.write("one", table(1));
store.write("two", table(2));
store.sync(&mut session);
assert_eq!(session.prefs().sections.len(), 2);
let (one, two) = (session.section_rev("one"), session.section_rev("two"));
let loaded = store.0.lock().unwrap().loaded;
store.sync(&mut session);
assert_eq!((session.section_rev("one"), session.section_rev("two")), (one, two));
assert_eq!(store.0.lock().unwrap().loaded, loaded, "an idle sync reads nothing");
store.write("two", table(3));
store.sync(&mut session);
assert_eq!(session.section_rev("one"), one, "a section nobody wrote keeps its revision");
assert_eq!(session.section_rev("two"), two.wrapping_add(1));
assert_eq!(store.0.lock().unwrap().loaded, loaded, "a component's own write is not read back");
session.edit_prefs(|p| {
p.sections.insert("one".into(), serde_json::json!({ "n": 9 }));
});
store.sync(&mut session);
assert_eq!(store.0.lock().unwrap().loaded, loaded + 1, "only the changed section is read");
assert_eq!(store.read("one"), Some(table(9)));
assert_eq!(store.read("two"), Some(table(3)));
session.edit_prefs(|p| {
p.sections.remove("one");
});
store.sync(&mut session);
assert_eq!(store.read("one"), None);
}
/// Every theme PhotoCraft has a palette for names a framework built-in.
#[test]
fn every_palette_theme_is_a_builtin() {
@@ -335,6 +335,8 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View,
// What the controls report for the host's pass.
let mut body_shown = tools::BodyShown::default();
let live = canvas_controls(app, ui, body.rect, host, &space, &mut turned, &mut body_shown);
// The Free Transform preview joins the picture slot after the document, which is prepared after the tools.
let transform_picture = std::mem::take(&mut body_shown.transform_picture);
// The body can run more than once in a frame; a report from any of its runs counts.
if let Some(context) = body_shown.crop.as_mut().and_then(craft::draw::ui::CropShown::take_context) {
overlay_context = Some(context);
@@ -414,6 +416,8 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View,
};
display.show_at(ui, body.rect);
}
// The moving pixels over the document, which hides the layer they come from, and under the controls.
space.paint_picture(ctx, transform_picture);
space.paint_picture(ctx, clipping);
// The grid is drawn over the picture.
if app.ui.view.shows(app.ui.view.show.pixel_grid) {
@@ -528,6 +532,7 @@ fn canvas_controls(
let session = if primary { crate::transform_tool::show_in_canvas(app, ui, rect, now) } else { crate::transform_tool::SessionShown::default() };
let session_box_shown = session.shown;
reported.transform_snapped = session.snapped;
reported.transform_picture = session.picture;
crate::cam_transform::show(app, ui, rect);
super::transform_controls::show(app, ui, rect, session_box_shown);
crate::move_box::show(app, ui, rect);
+3 -1
View File
@@ -477,6 +477,8 @@ pub(crate) struct BodyShown {
pub(crate) crop: Option<CropShown>,
/// The snap lines of the open Free Transform's box, which its canvas tool hands to the host.
pub(crate) transform_snapped: Vec<SnapLine>,
/// The open Free Transform's preview, which the body adds to the canvas's picture slot after the document.
pub(crate) transform_picture: Vec<egui::Shape>,
}
/// Borrows a family tool as the host's `dyn`.
@@ -513,7 +515,7 @@ fn with_rig<R>(
let transform_open = app.ui.transform.is_some();
let lends_transform = stand_ins && (!in_gesture || tools.gesture_pick == GesturePick::Transform);
let free_transform = if lends_transform { app.ui.transform.take() } else { None };
let BodyShown { crop: crop_shown, transform_snapped } = shown;
let BodyShown { crop: crop_shown, transform_snapped, .. } = shown;
let mut transform = free_transform.as_ref().map(|session| crate::transform_tool::canvas_tool(session, transform_snapped));
// The symmetry session moves into the pass the same way.
let symmetry_transform = if stand_ins && fam == Family::Paint { app.ui.symmetry_transform.take() } else { None };
+22 -9
View File
@@ -199,14 +199,10 @@ fn dont_save_all(_: &Value, _: &Value) -> Vec<(String, Value)> {
vec![pair("applyToAll", json!(true)), pair("choice", json!("dontSave"))]
}
/// A blend label such as "Multiply" to the Blend row's id; a string `blend_from_str` refuses passes through so the
/// A blend label such as "Multiply" to the Blend row's id; a string `parse_blend` refuses passes through so the
/// row refuses it.
fn blend_id(value: &Value) -> Value {
value
.as_str()
.and_then(photocraft_engine::commands::blend_from_str)
.map(|mode| json!(crate::panels::layers_tree::blend_key(mode).to_string()))
.unwrap_or_else(|| value.clone())
value.as_str().and_then(photocraft_engine::commands::parse_blend).map(|mode| json!(mode.key().to_string())).unwrap_or_else(|| value.clone())
}
// PLAN: the framework field ids `mode` (Fill, Stroke) and `blend` (Smart Filter) are assumed (dialogs-w22 by request).
@@ -360,9 +356,26 @@ pub(crate) fn method(app: &mut PhotocraftApp, ctx: &egui::Context, req: &Control
if !matches!(req.method.as_str(), "ui.dialog.set" | "ui.dialog.confirm" | "ui.dialog.cancel" | "ui.dialog.apply") {
return None;
}
let id = match dialog_id(host(app), p) {
Ok(id) => id,
Err(e) => return Some(err(e)),
// Keyboard Shortcuts and Menus draws outside the host: Cancel closes it; its changes go through
// `edit.keyboardShortcuts` params (#15544).
if p.get("dialog").and_then(Value::as_str) == Some(crate::prefs_ui::shortcuts::CONTROL_ID) {
return Some(match req.method.as_str() {
"ui.dialog.cancel" if crate::prefs_ui::shortcuts::cancel(app) => ok(Value::Null),
"ui.dialog.cancel" => err("Keyboard Shortcuts and Menus is not open"),
_ => err("Keyboard Shortcuts and Menus takes its changes as `edit.keyboardShortcuts` params; `ui.dialog.cancel` closes it"),
});
}
// The unsaved-changes prompt is listed as "discard" and answered by that id.
let id = if p.get("dialog").and_then(Value::as_str) == Some(crate::discard_ui::CONTROL_ID) {
match crate::discard_ui::host_id(app) {
Some(id) => id,
None => return Some(err("no unsaved-changes prompt is open")),
}
} else {
match dialog_id(host(app), p) {
Ok(id) => id,
Err(e) => return Some(err(e)),
}
};
Some(match req.method.as_str() {
"ui.dialog.set" => set(app, ctx, id, p),
+1 -1
View File
@@ -615,7 +615,7 @@ fn marquee_params(app: &PhotocraftApp, p: &Value) -> std::result::Result<(Option
fn gradient_blend_param(p: &Value) -> std::result::Result<Option<photocraft_color::BlendMode>, String> {
let Some(value) = p.get("gradientBlendMode") else { return Ok(None) };
let Some(name) = value.as_str() else { return Err("gradientBlendMode must be a blend mode name".into()) };
photocraft_engine::commands::blend_from_str(name)
photocraft_engine::commands::parse_blend(name)
.filter(|m| photocraft_color::BlendMode::LAYER_MODES.contains(m))
.map(Some)
.ok_or_else(|| format!("unknown gradient blend mode `{name}`"))
+12 -1
View File
@@ -60,12 +60,18 @@ fn rects(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
}
for dialog in app.framework.dialogs.open_dialogs() {
if let Some(r) = rect(dialog.id) {
out.insert(dialog.id.value().to_string(), r);
out.insert(dialog_key(app, dialog.id), r);
}
}
Value::Object(out)
}
/// The key `rects` stores hosted dialog `id` under: the id `dialogs` lists it by, so the unsaved-changes prompt is
/// [`crate::discard_ui::CONTROL_ID`] there too (#15544), any other dialog its host id.
pub(super) fn dialog_key(app: &PhotocraftApp, id: egui::Id) -> String {
if crate::discard_ui::host_id(app) == Some(id) { crate::discard_ui::CONTROL_ID.to_string() } else { id.value().to_string() }
}
/// The notices posted since the last pass and the toast cards on screen in every window.
fn notices(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
let mut all: Vec<Value> = app.ui.notices.iter().map(|notice| serde_json::to_value(notice).unwrap_or_default()).collect();
@@ -87,6 +93,11 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
// The framework host's dialogs in their one stack order (top last).
let mut dialogs = craft::automation::dialogs::inspect(&app.framework.dialogs);
crate::layer_style::describe_params(app, &mut dialogs);
crate::discard_ui::describe(app, &mut dialogs);
// Keyboard Shortcuts and Menus draws beneath the host's dialogs, outside the host (#15544).
if let (Some(shortcuts), Some(list)) = (crate::prefs_ui::shortcuts::inspect(app), dialogs.as_array_mut()) {
list.insert(0, shortcuts);
}
// Last frame's task bar rect, unless the bar can't show now (hidden by `ui.set` before the
// next draw).
let task_bar_rect = app.ui.task_bar_shown.filter(|_| crate::crop_task_bar::eligible(app));
+110 -4
View File
@@ -986,11 +986,11 @@ fn preferences_apply_is_available_over_control_without_closing() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
let ctx = app.ctx().clone();
let r = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "edit.preferences.interface"}));
// The Preferences window is held by the app; control addresses it by the id `ui.inspect` lists
// and the reply names it by its key.
// The Preferences window is held by the app; control addresses it by the id `ui.inspect` lists,
// and the reply names it by that id (#15544).
let listed = dialogs(&mut app, &ctx);
let window = listed.iter().find(|d| d["key"] == "preferences").expect("the Preferences window is listed");
assert_eq!(r["result"]["dialog"], window["key"], "{r}");
assert_eq!(r["result"]["dialog"], window["id"], "{r}");
let id = window["id"].clone();
let mut values = window["fields"]["values"].clone();
values["interface"]["uiScale"] = json!("200");
@@ -1354,7 +1354,8 @@ fn dirty_close_prompted() -> (Box<PhotocraftApp>, egui::Context, std::rc::Rc<std
fn answer_save(app: &mut PhotocraftApp, ctx: &egui::Context, synthetic: bool) -> Result<(), String> {
let prompt = top_dialog(app, ctx)["id"].clone();
if synthetic {
let id = craft::automation::dialogs::dialog_id(&app.framework.dialogs, &json!({"dialog": prompt})).expect("the prompt is listed");
assert_eq!(prompt, crate::discard_ui::CONTROL_ID, "the prompt is listed as discard");
let id = crate::discard_ui::host_id(app).expect("the prompt is open");
app.automation_input = true;
let r = crate::dialogs::confirm(app, ctx, id);
app.automation_input = false;
@@ -2223,3 +2224,108 @@ fn shift_right_menu_choose_rejects_bad_choices_and_sets_the_tool() {
shift_right(&mut app, "magicEraser");
assert!(inspect(&app, &ctx)["brushModeMenu"].is_null());
}
/// A fresh app with a document, as a control client finds it, and the context the control channel runs on.
fn app_with_document() -> (Box<PhotocraftApp>, egui::Context) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
app.sync_views();
let ctx = app.ctx().clone();
(app, ctx)
}
/// The id `ui.menu.invoke {id, wait: false}` replied for the dialog it opened.
fn invoked_dialog(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) -> Value {
let reply = call(app, ctx, "ui.menu.invoke", json!({"id": id, "wait": false}));
assert_eq!(reply["ok"], true, "{id}: {reply}");
crate::canvas::testing::frame(app);
reply["result"]["dialog"].clone()
}
/// #15544: Keyboard Shortcuts and Menus is listed under the id its menu items reply with, and
/// `ui.dialog.cancel` with that id closes it, so a control client is never stuck behind it.
#[test]
fn keyboard_shortcuts_is_listed_and_cancelled_by_the_id_invoke_replies() {
for command in ["edit.keyboardShortcuts", "edit.menus"] {
let (mut app, ctx) = app_with_document();
let id = invoked_dialog(&mut app, &ctx, command);
assert!(id.is_string(), "{command}: the reply names the dialog: {id}");
let listed = dialogs(&mut app, &ctx);
assert!(listed.iter().any(|d| d["id"] == id), "{command}: {id} is listed in {listed:?}");
assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"}))["ok"], false, "{command}: the dialog is modal");
let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id}));
assert_eq!(cancelled["ok"], true, "{command}: {cancelled}");
assert!(!crate::prefs_ui::shortcuts_open(&app), "{command}: Cancel closed it");
assert!(dialogs(&mut app, &ctx).is_empty());
assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id}))["ok"], false, "{command}: nothing left to cancel");
let next = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"}));
assert_eq!(next["ok"], true, "{command}: commands run again: {next}");
}
}
/// #15544: Preferences replies with the id `ui.inspect` lists it under, and cancelling that id closes it.
#[test]
fn preferences_replies_with_the_id_it_is_listed_under() {
let (mut app, ctx) = app_with_document();
let id = invoked_dialog(&mut app, &ctx, "edit.preferences.interface");
let listed = dialogs(&mut app, &ctx);
assert_eq!(listed.len(), 1, "{listed:?}");
assert_eq!(listed[0]["id"], id, "the reply is the listed id");
assert_eq!(listed[0]["key"], "preferences");
let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id}));
assert_eq!(cancelled["ok"], true, "{cancelled}");
crate::canvas::testing::frame(&mut app);
assert!(dialogs(&mut app, &ctx).is_empty());
assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"}))["ok"], true);
}
/// #15544: Select › Color Range… replies with the bare id, as every other dialog does, not a `Result` around it.
#[test]
fn color_range_replies_with_the_bare_dialog_id() {
let (mut app, ctx) = app_with_document();
let id = invoked_dialog(&mut app, &ctx, "select.colorRange");
assert!(id.is_string(), "a bare id, not a wrapper: {id}");
assert_eq!(top_dialog(&mut app, &ctx)["id"], id);
assert_eq!(top_dialog(&mut app, &ctx)["key"], "select.colorRange");
let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id}));
assert_eq!(cancelled["ok"], true, "{cancelled}");
assert!(dialogs(&mut app, &ctx).is_empty());
}
/// #15544: the unsaved-changes prompt is listed as `"discard"` with the command it holds back, the document it
/// asks about, how many are left and the choices, and `ui.dialog.confirm` / `ui.dialog.cancel` take that id
/// (docs/control-protocol.md).
#[test]
fn the_unsaved_changes_prompt_is_listed_as_discard_and_answered_by_that_id() {
let (mut app, ctx) = app_with_document();
app.run("layer.new.layer", json!({})).unwrap();
let prompt = |app: &mut PhotocraftApp| dialogs(app, &ctx).into_iter().find(|d| d["id"] == "discard");
assert!(prompt(&mut app).is_none());
// Close the changed document: the prompt is listed; Cancel keeps the document.
assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "file.close"}))["ok"], true);
crate::canvas::testing::frame(&mut app);
let listed = prompt(&mut app).unwrap_or_else(|| panic!("listed as discard: {:?}", dialogs(&mut app, &ctx)));
let name = app.session.active().unwrap().doc.name.clone();
assert_eq!(listed["fields"]["command"], "file.close");
assert_eq!(listed["fields"]["document"], name.as_str());
assert_eq!(listed["fields"]["remaining"], 1);
assert_eq!(listed["fields"]["choices"], json!(["save", "dontSave", "cancel"]));
// Its rect is keyed by that id too, as `rects` keys every hosted dialog by its `dialogs` id; others keep theirs.
let host = crate::discard_ui::host_id(&app).expect("the prompt is open");
assert_eq!(super::inspect::dialog_key(&app, host), "discard");
let other = egui::Id::unique("another dialog");
assert_eq!(super::inspect::dialog_key(&app, other), other.value().to_string());
let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"}));
assert_eq!(cancelled["ok"], true, "{cancelled}");
crate::canvas::testing::frame(&mut app);
assert!(prompt(&mut app).is_none());
assert_eq!(app.session.documents().len(), 1, "Cancel keeps the document");
assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"}))["ok"], false, "nothing left to answer");
// Don't Save by that id closes it.
assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "file.close"}))["ok"], true);
crate::canvas::testing::frame(&mut app);
let answered = call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"}));
assert_eq!(answered["ok"], true, "{answered}");
crate::canvas::testing::frame(&mut app);
assert!(app.session.documents().is_empty(), "Don't Save closed the document");
}
@@ -0,0 +1,49 @@
//! A dialog's title is its command's name without the menu item's ellipsis (#15541): Edit › Stroke…
//! opens "Stroke", as in Photoshop. Covers the dialogs that name themselves after their menu item.
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use crate::PhotocraftApp;
/// Opens one dialog.
type Open = fn(&mut PhotocraftApp);
fn harness() -> Harness<'static, Box<PhotocraftApp>> {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_max_steps(64).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro());
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 120})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
app.run("select.all", json!({})).unwrap();
app
});
h.run_steps(6);
h
}
#[test]
fn dialog_titles_drop_the_menu_ellipsis() {
let cases: [(&str, Open); 4] = [
("Stroke", |app| {
crate::stroke_ui::open(app);
}),
("New Group", |app| {
crate::new_group_ui::open(app, crate::new_group_ui::NEW_GROUP);
}),
("New Group from Layers", |app| {
crate::new_group_ui::open(app, crate::new_group_ui::FROM_LAYERS);
}),
("New Brush Preset", |app| {
crate::brush_preset_dialog::open(app, None);
}),
];
for (title, open) in cases {
let mut h = harness();
open(h.state_mut());
h.run_steps(4);
assert!(h.query_all_by_label(&format!("{title}…")).next().is_none(), "the {title} dialog's title has no ellipsis");
assert!(h.query_all_by_label(title).next().is_some(), "the dialog is titled {title}");
}
}
+1 -1
View File
@@ -660,7 +660,7 @@ fn convert_blend_mode(key: &str, value: &mut Value) {
}
let Some(mode) = value.get_mut("mode") else { return };
if let Some(blend) = mode.as_str().and_then(crate::panels::layers_tree::blend_of) {
*mode = Value::String(crate::panels::layers_tree::blend_key(blend));
*mode = Value::String(blend.key().to_string());
}
}
+6 -6
View File
@@ -6,18 +6,18 @@ use craft::ui::runtime::env::Label;
use photocraft_color::BlendMode;
use serde_json::{Map, Value, json};
use crate::panels::layers_tree::blend_key;
/// A blend-mode row `key` over the Layers panel's mode list (`group` adds Pass Through), opening on `current`.
pub(crate) fn blend_param(key: &str, label: impl Into<Label>, group: bool, current: BlendMode) -> Param {
let modes =
crate::panels::blend_options(group, current).into_iter().map(|(m, name)| (crate::panels::blend_entry(blend_key(m), m), Label::from(name))).collect();
Param::new(key, label, ParamKind::blend(modes, Some(blend_key(current))))
let modes = crate::panels::blend_options(group, current)
.into_iter()
.map(|(m, name)| (crate::panels::blend_entry(m.key().to_string(), m), Label::from(name)))
.collect();
Param::new(key, label, ParamKind::blend(modes, Some(current.key().to_string())))
}
/// The mode a blend row `key` holds; Normal when the field is missing or unreadable.
pub(crate) fn blend_mode(fields: &DialogFields, key: &str) -> BlendMode {
fields.text(key).and_then(photocraft_engine::commands::blend_from_str).unwrap_or(BlendMode::Normal)
fields.text(key).and_then(photocraft_engine::commands::parse_blend).unwrap_or(BlendMode::Normal)
}
/// The Blending section, Mode, Opacity (percent) and Preserve Transparency: the rows Fill and Stroke share.
@@ -67,7 +67,7 @@ pub fn open(app: &mut PhotocraftApp, brush: Option<&BrushSettings>) -> DialogId
// Include Color belongs to the tool settings: only with them, as in Photoshop.
Param::new("color", tl!("Include Color"), ParamKind::bool(false)).enabled_when("toolSettings", true),
];
let mut dialog = ParamDialog::command(KEY, tl!("New Brush Preset…"), rows).values(Bind::bound(fields)).ok_enabled(why.is_none());
let mut dialog = ParamDialog::command(KEY, tl!("New Brush Preset"), rows).values(Bind::bound(fields)).ok_enabled(why.is_none());
if let Some(why) = why {
dialog = dialog.ok_reason(Label::from(why));
}
+37
View File
@@ -418,6 +418,43 @@ pub(crate) fn authorize_save(app: &PhotocraftApp, from_control: bool) -> Result<
}
}
/// The id the control channel knows the prompt by: `ui.inspect` lists it under this id, and `ui.dialog.confirm` and
/// `ui.dialog.cancel` answer it by it (docs/control-protocol.md, #4920, #15544).
pub const CONTROL_ID: &str = "discard";
/// The host's id of the open question, for a control request naming [`CONTROL_ID`].
pub(crate) fn host_id(app: &PhotocraftApp) -> Option<craft::ui::dialog::DialogId> {
app.framework.dialogs.get::<UnsavedChangesDialog>().map(craft::ui::dialog::StackDialog::id)
}
/// Lists the open question in `dialogs` (the host's `ui.inspect` entries) under [`CONTROL_ID`], its fields adding the
/// command it holds back, the document it asks about, how many are left to answer, the choices `ui.dialog.confirm`
/// takes and the default one.
pub(crate) fn describe(app: &PhotocraftApp, dialogs: &mut Value) {
let Some(key) = host_id(app).map(|id| id.value().to_string()) else { return };
let Some(entry) = dialogs.as_array_mut().and_then(|list| list.iter_mut().find(|d| d["id"] == key.as_str())) else { return };
entry["id"] = json!(CONTROL_ID);
let Some(p) = app.discard.as_ref() else { return };
let name = p.docs.first().and_then(|&doc| index_of(app, doc)).and_then(|i| app.session.documents().get(i)).map(|d| d.doc.name.clone());
let reverts = p.id == "file.revert";
let choices: &[&str] = match (reverts, p.docs.len() > 1) {
(true, _) => &["dontSave", "cancel"],
(false, false) => &["save", "dontSave", "cancel"],
(false, true) => &["save", "saveAll", "dontSave", "dontSaveAll", "cancel"],
};
let described = json!({
"command": p.id,
"document": name,
"remaining": p.docs.len(),
"choices": choices,
"default": if reverts { "dontSave" } else { "save" },
});
match entry.get_mut("fields").and_then(Value::as_object_mut) {
Some(fields) => fields.extend(described.as_object().cloned().unwrap_or_default()),
None => entry["fields"] = described,
}
}
/// The command the prompt holds back and its params, for the automation policy to see before a
/// control client answers it.
pub fn pending_command(app: &PhotocraftApp) -> Option<(String, Value)> {
@@ -8,7 +8,6 @@ use serde_json::json;
use super::{COMMAND, greyed, param};
use crate::PhotocraftApp;
use crate::panels::layers_tree::blend_key;
/// The reference application's Fade Mode list, a group per row.
const GROUPS: [&[&str]; 6] = [
@@ -46,7 +45,7 @@ fn the_list_is_the_27_modes_in_the_reference_order() {
#[test]
fn the_params_doc_lists_all_27_modes_and_the_old_names_still_work() {
let options = spec_modes();
let modes: Vec<Option<BlendMode>> = options.iter().map(|o| photocraft_engine::commands::blend_from_str(o)).collect();
let modes: Vec<Option<BlendMode>> = options.iter().map(|o| photocraft_engine::commands::parse_blend(o)).collect();
assert_eq!(modes, BlendMode::LAYER_MODES.map(Some).to_vec());
for old in ["normal", "multiply", "screen", "overlay", "softLight", "hardLight", "darken", "lighten", "difference", "color", "luminosity"] {
assert!(options.iter().any(|o| o == old), "{old} is still listed");
@@ -56,12 +55,12 @@ fn the_params_doc_lists_all_27_modes_and_the_old_names_still_work() {
/// The dialog's row writes the Layers panel's keys; each one fades.
#[test]
fn every_listed_mode_fades() {
for key in BlendMode::LAYER_MODES.map(blend_key) {
for key in BlendMode::LAYER_MODES.map(|mode| mode.key().to_string()) {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();
s.execute("edit.fill", json!({"color": "#336699"})).unwrap();
let out = s.execute(COMMAND, json!({"opacity": 50, "mode": key})).unwrap();
assert_eq!(out["mode"], json!(photocraft_engine::commands::blend_from_str(&key).unwrap().label()), "{key}");
assert_eq!(out["mode"], json!(photocraft_engine::commands::parse_blend(&key).unwrap().label()), "{key}");
}
}
@@ -104,7 +103,7 @@ fn the_row_disables_the_documents_greyed_modes() {
let ParamKind::Blend { modes, .. } = &row.kind else { panic!("Mode is a blend row") };
assert_eq!(modes.len(), BlendMode::LAYER_MODES.len(), "{mode} {depth}");
for m in BlendMode::LAYER_MODES {
assert_eq!(row.option_enabled(&blend_key(m)), !want.contains(&m), "{mode} {depth}: {}", m.label());
assert_eq!(row.option_enabled(m.key()), !want.contains(&m), "{mode} {depth}: {}", m.label());
}
}
}
+1 -2
View File
@@ -7,7 +7,6 @@ use craft::ui::runtime::env::Label;
use photocraft_color::{BlendMode, ColorMode, SampleType};
use crate::PhotocraftApp;
use crate::panels::layers_tree::blend_key;
pub(crate) const COMMAND: &str = "edit.fade";
@@ -28,7 +27,7 @@ pub(crate) fn greyed(mode: ColorMode, depth: SampleType) -> &'static [BlendMode]
/// The Mode row of the Fade dialog, labelled `label`: the blend list with the active document's greyed modes disabled.
pub(crate) fn param(app: &PhotocraftApp, label: Label) -> Param {
let greyed = app.session.active().map_or(&[][..], |st| greyed(st.doc.mode, st.doc.depth));
super::blend_options::blend_param("mode", label, false, BlendMode::Normal).disabled_options(greyed.iter().map(|m| blend_key(*m)))
super::blend_options::blend_param("mode", label, false, BlendMode::Normal).disabled_options(greyed.iter().map(|m| (*m).key().to_string()))
}
#[cfg(test)]
+1 -2
View File
@@ -17,7 +17,6 @@ use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::dialogs::blend_options::{blending_params, blending_rows};
use crate::dialogs::params::{captured, open_param};
use crate::panels::layers_tree::blend_key;
/// The command of the dialog, which is also its dialog key.
pub const COMMAND: &str = "edit.fill";
@@ -64,7 +63,7 @@ fn defaults(foreground: [f32; 3], first_pattern: Option<String>) -> DialogFields
f.set("pattern", id);
}
f.set("colorAdaptation", true);
f.set("mode", blend_key(BlendMode::Normal));
f.set("mode", BlendMode::Normal.key().to_string());
f.set("opacity", 100.0);
f.set("preserveTransparency", false);
f
+1 -1
View File
@@ -33,7 +33,7 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> DialogId {
let command = if command == FROM_LAYERS { FROM_LAYERS } else { NEW_GROUP };
let name = app.session.active().map(|st| st.doc.next_layer_name("Group")).unwrap_or_else(|| "Group 1".into());
// The window title, as in Photoshop.
let title = if command == FROM_LAYERS { tl!("New Group from Layers…") } else { tl!("New Group…") };
let title = if command == FROM_LAYERS { tl!("New Group from Layers") } else { tl!("New Group") };
params::open_param(app, command, DialogFields::new(), Value::Null, move |fields: &mut DialogFields| {
let rows = vec![
Param::new("name", tl!("Name:"), ParamKind::text(name.clone())),
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more