Compare commits

...
Author SHA1 Message Date
Brandon ThomasandClaude Opus 5.5 ffd811d679 feat(save): File › Save keeps a JPEG's quality and a WebP's lossy/lossless encoding (#2399)
Opening a JPEG now estimates the quality it was saved at from its quantisation
tables (the Annex K tables of ITU-T T.81 scaled by the IJG quality curve; exact
for such tables, the closest fit otherwise). Opening a WebP records whether it
is lossless (VP8L) or lossy (VP8), and a lossy one's quality from its base
quantiser index. The settings live on the document (`Document::file_encoding`,
saved in .pcraft) and a save that asks for no quality writes the file back the
same way, as Photoshop's Save does: File › Save, Save As and Save a Copy start
there instead of the fixed codec defaults (quality 90, WebP always lossless).
An explicit quality still wins; new documents and other formats keep the
defaults. Hostile or truncated DQT/VP8 headers give no estimate, never a panic.

Refs #2399

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 04:13:51 -04:00
6a852f8852 fix(ui): correct the clipping-mask indicator orientation (#3037)
* fix(ui): correct the clipping-mask indicator orientation

* Drop the before/after screenshots from the repository

Docs screenshots stay out of the tree; the PR description keeps them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-12 02:10:18 -04:00
Dan HiornsandClaude Opus 5.5 cb1c06fc57 GPU memory budget: read installed RAM on Windows (#3189)
physical_memory() had no Windows implementation, so the wgpu
compositor's budget capped layer textures at a quarter of an assumed
16 GB on every Windows machine: too little on a large one (4 GB of a
62 GB PC's 8 GB Memory Usage allowance) and too much on an 8 GB laptop
whose integrated GPU shares that RAM. Read it with GlobalMemoryStatusEx
through winsafe, the safe binding the desktop app already uses (same
pinned version, kernel feature only).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-12 01:43:06 -04:00
f14817a5d2 Animated GIF: every frame loads into video layers (#572) (#2999)
* feat(codecs): decode every frame of an animated GIF (#572)

decode_gif_frames returns each frame composited onto the logical screen
(disposal methods applied) with its delay in milliseconds. decode still
keeps the first frame only. A damaged later frame keeps the frames before
it and marks the first with DecodeWarning::Truncated; dimensions, the
total decoded bytes and a frame cap are checked against the limits.

* feat(io): import_gif_frames hands each GIF frame over as a document (#572)

A frame at a time becomes a single-layer document, so a caller can
flatten and drop it instead of holding every frame twice.

* feat(engine): animated GIFs load every frame into video layers (#572)

New Video Layer from File, Replace Footage, Reload Frame and Video Frames
to Layers take all frames of a GIF instead of the first. The timeline rate
comes from the GIF's delays (the most common one, delays under 20 ms shown
at 100 ms as browsers do); an explicit fps still wins.

* docs: animated GIF frames in video layers (#572)

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-12 01:26:37 -04:00
skylar taylor-barrick 61b6276c78 Security: harden document exports and automation inputs (#2269)
* chore: clear strict Clippy simplifications

* security: harden web exports and generated image assets

* security: reject redirected directory bundle writes

* security: quote paths in droplet shell launchers

* security: use private ephemeral print spool files

* security: bound automation file reads and MCP input

* security: bound MCP transport requests before dispatch

* chore: keep current sample checks Clippy clean

* security: preserve safe export roots and print semantics

* security: clear non-sending print state before replay

* security: forget print send overrides between jobs

* chore: keep macOS UI tests and Clippy clean

* Test web export paths portably on Windows
2026-10-11 23:18:52 -06:00
Sir Starch b4a949225d Support automatic monitor ICC profiles on Linux X11 (#2963)
* Linux X11: detect and apply monitor ICC profiles

* Test Linux monitor ICC profile handling

* Gate display detection test to supported platforms
2026-10-12 01:17:59 -04:00
Sir Starch e8c7656150 Use each XRandR output's ICC profile in the screen picker (#2962)
* Screen picker: use each XRandR output's ICC profile

* Test X11 screen picker ICC validation
2026-10-12 01:09:03 -04:00
Sir Starch 82c58fabab Use Fontconfig for Linux font discovery (#2330) (#2961)
* Fix #2330: discover installed fonts through Fontconfig

* Fix wasm cfg for Fontconfig fallback

* Add Linux font discovery regression tests

* Reject Fontconfig matches without CJK coverage
2026-10-12 01:05:56 -04:00
5e0a6d404d Tools: Shift key switches tools by default, as in Photoshop (#3525) (#3528)
* Tools: Shift key switches tools by default, as in Photoshop (#3525)

Use Shift Key for Tool Switch is on by default in Photoshop: T keeps the
current tool, Shift+T cycles. Saved settings keep their stored value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tests: the M-key marquee cycling test sends Shift+M, the new default (#3296)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-12 00:54:41 -04:00
FinnNkandClaude Opus 5.5 962e0a2f98 feat(ui): Photoshop's New Guide: units and colour (#3553)
* feat(engine): accept Photoshop units for guide positions

view.newGuide and view.moveGuide take the position as before (a number
of pixels) or as text with a unit, as Photoshop's New Guide dialog does:
"50%", "2.5 cm", "1in", "12pt", "3pc", "100px". Percent is of the
document's width for a vertical guide and its height for a horizontal
one; points and picas follow Units & Rulers › Point Size. Fractional
positions are kept. Text that isn't a length, NaN and positions beyond
1,000,000 px are refused without recording a history step.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(engine): guides can have their own colour

Photoshop's New Guide sets a colour per guide; PhotoCraft guides only had
the Preferences guide colour. Guides now keep optional colours, keyed by
orientation and position so code that drops or reorders guide positions
(crop, artboards, guide layouts) can never move a colour onto another
guide: an unmatched guide just uses the preference colour.

view.newGuide takes an optional "color": a name from New Guide's list
(lightBlue, lightRed, green, mediumBlue, yellow, magenta, cyan, lightGray,
black) or "#rrggbb". Without one the guide uses the preference colour, as
guides dragged from the rulers always have. Moving a guide carries its
colour; deleting and clearing drop it (Clear Guides, Clear Canvas Guides,
Clear Selected Artboard Guides and New Guide Layout's Clear Existing
Guides alike); undo restores it. Guides are drawn in their own colour
(while New Guide Layout previews, the rest show the colour it will set), and .pcraft files keep it (omitted when no guide has
one, so older readers and files are unaffected). PSD export keeps guide
positions only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(ui): Photoshop's New Guide dialog: units and colour

View › Guides › New Guide… was the generic schema dialog, whose position
field was whole pixels only and had no colour. It now has its own
dialog, as in Photoshop:

- Position opens in the ruler unit ("0 cm") and takes any unit
  Photoshop's field takes ("50%", "2.5 cm", "12 pt"); a bare number is
  in the ruler unit. The last guide reopens in whatever the ruler unit
  is then ("5.08 cm").
- Color lists Custom…, Light Blue, Light Red, Green, Medium Blue,
  Yellow, Magenta, Cyan (the default), Light Gray and Black. Custom…
  shows a swatch that opens the Color Picker. The guide stores the
  chosen colour itself, so a later change of the preference guide
  colour leaves it alone.
- A position the engine refuses reopens the dialog with what was typed
  and the engine's message, as Photoshop keeps New Guide open.

Light Blue, Light Red, Medium Blue and Light Gray are new to the
catalogues; they were translated for all 16 languages from the existing
colour terms in each and would benefit from native review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(engine): one unit-suffix table for typed lengths

New Guide's position field (Unit::parse_length) and the Crop tool's size
fields (crop_size::unit_of) each kept the same table of unit suffixes.
Unit::from_suffix is now the one table: px, in or ", cm, mm, pt, pc or
pica, % and their long forms, in any case. The crop fields keep their own
number parsing (they accept arithmetic) and still refuse percent; they now
also accept "pc" for picas.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(ui): New Guide and New Guide Layout share one colour list

New Guide Layout (#2930) offered five colours of its own; New Guide offers
Photoshop's nine. Both dialogs now list the same nine (GUIDE_COLORS), in
Photoshop's order and with the same translated names. Cyan (#4affff, the
default guide colour), Magenta (#ff00ff) and Yellow (#ffcc00) take New
Guide Layout's values; Light Blue, Light Red, Green, Medium Blue, Light
Gray and Black keep New Guide's. New Guide Layout's Blue (#378ef0) and
jade Green (#00a86b) give way to Photoshop's Light Blue and Green; a colour
outside the list still shows as Custom.

GUIDE_COLORS drops its unused label column (the dialogs translate the
names), and New Guide Layout reads "#rrggbb" with prefs::parse_hex instead
of its own copy (rulers::parse_guide_color).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-12 00:46:56 -04:00
F4LCON 973e7776ea History panel: snapshots (camera button, snapshot rows) (#3545)
Part of #2966. The History panel's camera button takes a named snapshot
of the document ("Snapshot N", not a history state). Snapshots are
listed under the opening state with a thumbnail and scroll with the
states; clicking one returns the document to it as one new, undoable
state named after it. A double-click or right-click › Rename… renames
it in place, and right-click › Delete removes it. Snapshots live for the
session only, as in Photoshop.

For agents: history.newSnapshot {name?, from?: fullDocument |
mergedLayers | currentLayer}, history.selectSnapshot, renameSnapshot and
deleteSnapshot, addressed by ids that are never reused, and doc.inspect
reports snapshots.
2026-10-12 00:35:56 -04:00
skylar taylor-barrick 2bf49f10a7 Security: verify AppImage build inputs (#2270)
* security: pin and verify release build inputs

* docs: explain verified offline AppImage inputs

* security: validate executable AppImage tooling offline

* security: preserve read-only verified AppImage caches

* test: cover verified runtime downloads and cache diagnostics

* test: assert verified runtime mode and cache diagnostics

* Fix shellcheck ordering in verified download test

* Use external chmod for cache test setup
2026-10-11 22:33:26 -06:00
Valentin KleinandClaude Opus 5.5 80d646fc17 Brush: draw the smoothing string from the brush to the pointer while drawing (#3479) (#3526)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-12 00:26:04 -04:00
Scott C Hughes ee05bc833b fix(io): a fresh Metrics type layer writes no empty Txt2 stub (#3514) (#3529)
PSD export always wrote a document-level Txt2 block, and for a fresh document its
document-resources dictionary (/0) was the empty `<< >>` Photoshop never writes. Photopea's
reader fails on it ("Cannot read properties of undefined (reading '_Resources')"), so a PSD
saved with a new type layer stopped opening there.

Write the block only when it carries something: the file already had one (round-trip its pen
positions and extras), or a layer uses the Optical auto-kern mode - the one mode EngineData's
AutoKerning cannot distinguish (#1348). A plain Metrics document now writes no block, as 0.3.0
did.

Tests: text needs_txt2_only_for_optical; io fresh_metrics_text_writes_no_txt2_block.
2026-10-12 00:18:14 -04:00
UnemarsandClaude Opus 5.5 6ecad20132 Content-Aware tools: faster, cancellable at once, same pixels (P21, P22, P49) (#3395)
* Content-Aware tools: faster, cancellable at once, same pixels

#2202 matched Photoshop's Content-Aware Fill but made the perf nightly slower (#2575): P21
Content-Aware Fill 10 MP 5x, P22 Spot Healing 2.4x, P49 cancel on 24 MP 4x and over its 200 ms
budget. This keeps every result bit for bit and takes the time back:

- The solver works over the hole's bounds grown by a patch: match field, costs, votes and the
  per-target tables are kept there (nothing outside changes or is matched), the vote computes
  each target's weight once and writes into a buffer instead of a Vec per pixel.
- Colour adaptation reuses each patch's own moments (target sums kept per EM step, source sums
  per level where they pay off), summed in the same order as before.
- Exact early outs: SSD per pixel instead of per row (callers only ask "better?"), and the onion
  peel's exhaustive search starts from where the filled neighbours took their sources and stops a
  source once it can only lose (first-of-equals kept).
- PatchMatch sweeps a band in wavefronts of blocks when there are fewer bands than threads: each
  cell sees the same neighbours and random numbers (SplitMix64 skip) as in raster order.
- Parallel pyramid, valid-source and target setup; no copy of the window when there are no
  variants (fill_owned / complete_masked_owned); the job reads the window in parallel bands and
  keeps only the selection's bounds for the apply step.
- Cancellation is checked per row everywhere, also in Auto sampling and in its max flow
  (maxflow_with / grid_cut_cancellable): a 24 MP job now stops in tens of milliseconds.
- algo::par: rayon on native, sequential on wasm.

Proof: the new `content_aware_bench` example hashes every tool's output (Fill with each sampling
and adaptation option, Edit > Fill, Delete and Fill, Spot Healing x3, Patch, Content-Aware Move,
8/16/32-bit, Gray/CMYK/Lab, and the benchmarks' 10 and 24 MP fills): 117 hashes identical to
main, also with 1, 2 and 4 threads. New tests compare the onion peel with a plain scan, full and
clipped patch distances and moments, the valid-source runs with the summed-area test, thread
counts 1/3/16, in-place and copied fills, and cancellation of Auto sampling and max flow.

perf_scenarios --cpu, Ryzen 7 5800X shared with other work (load 4-7), 3 interleaved rounds:
P21 p50 295-306 -> 167-171 ms (max 342-362 -> 180-184); P22 p50 67-68 -> 38-40 ms (max 69-71 ->
40-41); P49 max 378-389 -> 54-77 ms (p50 94-110 -> 47). retouch_bench: Content-Aware Move
-47..-64 %, Spot Healing Content-Aware -40..-61 %.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Content-Aware: faster Spot Healing dabs than main with #2805, same pixels

Against main with #2805 the branch was slower for small Spot Healing dabs (size 50:
+25-30 %, single-threaded +60 %): its onion peel walked all 49 offsets of every candidate patch,
checking each against the known pixels, and had no bound at the hole's edge.

- Onion peel: the target's known pixels are gathered once (#2805), the search starts from the
  filled neighbours' shifted sources or every 16th source at the hole's edge (#2805), the limit
  a candidate must stay under is a precomputed sum (no division per pixel), and candidates are
  summed four at a time in step: their sums are independent, so the processor overlaps them.
  Each is still given up only against the best from before the four, which can only improve.
- Vote: each target's weight and match centre are taken once; a pixel's patches are visited
  over the clipped offset range, with the channel count and the colour adaptation fixed at
  compile time. Same sums, same order.
- Valid sources: sliding counts per row and stacked runs per column instead of a 7-row check
  per pixel; the k-th source is found through per-row and per-64-column counts, so no level
  but the coarsest lists them all.
- `integral` stays out of line: inlined into `synthesize` it made Create Texture slower.

Same results: `content_aware_bench -- hash` (112 cases) and `-- hash-big` (the benchmarks' 10 and
24 MP fills) equal main's, also with 1 and 3 threads; the onion peel tests (#2805's and ours)
compare with the plain scan. `content_aware_bench bench spot` runs retouch_bench's Spot Healing
dabs; with `CAF_SPOT_TYPE` (comma-separated) other types, with page faults per dab.

Ryzen 7 5800X, shared (load 5-20), interleaved with main (3af4c46a), min of rounds,
retouch_bench, all threads / one thread:
Spot Healing Content-Aware 50: 49 -> 31 / 204 -> 117 ms; 100: 62 -> 35 / 164 -> 98 ms;
200: 118 -> 67 / 250 -> 158 ms; 300: 212 -> 119 / 411 -> 285 ms. Content-Aware Move -47..-62 %
(one thread -23..-45 %). Rows that don't run this code stay within noise, except Proximity
Match 200 after the Content-Aware dabs in the same process (+8..23 %): it takes ~5800 page
faults there against ~300 on main, because main's heavier dabs left more of the heap faulted
in; alone, or after Content-Aware dabs in `bench spot`, it is equal.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-12 00:11:10 -04:00
b14037083d Brush and Pencil: hold ~ to erase, and Clear mode (#3439) (#3465)
* Brush and Pencil: hold ~ to erase

Fixes #3439. Holding ~ (the backtick key) with the Brush or Pencil makes
the strokes started while it is held erase, with that tool's own brush,
as in Photoshop; releasing it paints again and the tool never changes.
The key is a Tools › Temporary binding (tools.temporary.erase), so it
can be rebound or removed in Keyboard Shortcuts.

* Brush and Pencil: Clear painting mode, used by ~

Photoshop's Clear joins the Brush's and Pencil's Mode menus, after
Dissolve: chosen there, every stroke erases with that tool's brush until
another mode is picked. Holding ~ now puts the stroke in Clear mode too,
and the Mode menu shows Clear while the key is held. History names the
tool rather than the Eraser. Agents get it as "mode": "clear" on
paint.stroke and paint.pencil.

* Keep the Smoothing doc comment on smoothing_field

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-12 00:02:42 -04:00
MrCloudy2andClaude Opus 5.5 7e5d2ce6da Warp presets: Photoshop's Bezier control grids instead of approximations (#3444)
The 15 warp presets (Edit > Transform > Warp, smart object warps, Warp
Text) were our own closed-form approximations, up to 70 px off
Photoshop's: Arc kept its centre fixed and pulled the ends in where
Photoshop keeps the inner edge's corners and raises the middle, Flag
waved the wrong way at a third of the height, Squeeze shrank instead of
pinching.

Measured on Photoshop 27.11 (scripted renders of a grid image whose
colours encode each pixel's position, 102 cases: every preset at bend
±50 and ±100, both distortions, vertical orientation, square, wide and
tall boxes), every preset is a single bicubic Bezier patch (fits within
0.5 px). Its control grid:
- Arc: each row a circular arc of b·π around one centre, the inner edge
  keeping its chord; Arch, Bulge, Arc Lower/Upper and Shell built from
  the same arcs. Circular in pixels on any box.
- Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist: control
  points moved linearly with the bend, in box units.
- Vertical distortion scales the top and bottom rows about their
  midpoints and blends the rows between; horizontal distortion scales
  each column. Vertical orientation swaps the axes and the two
  distortions.
All 102 cases land within 1 px (median) of Photoshop. On the corpus's
Photoshop-made warped text, warp-arc-50 now spans 340x85 at (-3, 3)
against Photoshop's 350x88 at (-7, 3), where it was 278x74 at (28, 62).

Presets also convert to custom meshes exactly now (to_mesh splits the
patch instead of fitting). Tests that pinned the old shapes now assert
Photoshop's; presets_match_photoshop checks measured points.

Still open: Warp Text warps over our line box, while Photoshop uses the
type layer's stored `bounds`; with those the five corpus warp files land
within a few px (arc, flag, bulge with distortion, twist, vertical rise).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 23:56:17 -04:00
David MannandClaude Opus 5.5 bea81c2f3d Save: show save progress as Saving NN% in the status bar and tab title (#3389) (#3485)
Background saves only ever reported 0 % ("Encoding", then "Writing"), because
photocraft_io::export produced all the bytes in one call: the status bar showed an
indeterminate bar and no percentage. Now:

- photocraft_io::export_with(doc, name, opts, &Interrupt) reports encoding progress
  (export keeps its signature and calls it with Interrupt::NONE, same bytes): PSD/PSB
  per layer record and per composite band, layered TIFF the same plus its encoder
  stages, .pcraft after its previews, flat formats once the composite is rendered.
  Cancelling stops the conversion early and returns IoError::Cancelled.
- photocraft_format::atomic_write_progress writes in 8 MiB chunks and reports the
  fraction written.
- The desktop save maps encoding to 0..85 % and writing to 85..99 %, 100 % once the
  file is flushed and renamed.
- The status bar reads "Saving 45%" for a save (file name on hover), and the
  document's tab title gets " - Saving 45%" in both tab strips, as in Photoshop.
  Percentages round down so 100 % only shows when done.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-11 23:49:53 -04:00
MrCloudy2andClaude Opus 5.5 3794ad471f Color Balance: Photoshop's per-channel levels and gamma curves (#3443)
Color Balance added a share of each slider weighted by the pixel's
lightness, then (Preserve Luminosity) rescaled to the old luma. On the
corpus's Photoshop-made file (photoshop/adjustments/rgb8/color-balance.psd,
all three tones moved, Preserve Luminosity on) that was up to 43 levels
off on 99% of the pixels.

Measured on Photoshop 27.11 (scripted: a gray ramp and 16 pure colours
through each slider at ±25, ±50 and ±100, with Preserve Luminosity on
and off, plus two and three tones and two sliders at once), every
slider is a levels-and-gamma curve on each channel:
- Preserve Luminosity off: midtones is gamma 2^-a on the slider's own
  channel; shadows gamma 2^(-a/2), after a black point at 0.39·|a| when
  lowered; highlights gamma 2^(-a/2), after a white point at 1 - 0.39·a
  when raised.
- Preserve Luminosity on: midtones gamma 2^(-a/2) on its channel and
  2^(a/2) on the other two; shadows and highlights go by the differences
  between a tone's sliders: a black point at 0.39·(max - own) and a
  white point at 1 - 0.39·(own - min) per channel.
- Tones apply highlights, shadows, then midtones.
All 88 measured cases match within 1 level, except midtones +100 below
about 28 of 255 (Photoshop flattens the steepest gamma near black, by
up to 9 levels). The corpus file is now within 4 levels (mean 1.4, was
20.9).

The GPU builds the same curves into per-channel tables and uses the
Levels/Curves kernel; the old Color Balance shader case is gone.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 23:45:58 -04:00
skylar taylor-barrick d380309338 CI: restore tests, catalogs, and web size gate (#3923)
* ci: restore test and Clippy gates

* ci: keep browser wasm below size gate

* CI: restore plural catalog and MCP resource test gates

Adapted the catalog, parser, and shared-cache test fixes from PhotoCraft PR #3821 by @bommerts. The source-key test, bundled-catalog test, and MCP resource test pass locally.

* CI: expect saved native document name in CLI test

The native save path intentionally writes the output filename into the reopened bundle. Keep the pre-save Run assertion and assert r.pcraft after reopening.

* CI: compare orientation round trips without saved filenames

Native saves encode the output filename in document name. Check each expected name, then compare the remaining document fields and pixels.
2026-10-11 21:37:09 -06:00
MrCloudy2andClaude Opus 5.5 9237a8bdde PSD gradients: read the interpolation method Photoshop writes; add Smooth (#3442)
Gradient fills and gradient effects read their interpolation method from
`gs99`, a key Photoshop doesn't write. Gradient fill layers saved by
Photoshop 27.11 store it as the enum `gradientsInterpolationMethod`
(Perc, Lnr , Smoo, Gcls), so every Perceptual, Linear or Smooth gradient
opened as Classic. It shows once the fill is re-rendered (any edit):
measured against Photoshop's own composite of the saved file, a
black→white Linear fill was up to 74 levels off and Perceptual 31; both
are now within 1. `gs99` stays as a fallback.

Smooth, Photoshop's default method since 2024 (also for Gradient Map),
had no model. Measured on Photoshop 27.11 (scripted gradients on three
colour pairs), it runs straight across each segment in Oklab with its
own easing, the same curve for every pair, and Smoothness doesn't
change it. The curve fits no simple formula, so it is a 17-point
measured table. Two-stop Smooth gradients are within 2 levels (Classic
was 31 to 83 off); with three or four stops within 11 to 25 (Classic 48
to 106), as Smooth also smooths across stops in a way not modelled yet.

Corpus: no file changes status; psd-tools effect-enums.psd (Smoo
gradient effects) goes from 7.10% to 6.13% differing pixels.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 23:33:46 -04:00
David MannandClaude Opus 5.5 39aa849b47 Raw: open monochrome LinearRaw DNGs (1 sample per pixel) (#3497) (#3503)
A one-sample LinearRaw DNG (VueScan film scans, Leica Monochrom) was
rejected as "LinearRaw data with 1 samples per pixel". The DNG decoder
now accepts it and develop renders it as neutral grey: the one sample
fills all three channels, white balance, colour matrices and camera
looks do not apply, and the output is R = G = B in 16-bit ProPhoto.
io skips the preview colour fit for such files.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-11 23:33:40 -04:00
Valentin KleinandClaude Opus 5.5 c20b81b251 Autosave: best-effort cleanup after commit; sweep orphaned recovery bundles (#3489) (#3502)
save_dir removed unreferenced objects with `remove_file(..)?` after the
manifest commit, so a vanished or locked file made a completed save
(autosave) report failure. The cleanup is now best-effort.

RecoveryStore::new sweeps recovery data nothing could load or clean up:
bundles without a sidecar (crash during a first autosave) and
*.pcsave.tmp files of other processes, only once untouched for 24 hours
so another instance's in-progress save is never touched.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 23:31:23 -04:00
4030096482 perf: Edit > Clear works tile by tile on large selections (#3463) (#3482)
Clear (and the background-colour fill it does on a Background layer)
read the whole selection bounds into one float buffer, looked the
selection up in its tile map once per pixel and wrote every tile back,
single-threaded. On an 8000x6000 layer that took about 2 s (3 s on the
Background). It now edits the encoded tiles in parallel, drops fully
cleared tiles, shares one solid tile for fully covered opaque fills and
copies a tile only when a pixel in it changes. Results match the old
pass exactly; 20-110 ms on the same documents.

Fixes #3463

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 23:29:25 -04:00
siraxeandJJ 80b8deab0f Brush cursor: shaped tips trace their outline (split from #2516) (#3467)
Add the brush-outline half of #2516 on its own, so review and merge stay
small; the last-brush persistence half follows separately.

- paint: new `outline` module traces the tip shape as closed rings in
  radius units -- a computed ellipse for round tips (rotated/flattened),
  marching squares over the bitmap for sampled/stored tips, at the full
  tip or the 50 % alpha contour. Traced rings stay finite and bounded for
  hostile sizes; tested for the half-coverage contour, blank tips and
  hostile input.
- ui-egui: new `brush_cursor` picks the traced outline when the tip has a
  shape and falls back to the plain circle otherwise; `tool_cursor` gained
  the `Outline` shape (bitmap rasterisation by segment splatting, painter
  fallback on non-Windows).
- The Normal Brush Tip circle now goes through `half_coverage_radius`
  (#2744) so outline and circle agree on the real 50 % contour.

Review fixes from #2516:
- Merged main; docs/scorecard.md is main's version and was verified with
  `cargo xtask scorecard --check` (regeneration changes nothing).
- Dropped the scratch benchmark `crates/paint/examples/tmp_outline_bench.rs`
  and the two `#[ignore = "temp bench"]` tests in tool_cursor/tests.rs.

Co-authored-by: JJ <[email protected]>
2026-10-11 23:23:29 -04:00
Fabian GhenofandClaude Opus 5.5 17855ab3d1 Commands check an explicit "layer" instead of whichever layer is active (#3466)
A command whose params document "layer":id acts on that layer, but its
availability check looked at the active layer. With another layer selected,
`layer.smartObjects.replaceContents {"layer": N, "path": …}` failed with "the
active layer is a Group layer, not a smart object", although layer N is a
smart object; likewise Rasterize, Export Contents, Merge Down and the rest.
Scripts, recorded actions and MCP agents hit this whenever the selection
differs from the layer they name.

Two allow-lists covered part of it: #466 (smart filters, Edit Contents,
Convert to Layers) and #2457 (hide, show, rename with nothing selected). The
#466 check now applies to every command that documents "layer":id (210
today; the old list is a subset): the precondition runs with the named layer
as the active one, then the active layer is restored. A name that isn't a
layer of the active document falls back to the usual check, so bad ids still
fail as before. It moves from smart_cmds to Session, as it isn't specific to
smart objects any more.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 23:17:45 -04:00
Yousuf 'Jay' Philips afac33f8d7 Fix GIMP hole heading name and location (#3517) 2026-10-11 23:12:04 -04:00
DomiLuebbenandClaude Sonnet 5.5 5d8e5c138b Copy takes every selected layer, Paste recreates them (#2478) (#3394)
* fix(clipboard): Copy takes every selected layer, Paste recreates them (#2478)

With several layers selected and no pixel selection, Edit > Copy only
copied the active layer's pixels, so Paste made one layer. Photoshop
copies all selected layers and pastes them back as layers.

Copy now puts the selected layers (those no selected group already
carries, bottom-to-top) on the session clipboard as whole layers, which
Paste already knew how to recreate (paste_layers). The OS clipboard still
gets the merged pixels. A pixel selection keeps the old behaviour (the
active layer's selected pixels), and the Background in the set pastes as
an ordinary, unlocked layer, as Duplicate Layer makes it.

Tests: several layers round-trip in one undo step, a pixel selection
still copies one layer, and the Background case.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* test(clipboard): several copied layers paste into another document (#2478)

Copy two layers in one document, paste them into a 16-bit and a 32-bit
document: both arrive in order, converted to the target depth with their
own pixels, as one undo step, and the source document is untouched.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-10-11 23:08:12 -04:00
prekabrekiandprekabreki 9829d7ea37 Duplicate Layer from the menu opens a dialog for the copy's name and destination document (#3348) (#3440)
Co-authored-by: prekabreki <[email protected]>
2026-10-11 23:02:59 -04:00
f0322f74e8 fix(selection): scope Color Range to the active selection (#3313) (#3366)
* fix(selection): keep Color Range inside active selection and reject out-of-bounds samples

* fix(ui): scope Color Range dialog and canvas previews to the active selection

* test(selection): cover Color Range scoping, sampling, invert, Add and undo

* test(ui): ensure Color Range preview and pipette honor existing selection

* test(selection): avoid Debug bound when asserting prepared-query error

* test(selection): validate malformed Color Range sample orders without selection interference

* Color Range: format, and scope the OK undo test's prior selection (#3313)

The existing ok_applies_one_undo_step test picked a prior selection that
excluded the red it then expected Color Range to select; with Color Range
scoped to the active selection it now selects the red inside it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 22:52:08 -04:00
kotulskyandkotulsky 51c671c5a0 fix(selection): load shape and path thumbnails with Ctrl-click (#3449)
Load Work Path, saved path and layer path thumbnails as selections on
Ctrl/Cmd-click. Support Shift to add, Alt to subtract and Shift+Alt to
intersect, without changing the selected path or treating the click as
Save Path. Clicking the row name keeps its existing selection behavior.

Render uncached shape transparency instead of selecting the entire canvas.
Add regression tests for thumbnail hit testing, active-layer preservation,
selection combinations, undo/redo and 8/16/32-bit uncached shapes.

Co-authored-by: kotulsky <[email protected]>
2026-10-11 22:51:42 -04:00
Mr-Pearce 8f102b0222 feat(api): add file path to document.inspect (#3398) 2026-10-11 22:34:03 -04:00
piero-83 23417a60b6 fix(engine): create new layer masks at the document depth (#3359)
* fix(engine): use document depth for new pixel masks

* test(engine): check mask depth and selection coverage

* test(engine): preserve mask edits across native and PSD round trips
2026-10-11 22:30:26 -04:00
Thomas Han fb36a3fdc4 fix(presets): never overwrite preset or actions files that failed to load (#3346)
* fix(presets): never overwrite a brush group file that failed to load

A group file skipped at load (corrupt, newer version, missing tips) was replaced on the next sync with only the new presets. Remember skipped files and leave them unchanged with a warning.

* fix(presets): never overwrite an actions.json that failed to load

A corrupt, oversized or newer-version actions.json loaded as an empty list, and the next action change rewrote it with only the new actions. Remember the skip and leave the file unchanged with a warning.
2026-10-11 22:25:31 -04:00
Valentin KleinandClaude Opus 5.5 60ef9d836f Format: reopening a .pcraft shares deduplicated tiles again (#3315) (#3339)
Saves store each distinct tile once (a solid fill shares one Arc<Tile>), but
the loader fetched, decompressed and charged max_total_bytes once per tile
reference and gave every coordinate its own copy. A solid canvas above
~65536² (8-bit) failed to reopen with "bundle expands beyond 17179869184
bytes", and smaller ones lost their sharing (a solid 30000² 32-bit document
went from about 1 MB to about 14 GB in memory).

The loader now keeps the decoded tiles of the current load by sample type and
content hash: each distinct tile is decoded, hash-checked and charged against
the budget once, and every further reference gets the same copy-on-write Arc.
The budget still bounds distinct decoded bytes; extra references cost a map
lookup and an Arc clone each, bounded by max_manifest_bytes.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 22:21:45 -04:00
alexanderalber 980cf05be4 Group effects follow their children's effects, not just their pixels (#3274) (#3326)
A group's effect region and the empty-tile check were computed from
layer_bounds, which for a group is the union of its children's pixels.
A child's outside stroke reaching past that region was cut off on the
canvas (GPU) and in tiled CPU renders, and the group's drop shadow
followed the cut shape.

New photocraft_compose::effect_source_bounds: for a group, the children
grown by their own effect reach. Used by compose::effect_region,
compose::empty_in and gpu::bounds::effect_region.

generated with Claude Code
2026-10-11 22:20:23 -04:00
538c5020b2 New Document: a real Recent category of recently created documents (#3131) (#3135)
File › New › Recent was a hard-coded pair of presets plus Clipboard. Each
document created with the dialog now records its settings (size,
resolution, mode, depth, background, display units) through the new
document.recent.add command: newest first, equal entries collapsed, at most
20, persisted with the presets (a damaged entry is dropped on load, the rest
kept). The Recent tab lists Clipboard, those documents, then the defaults
they don't cover; a click restores every setting, a double-click creates,
and the grid scrolls past three rows. document.recent.list exposes the list
to agents; creation stays in file.new. Closes scorecard row UI-217-12.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 22:17:17 -04:00
KnottyDyesandClaude Opus 5.5 48c1721470 MCP: command_batch says it is not atomic, and the docs explain recovery (#3338)
Agents read the tool description, not docs/mcp.md, and the command_batch
description only said it stops at the first error. It now also says the
steps run in order and that earlier successful steps stay applied: there
is no rollback. docs/mcp.md gives the stop_on_error default and a recovery
recipe: inspect with doc_inspect, undo with edit.undo once per history
entry (undo does not reverse files written to disk), or experiment on a
copy made with image.duplicate or history.newDocument. A test checks the
listed description.


Claude-Session: https://claude.ai/code/session_01BSB7fMQUccqFQekksDGWpo

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 22:10:12 -04:00
myangaa1 27222cf4b7 Let [ shrink the brush to 1 px (#3229) (#3332)
`[` steps the brush size down by 25 %, rounded: from 2 px that is 1.6,
which rounds back to 2, so the key never reached 1 px and pixel artists
had to type the size. `]` already grows by at least a pixel; `[` now
shrinks by at least a pixel the same way, still never below 1 px.
2026-10-11 22:05:50 -04:00
0e2c34af3e Vanishing Point: on-canvas plane editor with Create/Edit Plane, grid and paste (#3122) (#3133)
Filter > Vanishing Point now opens a dialog mode on the canvas instead of
the generic parameter dialog:

- Create Plane (C): four clicks, in any order, make a plane (corners are
  normalised clockwise from the top-left, the order paste expects).
- Edit Plane (V): drag corner nodes, or edge nodes to slide an edge along
  the plane's own perspective; click a plane to select it, Delete removes it.
- The plane grid is drawn at the Grid Size, in the accent colour when the
  plane is valid, warning yellow when its perspective is doubtful and red
  (outline only) when the quad isn't convex (VpPlane::check).
- With an image on the clipboard the selected plane previews it pasted in
  perspective; drag to move it, Width sets its size, New Layer renders it
  on a new layer. OK / Enter runs filter.vanishingPoint with the planes and
  the paste as one history step; the control channel drives the same
  session through {"ui": {...}}.

The engine now rejects a drawn plane whose corners don't form a convex
quad (bow-tie, dented) instead of warping along it.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 22:02:04 -04:00
Valentin KleinandClaude Opus 5.5 638b5cc4e6 Clone Source: W/H link and overlay blend modes (#3298) (#3310)
The Clone Source panel gets Photoshop's W/H chain (Maintain aspect
ratio): with it on, a new W or H scales the other by the same factor.
cloneSource.set takes "linked" and cloneSource.list reports it.

The overlay's Darken, Lighten and Difference modes were stored but
never drawn. draw_clone_preview now blends the source with the
composite under the brush (clone_source::overlay_blend), so Difference
goes black where source and image line up.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 21:40:37 -04:00
7fd53f0e3f Puppet Warp: the mesh follows the object outline (#3105) (#3117)
The mesh was every square grid cell touching the layer's opaque pixels:
a staircase up to a cell outside the shape, and shapes closer than about
a cell shared cells, so pinning one dragged the other along.

build_mesh now traces the outline of the opaque region grown (or shrunk)
by Expansion from a signed distance field, simplifies it (Douglas-Peucker,
corners kept), splits its sides to the Density spacing, fills the inside
with a triangular lattice and triangulates the points (Bowyer-Watson
Delaunay, outline sides recovered by midpoint splits), keeping the
triangles inside the outline. Separate shapes get separate meshes, so an
unpinned one stays put, as in Photoshop. Vertices are numbered in reverse
Cuthill-McKee order to keep the solver's banded factor narrow, and the
density's spacing counts the grown region so a large Expansion on a small
layer no longer builds tens of thousands of vertices.

Scorecard TOOL-214-6 done; docs/gaps.md G7 updated.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 21:40:06 -04:00
9a9d23d258 Levels: black, gray and white point eyedroppers (#3116) (#3128)
* Curves: pencil mode, Smooth and Edit points (#3088)

The Curves editor (Image > Adjustments dialog and the adjustment layer's
Properties panel) gains Photoshop's "Edit points to modify the curve" and
"Draw to modify the curve" buttons plus Smooth, with tooltips. A drawn
curve is a 256-level map per channel, evaluated piecewise-linearly.

- doc: Adjustment::Curves gains `pencil` (serde default), with
  curve_map / curve_map_outputs helpers.
- compose: curve_map_lut / curve_lut_mode for drawn curves.
- engine: curves params take `pencil` and `smooth`; channels accept
  256-level maps; switching modes draws the spline into maps or fits up to
  16 points to the drawing. Eyedroppers fit points first.
- io: the PSD `curv` map flag (first byte, psd-tools `is_map`) was read
  as padding, so pencil curves from Photoshop were misparsed; they are now
  read and written as 256-byte maps, and smart-filter Curves use `Mpng`.
- scorecard UI-217-15 note updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Properties: Curves adjustment layers get the black/gray/white eyedroppers (#3110)

The Set Black/Neutral Gray/White Point pickers existed only in the
Image > Adjustments > Curves dialog (#873). The Properties editor of a
Curves adjustment layer now has them too (layer_picker.rs): with one
armed, a click on the image runs one layer.setAdjustment with the new
`eyedropper` param, which samples the image below the layer (the layer
hidden, like its Properties histogram) at the Eyedropper's Sample Size,
so a repeated click keeps the curve and the edit is one undoable,
recordable step agents can send directly. Esc, another tool or another
layer disarms it; ui.pointer and ui.inspect (`layerPicker`) cover it.

Scorecard UI-217-15 is done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Levels: black, gray and white point eyedroppers (#3116)

Image > Adjustments > Levels and a Levels adjustment layer's Properties
panel get Photoshop's Set Black/Neutral Gray/White Point eyedroppers.
Black/white move each channel's input black/white to the sample, gray
sets each channel's midtone gamma so the sample turns neutral at its
luma (Grayscale: composite input, no gray). The engine takes the same
`eyedropper` param as Curves on image.adjustments.levels,
layer.newAdjustmentLayer.levels and layer.setAdjustment.

On a smart object, image.adjustments.levels/curves with `eyedropper`
now record the resolved adjustment as the smart filter instead of the
raw sample, which re-rendered as an identity (#3127).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Merge upstream/main: Curves in new compose/gpu HDR tests gets the pencil field (#3088)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 21:27:08 -04:00
Nigel Ihza Firdausy 6f6d2ea467 fix(format): save the target file name in native bundle manifests (#3312) (#3319) 2026-10-11 21:26:13 -04:00
Valentin KleinandClaude Opus 5.5 6e9ba6511d Format: admit the declared .pcraft canvas before loading it (#2935) (#3295)
* Format: admit the declared .pcraft canvas before loading it (#2935)

A .pcraft manifest's canvas size was copied into the Document unchecked, so
a few bytes of JSON could declare a 300000x300000 (or u32::MAX) canvas that
the CPU reduction, thumbnails and display textures then work against in
proportion to its area.

The loader now refuses an empty canvas, a side above 300000 (Photoshop's PSB
limit, as for PSD and file.new) and an area above 4 gigapixels, right after
reading the manifest and before any tile or blob is decoded. Both limits are
LoadOptions fields so trusted callers can change them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Format: admit every canvas the app can create on .pcraft load (#2935)

The default pixel budget was 2^32 (65536 x 65536), but file.new, Canvas
Size, Image Size with Resample off and PSB import all reach 300000 x
300000, so a document a user could create and save would not reopen.
The default is now the full 300000^2 PSB canvas; the side limit still
refuses anything larger, and callers handling untrusted files can lower
either budget. Loading stays proportional to the file: layers keep only
the tiles the bundle holds, so a huge declared canvas allocates nothing
for its area.

A compile-time assert in document_preset_cmds ties file.new's
MAX_DIMENSION to the loader's defaults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 21:22:11 -04:00
ee9c9ef159 Properties: Curves adjustment layers get the black/gray/white eyedroppers (#3110) (#3115)
* Curves: pencil mode, Smooth and Edit points (#3088)

The Curves editor (Image > Adjustments dialog and the adjustment layer's
Properties panel) gains Photoshop's "Edit points to modify the curve" and
"Draw to modify the curve" buttons plus Smooth, with tooltips. A drawn
curve is a 256-level map per channel, evaluated piecewise-linearly.

- doc: Adjustment::Curves gains `pencil` (serde default), with
  curve_map / curve_map_outputs helpers.
- compose: curve_map_lut / curve_lut_mode for drawn curves.
- engine: curves params take `pencil` and `smooth`; channels accept
  256-level maps; switching modes draws the spline into maps or fits up to
  16 points to the drawing. Eyedroppers fit points first.
- io: the PSD `curv` map flag (first byte, psd-tools `is_map`) was read
  as padding, so pencil curves from Photoshop were misparsed; they are now
  read and written as 256-byte maps, and smart-filter Curves use `Mpng`.
- scorecard UI-217-15 note updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Properties: Curves adjustment layers get the black/gray/white eyedroppers (#3110)

The Set Black/Neutral Gray/White Point pickers existed only in the
Image > Adjustments > Curves dialog (#873). The Properties editor of a
Curves adjustment layer now has them too (layer_picker.rs): with one
armed, a click on the image runs one layer.setAdjustment with the new
`eyedropper` param, which samples the image below the layer (the layer
hidden, like its Properties histogram) at the Eyedropper's Sample Size,
so a repeated click keeps the curve and the edit is one undoable,
recordable step agents can send directly. Esc, another tool or another
layer disarms it; ui.pointer and ui.inspect (`layerPicker`) cover it.

Scorecard UI-217-15 is done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Merge upstream/main: Curves in new compose/gpu HDR tests gets the pencil field (#3088)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 21:16:28 -04:00
Valentin KleinandClaude Opus 5.5 59820ecafb Codecs: decode PNM straight into the budgeted output buffer (#2938) (#3291)
Limits::max_alloc budgets the decoded pixel buffer, but the PNM decoder
collected one u32 per sample first (4x an 8-bit image, plus a u16 copy
for 16-bit) and PFM built a Vec<f32> beside the output bytes. Samples are
now rescaled and written straight into the native-endian output buffer
(reserved fallibly), so the only header-sized allocation is the one
Limits::check already charged.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 21:16:07 -04:00
Sir Starch 04e7e7d7f8 fix(io): smooth PSD gradients no longer overshoot their stops (#3028) (#3285)
The Catmull-Rom tangents used for Smoothness are derived from the
neighbouring stops, so a segment between two equal-coloured stops (a
flat plateau) picked up a non-zero tangent and dipped below its own
colour. In the Gradient Map from #3028 the 27%-53% plateau (#1c1c1c)
rendered about 19/255 too dark.

Bound each interpolated channel to the range of the segment's two end
colours. Smoothness still bends the ramp, but never invents a colour
outside the segment, so plateaus stay exactly flat.

The regression test uses the four stop positions and grey values from
the issue (synthetic, no artwork) and fails without the clamp.
2026-10-11 21:14:28 -04:00
aba9b2b4ef Curves: pencil mode, Smooth and Edit points (#3088) (#3108)
* Curves: pencil mode, Smooth and Edit points (#3088)

The Curves editor (Image > Adjustments dialog and the adjustment layer's
Properties panel) gains Photoshop's "Edit points to modify the curve" and
"Draw to modify the curve" buttons plus Smooth, with tooltips. A drawn
curve is a 256-level map per channel, evaluated piecewise-linearly.

- doc: Adjustment::Curves gains `pencil` (serde default), with
  curve_map / curve_map_outputs helpers.
- compose: curve_map_lut / curve_lut_mode for drawn curves.
- engine: curves params take `pencil` and `smooth`; channels accept
  256-level maps; switching modes draws the spline into maps or fits up to
  16 points to the drawing. Eyedroppers fit points first.
- io: the PSD `curv` map flag (first byte, psd-tools `is_map`) was read
  as padding, so pencil curves from Photoshop were misparsed; they are now
  read and written as 256-byte maps, and smart-filter Curves use `Mpng`.
- scorecard UI-217-15 note updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Merge upstream/main: Curves in new compose/gpu HDR tests gets the pencil field (#3088)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 21:05:58 -04:00
1051265f75 Type: fall back to installed Khmer, Lao and Burmese fonts (#218) (#3259)
Text in these scripts drew .notdef boxes although the OS had a font for
them. Detection was never the problem: the system font scan loads them,
and asking for one by name shapes correctly. The fallback stack is a
list of family names intersected with the installed fonts, and it had no
entry for any of the three, so an installed Khmer, Lao or Burmese font
could not be reached from a Latin-only face.

- photocraft-text: KHMER_FAMILIES, LAO_FAMILIES and MYANMAR_FAMILIES join
  fallback_candidates next to THAI_FAMILIES; the web build's served-font
  scripts gain Khmr, Laoo and Mymr (with their ranges and languages).
- photocraft-ui-egui: the UI's lazy loader had one non-CJK slot (Thai).
  It becomes a LazyScript slot table, so the three scripts are data
  rather than a third and fourth copy of the same state machine.
- Tests assert detection and selection separately, so a future failure
  names its layer, and skip when a machine lacks the script's font.

Co-authored-by: Raccoon <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 21:03:22 -04:00
b0e555c60f automation: export layers, data sets and CSVs through the granted roots (#3216) (#3230)
* automation: doc.place reads a file through the read root (#2810)

file.placeEmbedded takes an ambient path, so automation refuses it and an
agent could not place a file into the open document at all. doc.place
resolves the path beneath the read root the way doc.open does and hands the
bytes it already read to the public file_cmds::place_bytes, so the existing
cap-std rules stay the only path rules: no new scope logic, and the ambient
command keeps its refusal. Trusted-local callers still run the command.

* automation: export layers, data sets and CSVs through the roots (#3216)

file.export.layersToFiles and file.export.dataSetsAsFiles take an ambient
dir, file.import.variableDataSets an ambient path, so all three are refused
in automation even for files inside the granted roots, and an agent could
not export a single file or a data set at all.

Both halves already existed: the engine writes bytes it has just encoded
(save_doc is encode + write_file, and the data-set exporter encodes with
photocraft_io::export before writing), and the automation side already
holds a write capability — AuthorizedWorkspace::export_sequence creates the
directory, refuses to overwrite, accepts only single-component names and
removes every file it created when a step fails, which is what Render Video
uses. So each command body moves behind the same sink callback
render_video_with takes: the command keeps writing the bytes it is handed
to its dir, the new methods write the very same bytes through the root, and
the two implementations cannot drift.

---------

Co-authored-by: switch87 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 21:01:26 -04:00
Vikram Bhaskaran 2af2cec6ea Edit > Copy takes a targeted layer mask, so masks travel between layers and documents (#2928) (#3267) 2026-10-11 20:50:49 -04:00
6de37ce7f0 Interface: an Enable Animations preference (#3273) (#3276)
Preferences › Interface › Enable animations (interface.enableAnimations, on by
default). Off, prefs_ui::sync_animations sets egui's animation_time to 0 and
scroll_animation to none in both the dark and light styles, so menus, popups
and collapsing sections change at once and scroll areas jump. It is re-applied
each frame, so a theme change keeps it. Translated in all 16 catalogs; the
scorecard row UI-217-10 goes to partial.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 20:34:58 -04:00
6d08ae6400 Layers panel: dragging the vector mask to the Trash asks to delete just the mask (#3119) (#3125)
* Layers panel: Shift+Plus/Minus cycle blend modes; effects dropped on the Trash are deleted (#3102)

- blend_keys.rs: Shift+Plus / Shift+Minus step to the next / previous blend mode, wrapping:
  the brush's mode with the Brush or Pencil (tools.setBrush), the Gradient's with the Gradient
  tool, otherwise the active layer's (layer.setProps; groups include Pass Through, the
  Background is left alone). One undo step per press.
- panels.rs: an effect row dragged onto the footer's Delete button deletes that effect, the
  "Effects" row clears the whole style (layer.layerStyle.clear).
- engine: layer.layerStyle.clear takes an optional "effect" index ("Delete Effect" step);
  bad indices and layers return Err.
- scorecard UI-217-14 -> done (its wheel, footer drop and thumbnail checker parts were already
  on main via #1961, #965).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Layers panel: Shift+Plus/Minus step the blend mode on a German layout too (#3102)

On layouts with a key of its own for `+` (German, Italian, Spanish) Shift+`+`
types `*`, which egui has no key for, so egui-winit reports the physical key:
`]` on German. That matched Shift+] (Increase Brush Hardness) before the blend
keys ever saw it. Shift+`-` types `_` and arrives as the physical `/`.

shortcuts::layout_symbols now turns such a fallback press (Shift, the key equal
to its physical key, not a digit, next to the text `*` or `_`) into `+` / `-`
before any shortcut is dispatched. A US Shift+] still arrives as `}` and keeps
raising the hardness; US Shift+8 (`*`) stays a digit for the opacity keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Shortcuts: Ö / # are the brush keys on a German layout (#3109)

Photoshop's German shortcuts step the brush size with Ö / # and the hardness
with Shift+Ö / Shift+#, since [ and ] need AltGr there (and that press carries
Alt on the Mac and Windows, which the shortcut match rejects). egui can't name
ö or #, so they arrived as the physical ; and \ and matched nothing; Shift+#
types ' and arrived as Quote.

shortcuts::layout_symbols (from #3102) now reads a table of typed symbol and
Shift: ö / Ö -> [, # / ' -> ], next to * -> + and _ -> -. It runs at the top of
shortcuts::handle (unless a text field has focus), so Liquify's and the
Magnetic Lasso's [ ] get the German keys too. Only presses whose key egui took
from the physical key or from that very text change, and never digits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Layers panel: a mask dragged onto the Trash asks to apply or delete it (#3113)

A drag that started on a layer's mask thumbnail dragged the whole row, and
dropping it on the Trash deleted the layer. Now a drag from the pixel mask
thumbnail (where it was drawn last frame) drags the mask: it shows a "Layer
Mask" ghost and starts neither a layer reorder nor a cross-document transfer.
Dropped on the Trash it opens Photoshop's prompt "Apply mask to layer before
removing?" with Apply (layer.layerMask.apply, greyed out where it can't run),
Delete (layer.layerMask.delete) and Cancel. Clicking the Trash still deletes
the targeted mask at once (#2197).

The prompt (mask_trash_prompt.rs) is an ordinary dialog: ui.dialog.confirm
applies, ui.dialog.set {"choice": "delete"} + confirm deletes, cancel keeps.
Two new strings in all 16 catalogs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Layers panel: dragging the vector mask to the Trash asks to delete just the mask (#3119)

A drag that started on a row's vector mask thumbnail picked up the whole
layer row, so dropping it on the Trash deleted the layer. The mask drag
from #3113 now covers both thumbnails: a vector mask dropped on the Trash
opens Photoshop's "Delete the vector mask?" (OK / Cancel), and OK runs
layer.vectorMask.delete. Clicks on the thumbnail are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Brush keys: layout table plus bracket-position fallback for every layout (#3109)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* layout_keys: drop unused field, fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 20:29:36 -04:00
Valentin KleinandClaude Opus 5.5 c450e755ae PNG export: Indexed Color keeps the document resolution (#3047) (#3271)
The palette PNG encoder never wrote a pHYs chunk, so an Indexed Color
document saved as PNG reopened at 72 ppi while the RGB path kept its
resolution. encode_png_indexed now takes an optional dpi and the flat
exporter passes the document resolution under the same embed_metadata
rule as the ordinary PNG encoder. Save for Web PNG-8 is unchanged.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 20:12:44 -04:00
872d3df2c5 Layers panel: a mask dragged onto the Trash asks to apply or delete it (#3113) (#3118)
* Layers panel: Shift+Plus/Minus cycle blend modes; effects dropped on the Trash are deleted (#3102)

- blend_keys.rs: Shift+Plus / Shift+Minus step to the next / previous blend mode, wrapping:
  the brush's mode with the Brush or Pencil (tools.setBrush), the Gradient's with the Gradient
  tool, otherwise the active layer's (layer.setProps; groups include Pass Through, the
  Background is left alone). One undo step per press.
- panels.rs: an effect row dragged onto the footer's Delete button deletes that effect, the
  "Effects" row clears the whole style (layer.layerStyle.clear).
- engine: layer.layerStyle.clear takes an optional "effect" index ("Delete Effect" step);
  bad indices and layers return Err.
- scorecard UI-217-14 -> done (its wheel, footer drop and thumbnail checker parts were already
  on main via #1961, #965).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Layers panel: Shift+Plus/Minus step the blend mode on a German layout too (#3102)

On layouts with a key of its own for `+` (German, Italian, Spanish) Shift+`+`
types `*`, which egui has no key for, so egui-winit reports the physical key:
`]` on German. That matched Shift+] (Increase Brush Hardness) before the blend
keys ever saw it. Shift+`-` types `_` and arrives as the physical `/`.

shortcuts::layout_symbols now turns such a fallback press (Shift, the key equal
to its physical key, not a digit, next to the text `*` or `_`) into `+` / `-`
before any shortcut is dispatched. A US Shift+] still arrives as `}` and keeps
raising the hardness; US Shift+8 (`*`) stays a digit for the opacity keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Shortcuts: Ö / # are the brush keys on a German layout (#3109)

Photoshop's German shortcuts step the brush size with Ö / # and the hardness
with Shift+Ö / Shift+#, since [ and ] need AltGr there (and that press carries
Alt on the Mac and Windows, which the shortcut match rejects). egui can't name
ö or #, so they arrived as the physical ; and \ and matched nothing; Shift+#
types ' and arrived as Quote.

shortcuts::layout_symbols (from #3102) now reads a table of typed symbol and
Shift: ö / Ö -> [, # / ' -> ], next to * -> + and _ -> -. It runs at the top of
shortcuts::handle (unless a text field has focus), so Liquify's and the
Magnetic Lasso's [ ] get the German keys too. Only presses whose key egui took
from the physical key or from that very text change, and never digits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Layers panel: a mask dragged onto the Trash asks to apply or delete it (#3113)

A drag that started on a layer's mask thumbnail dragged the whole row, and
dropping it on the Trash deleted the layer. Now a drag from the pixel mask
thumbnail (where it was drawn last frame) drags the mask: it shows a "Layer
Mask" ghost and starts neither a layer reorder nor a cross-document transfer.
Dropped on the Trash it opens Photoshop's prompt "Apply mask to layer before
removing?" with Apply (layer.layerMask.apply, greyed out where it can't run),
Delete (layer.layerMask.delete) and Cancel. Clicking the Trash still deletes
the targeted mask at once (#2197).

The prompt (mask_trash_prompt.rs) is an ordinary dialog: ui.dialog.confirm
applies, ui.dialog.set {"choice": "delete"} + confirm deletes, cancel keeps.
Two new strings in all 16 catalogs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Brush keys: layout table plus bracket-position fallback for every layout (#3109)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* layout_keys: drop unused field, fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 20:11:43 -04:00
Gert Pellin - GPE 5a907b110e test(paint): pin the retouch dab footprint to the Full Size ring (#1761) (#3258)
A dab never paints past radius + 0.5 px from its centre, at any hardness:
the half pixel is the anti-aliased edge of dab_coverage. A hard tip does
reach the ring; softer tips fade out inside it, which is the falloff
working as intended.
2026-10-11 20:02:35 -04:00
Dan HiornsandClaude Opus 5.5 599aea0086 Liquify: the brush fades to nothing at its edge at every Density (#2606) (#3241)
A dab's strength was (1 - density) + density * (1 - t^2)^2, so at the
brush rim it stopped at 1 - Density instead of 0: half strength at the
default Density 50, a hard-edged disc at 0. Forward Warp then moved the
pixels just inside the brush and left those just outside, tearing the
image along every dab's circle; with a dab every fifth of the radius
the tears stacked into the sawtooth edges and stripes in #2606. Density
was also backwards: 0 gave the strongest, flattest brush.

`falloff` now blends (1 - t^2)^3 (Density 0: the effect in the centre,
feathered) toward (1 - t^4)^2 (Density 100: most of the brush), both 1
at the centre and 0 with a flat slope at the rim, as Photoshop's
Density reads. Every Liquify brush tool and Freeze/Thaw use it.

Replaying saved Liquify strokes (the command, smart filters) now gives
the smooth result for the same strokes.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 20:01:39 -04:00
f1059f1885 Shortcuts: layout-independent brush keys, Photoshop's German keys plus a fallback for all layouts (#3109) (#3112)
* Layers panel: Shift+Plus/Minus cycle blend modes; effects dropped on the Trash are deleted (#3102)

- blend_keys.rs: Shift+Plus / Shift+Minus step to the next / previous blend mode, wrapping:
  the brush's mode with the Brush or Pencil (tools.setBrush), the Gradient's with the Gradient
  tool, otherwise the active layer's (layer.setProps; groups include Pass Through, the
  Background is left alone). One undo step per press.
- panels.rs: an effect row dragged onto the footer's Delete button deletes that effect, the
  "Effects" row clears the whole style (layer.layerStyle.clear).
- engine: layer.layerStyle.clear takes an optional "effect" index ("Delete Effect" step);
  bad indices and layers return Err.
- scorecard UI-217-14 -> done (its wheel, footer drop and thumbnail checker parts were already
  on main via #1961, #965).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Layers panel: Shift+Plus/Minus step the blend mode on a German layout too (#3102)

On layouts with a key of its own for `+` (German, Italian, Spanish) Shift+`+`
types `*`, which egui has no key for, so egui-winit reports the physical key:
`]` on German. That matched Shift+] (Increase Brush Hardness) before the blend
keys ever saw it. Shift+`-` types `_` and arrives as the physical `/`.

shortcuts::layout_symbols now turns such a fallback press (Shift, the key equal
to its physical key, not a digit, next to the text `*` or `_`) into `+` / `-`
before any shortcut is dispatched. A US Shift+] still arrives as `}` and keeps
raising the hardness; US Shift+8 (`*`) stays a digit for the opacity keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Shortcuts: Ö / # are the brush keys on a German layout (#3109)

Photoshop's German shortcuts step the brush size with Ö / # and the hardness
with Shift+Ö / Shift+#, since [ and ] need AltGr there (and that press carries
Alt on the Mac and Windows, which the shortcut match rejects). egui can't name
ö or #, so they arrived as the physical ; and \ and matched nothing; Shift+#
types ' and arrived as Quote.

shortcuts::layout_symbols (from #3102) now reads a table of typed symbol and
Shift: ö / Ö -> [, # / ' -> ], next to * -> + and _ -> -. It runs at the top of
shortcuts::handle (unless a text field has focus), so Liquify's and the
Magnetic Lasso's [ ] get the German keys too. Only presses whose key egui took
from the physical key or from that very text change, and never digits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Brush keys: layout table plus bracket-position fallback for every layout (#3109)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* layout_keys: drop unused field, fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Drop shortcuts::layout_symbols left by the merge: layout_keys::apply replaces it

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 19:55:11 -04:00
14733b5223 Moving type keeps its rendering: Artboards to Files no longer drops PSD text (#3218)
translate_layer re-rendered a type layer on every whole-pixel move. For type
from a PSD that replaced Photoshop's rendering with PhotoCraft's: paragraphs
re-wrapped, and text in a font that isn't installed vanished. Artboards to
Files moves each board to the origin this way, so a Steam store template's
"How to use" artboard lost its "Hello!" title. The Move tool, nudges, layer
comps and moving artboards went through the same path.

A whole-pixel move now shifts the rendered pixels, as smart objects and the
Move tool's live preview already do, and moves the TySh position with
photocraft_text::psd::translate_tysh: only the transform's translation
bytes change, so the rest of Photoshop's type data stays byte for byte. Type
with nothing rendered yet is still rendered.

On that template, 17 of 20 artboards now match Photoshop's own composite
exactly (the "How to use" board went from a mean difference of 4.5 to 0.02);
the remaining differences are shape layers (same cause, separate path) and
pre-existing 1-level rounding on two smart objects.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 19:46:29 -04:00
4ab61338ca Layers panel: Shift+Plus/Minus cycle blend modes; effects dropped on the Trash are deleted (#3102) (#3106)
* Layers panel: Shift+Plus/Minus cycle blend modes; effects dropped on the Trash are deleted (#3102)

- blend_keys.rs: Shift+Plus / Shift+Minus step to the next / previous blend mode, wrapping:
  the brush's mode with the Brush or Pencil (tools.setBrush), the Gradient's with the Gradient
  tool, otherwise the active layer's (layer.setProps; groups include Pass Through, the
  Background is left alone). One undo step per press.
- panels.rs: an effect row dragged onto the footer's Delete button deletes that effect, the
  "Effects" row clears the whole style (layer.layerStyle.clear).
- engine: layer.layerStyle.clear takes an optional "effect" index ("Delete Effect" step);
  bad indices and layers return Err.
- scorecard UI-217-14 -> done (its wheel, footer drop and thumbnail checker parts were already
  on main via #1961, #965).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Layers panel: Shift+Plus/Minus step the blend mode on a German layout too (#3102)

On layouts with a key of its own for `+` (German, Italian, Spanish) Shift+`+`
types `*`, which egui has no key for, so egui-winit reports the physical key:
`]` on German. That matched Shift+] (Increase Brush Hardness) before the blend
keys ever saw it. Shift+`-` types `_` and arrives as the physical `/`.

shortcuts::layout_symbols now turns such a fallback press (Shift, the key equal
to its physical key, not a digit, next to the text `*` or `_`) into `+` / `-`
before any shortcut is dispatched. A US Shift+] still arrives as `}` and keeps
raising the hardness; US Shift+8 (`*`) stays a digit for the opacity keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 19:45:42 -04:00
886372812d automation: doc.place reads a file through the read root (#2810) (#3215)
file.placeEmbedded takes an ambient path, so automation refuses it and an
agent could not place a file into the open document at all. doc.place
resolves the path beneath the read root the way doc.open does and hands the
bytes it already read to the public file_cmds::place_bytes, so the existing
cap-std rules stay the only path rules: no new scope logic, and the ambient
command keeps its refusal. Trusted-local callers still run the command.

Co-authored-by: switch87 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 19:33:29 -04:00
42ee0d9675 Content-Aware Scale: transform box with live preview (#3096) (#3103)
* Content-Aware Scale: transform box with live preview (#3096)

Edit > Content-Aware Scale opened a parameter dialog. Photoshop has no
dialog: it puts a scale-only transform box on the layer (or the
selection's bounds). The menu now opens that box.

- The box reuses Free Transform. Corner and edge drags scale and an
  inside drag moves; dragging outside does not rotate, Cmd does not
  skew or distort, and the Warp switch and the Transform modes are off.
- The options bar shows X/Y and W/H, then Amount, Protect (an alpha
  channel) and Protect skin tones.
- The live preview runs the command's own carving
  (ContentAwareScalePreview) on a 384 px copy on a worker thread. A
  run for a box that has changed since is cancelled after 150 ms, and
  the latest result is drawn through the box.
- Enter runs edit.contentAwareScale with the box's size and its new
  x/y params as one history step; Esc cancels.
- With params the command still runs directly.

Scorecard TOOL-214-7: done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Content-Aware Move's transform box: set the new content_aware field

#3095 (Transform On Drop) builds a TransformSession by hand; this PR adds
content_aware to it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 19:33:15 -04:00
Dan HiornsandClaude Opus 5.5 c18ee8c88b Tests: one GPU harness at a time in every GPU test binary (WARP crash) (#3212)
On Windows, GPU UI test binaries crashed with STATUS_ACCESS_VIOLATION
whenever two of their tests ran at once: arbitrary_rotation_preview 3
runs in 4 on main, and color_managed_canvas, crop_default_mode,
drag_preview_canvas and full_res_preview at random. egui_kittest
prefers a CPU adapter, which on Windows is WARP over DX12, and a dump
puts the fault inside d3d10warp.dll with two WARP devices rendering on
parallel test threads. Bare egui harnesses with no PhotoCraft code
crash the same way, and Vulkan or GL never does. CI's Windows runners
have no GPU, so they run on WARP too.

Three binaries already held a per-binary lock for the same class of
driver bug (Mesa llvmpipe and RADV, #194; libvulkan with NVIDIA and
lavapipe). That lock now lives once in photocraft-testkit
(`gpu_lock`, with the reasons) and every test in the twelve GPU test
binaries without it takes it on its first line. Under nextest each
test is its own process and the lock is free.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 19:27:26 -04:00
imSlicedBread 92baf43103 Preserve whitespace in OpenRaster layer names (#3207) 2026-10-11 19:17:06 -04:00
aa1febaffb Keep fitted Camera Raw colour during tuning and crop Nikon D5100 borders (#3201)
* raw: fit non-DNG colour to the camera's embedded JPEG

* raw: preserve fitted Camera Raw look and crop D5100 borders

---------

Co-authored-by: Gert Pellin <[email protected]>
Co-authored-by: optimalbytee <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 19:12:19 -04:00
d706acdde9 Numeric fields: typed units, scrubby labels, double-click reset (#3099) (#3100)
* Numeric fields: typed units, scrubby labels, double-click reset (#3099)

- Value fields convert a unit typed after a number into the field's unit
  (1in, 2.54cm, 72pt, 1pica/pc, 10px, 50%) at the active document's
  resolution; Image Size and New Document use their own resolution. A
  unit that can't convert, or bad arithmetic, keeps the old value.
- widgets::scrub_label: dragging a label scrubs the value field right
  after it on its row (a step a point, Shift x10, Alt a tenth as fast),
  with a horizontal-resize cursor. Used by options-bar labels, slider
  rows and the Character panel icons. A slider row reports the scrub as
  one drag, so adjustment edits coalesce into one history step.
- Adjustment slider rows with a known default and filter dialog sliders
  reset on double-click, like Color Balance already did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Scrubby labels: drag-only, not focusable, so Tab skips them

Sense::drag() is focusable in egui 0.36, so every scrubby label became an
extra Tab stop and tab_focus_reveals_the_final_narrow_tool_option could no
longer reach the last tool option.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 19:09:08 -04:00
Valentin KleinandClaude Opus 5.5 661ba806d1 Content-Aware Move: Transform On Drop (#3071) (#3095)
* Content-Aware Move: Transform On Drop (#3071)

The Content-Aware Move tool gains Photoshop's Transform On Drop checkbox. With it on, the drop
puts a transform box on the moved patch (the Free Transform box's handles, limited to move,
scale and rotate); Enter, the check button or a double-click computes the content-aware blend
with the transformed patch, Esc or the cancel button drops the whole move. The document is
untouched until the commit, so the move stays one History step.

Engine: paint.contentAwareMove takes scaleX / scaleY (%, 1..10000, negative flips) and rotate
(degrees, clockwise) about the selection's centre before the offset, validated (Err, not a
panic, for non-finite, out-of-range or off-canvas placements). The content and the selection's
shape are resampled through the inverse map on float samples (any depth); the selection is
transformed with the content. A plain move keeps the old, exact code path.

UI: cam_transform.rs holds the box (UiState.cam_transform, view state); the option is remembered
in ToolOptions and settable with ui.set camTransformOnDrop; ui.inspect reports camTransform.

Scorecard TOOL-213-4 stays partial: no live preview of the blended result yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tests: keep Transform On Drop cases in the Content-Aware Move test, not Patch (#3071)

paint.patch takes no scaleX/scaleY/rotate, so those cases (which only
paint.contentAwareMove rejects) failed patch_fails_gracefully. They are
already covered by content_aware_move_fails_gracefully.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 18:44:10 -04:00
Valentin KleinandClaude Opus 5.5 8584e5dbf8 Actions: Last Filter is recorded as the filter it repeated (#3089) (#3091)
filter.lastFilter was journaled as itself, so a recorded Ctrl+F step
looked up the playing session's last filter: it failed in a new session
("no filter applied yet") and applied whatever filter ran last otherwise.
dispatch now runs Last Filter as the filter it repeats, so that filter is
journaled, recorded, faded and run as a job, as Transform Again records
its transform (#1440).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 18:28:51 -04:00
Scott C Hughes 4e334b479b test(gradient): guard the on-canvas midpoint diamond drag (#3172) (#3512)
The midpoint diamond's hit-test and drag were untested, so a regression there would go
unnoticed. Add a repro that drags the diamond and asserts the midpoint follows (and no stop
is added). The path works on current main; this is coverage, not a behaviour change.
2026-10-11 18:20:26 -04:00
Valentin KleinandClaude Opus 5.5 f0d3156ad6 Freeform Pen: Alt-clicks draw straight segments; Cmd/Ctrl is Direct Selection with the new pens (#3085) (#3087)
* Tools: Freeform Pen and Curvature Pen (#1054)

The Pen flyout (P / Shift+P) now holds Pen, Freeform Pen and Curvature Pen.

Freeform Pen: a drag draws freehand; on release the trace is fitted with
cubic Beziers within the options bar's Curve Fit (default 2 px) by
photocraft_vector::trace::fit_trace (Schneider, "An Algorithm for
Automatically Fitting Digitized Curves", Graphics Gems 1990, the fitting
Make Work Path already uses), keeping turns sharper than 60 degrees as
corners. Releasing on the start point closes the path.

Curvature Pen: each click adds a smooth point and the path runs through
every point (Catmull-Rom style handles from
photocraft_vector::edit::curvature_knots); dragging a point moves it,
double-clicking toggles corner/smooth, clicking the first point closes,
Enter/Esc finish and Backspace removes the last point, as with the Pen.

Both commit through the Pen's path: a shape layer in Shape mode, else the
targeted vector mask, else the work path, as one History step.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Freeform Pen: Alt-clicks draw straight segments; Cmd/Ctrl is Direct Selection with the new pens (#3085)

The Freeform Pen now draws through lasso_ui, as the Lasso does: Alt held at
the release keeps the path open, each Alt-click adds a straight segment,
releasing Alt with the button down goes on freehand, with it up finishes
the path; clicking the start point closes it. freeform_finish fits each
freehand run on its own and joins the runs with straight segments between
corner anchors. Cmd/Ctrl with the Freeform or Curvature Pen is the
temporary Direct Selection, as with the Pen (#790); it finishes a path in
progress first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 18:16:39 -04:00
Scott C Hughes 3455234537 fix(crop): the crop box's own Undo/Redo (#3145) (#3510)
While a crop is pending, Edit > Undo/Redo now steps the *box*, not the document, as
Photoshop does. The frame's history lives on CropState; crop_ui::is_enabled/intercept route
the commands for every caller (menu, shortcut, control channel, MCP), and committing or
cancelling a crop clears it.

The ratio-field input is PR #3175. The handle-drag jitter is left as-is on main (whose
live crop-handle snapping, snap_ui::live_crop_handle, deliberately redesigns that path).

Test: edit_undo_steps_the_crop_box_not_the_document. cargo test -p photocraft-ui-egui --lib crop: 101 pass.
2026-10-11 18:10:38 -04:00
optimalbyteeandoptimalbytee da3f5ffd54 Optimise computed brush coverage and native raster row writes (#3098)
* Speed up raster writes with contiguous sample rows

* Specialise coverage rasterisation for computed brush tips

---------

Co-authored-by: optimalbytee <[email protected]>
2026-10-11 18:08:44 -04:00
0142b24fcb Artboards: a board moved past the canvas origin grows the canvas left/up (#3070) (#3073)
fit_canvas only grew the canvas to the boards' right/bottom edges, so a
board moved left of or above the origin (Move tool drag, layer.translate,
layer.artboard.set with negative x/y) stayed partly off-canvas. It now
shifts the whole document (boards, contents, guides, paths...) right/down
by the overhang via image_cmds::translate_doc and grows the canvas, inside
the move's undo step, like Photoshop's artboard documents.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 18:05:58 -04:00
2b2bb45870 Color Picker: no bigger than Photoshop's (532 × 376 points, was 682 × 437), buttons sized to their labels (#3500)
* Color Picker: no bigger than Photoshop's (532 x 376 points, was 682 x 437)

A 200-point colour field, 42-point component fields, buttons at their
width rather than stretched, smaller new/current swatches and tighter
spacing. Every control stays; the 16-point window padding stays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Color Picker: actions as wide as the longest label, not the column (133 points, was 160)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 18:03:29 -04:00
4fe6dc6764 Layers: the New Layer dialog (Layer › New › Layer…, ⇧⌘N) (#3104)
* Layers: clip groups follow New Layer, Arrange, Reorder and Delete (#2203)

Adding, moving or deleting layers never touched Layer::clipped, so a
new layer above a clipping base split its group and became the base of
the layers clipped above it, and moving or deleting a base left its
clipped layers clipping to whatever ended up below them.

The new clip_group module applies Photoshop's rules, measured on #2203:
a layer added or moved joins the clip group it lands in; a clipped
layer moved stays clipped while it still sits on a clip group; the
layers clipped to a base that moves away or is deleted are released;
and a clipped run left with nothing below it is released. They are
applied by layer.new.layer (new clipToPrevious param, Photoshop's Use
Previous Layer to Create Clipping Mask), layer.arrange.*, layer.moveTo
(Layers panel drags, batches and ⌥-drag copies) and layer.delete.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Layers: the New Layer dialog (Layer › New › Layer…, ⇧⌘N)

Layer › New › Layer… made a layer straight away. It now opens
Photoshop's New Layer dialog: Name (focused and selected), Use Previous
Layer to Create Clipping Mask, Color, Mode, Opacity, and Fill with
<mode>-neutral color, greyed out with "(No neutral color exists for
<mode> mode.)" for modes that have none. OK makes the layer in one
history step.

layer.new.layer gains mode, opacity, color and fillNeutral params
(new engine module new_layer.rs) beside clipToPrevious. The neutral
colors (white for the darkening modes and Divide, black for the
lightening and difference modes, 50% gray for the light modes) are
checked by compositing at 8, 16 and 32 bits.

As in Photoshop, the Layers panel's New Layer button still makes a
layer at once and ⌥-click opens the dialog; commands with params
(automation, Actions, MCP) never show it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 18:01:12 -04:00
b26256faee Type: triple-click selects a line, quadruple a paragraph, five clicks all text (#3493) (#3496)
While editing type, a run of clicks at one spot now selects like Photoshop:
two clicks the word, three the laid-out line (a column in vertical type),
four the paragraph up to its hard return, five all text; the next quick
click starts over with a caret. egui stops counting at three, so the Type
tool keeps its own count per layer (next_click_count) and the ranges come
from a pure helper over the text and its layout (click_selection).

Scorecard TYPE-218-8 is done; docs/gaps.md G8 updated.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 17:55:18 -04:00
Valentin KleinandClaude Opus 5.5 d7e2f171f3 Actions: a command that runs other commands is recorded once (#3067) (#3072)
* Actions: a command that runs other commands is recorded once (#3067)

A journaled command that called Session::execute journaled the inner
calls as well as its own entry, so a recorded action replayed them twice
(Straighten Layer: rotate + crop, then Straighten again). dispatch now
remembers the journal length when a command starts; when a replayable
command succeeds its entry replaces the entries of the commands it ran.
Edit > Transform > Again is not replayable and keeps its concrete transform.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Actions: Again on a Copy records its steps; taken-back steps are dropped (#3067)

- edit.transform.againCopy is not replayable, like Transform Again (#1440):
  it records layer.duplicate + edit.transform, which play in a session
  that never ran a transform. With one layer selected the duplicate names
  no layer id, so it plays on any document.
- compound, Again on a Copy and Frame from Layers take back what they ran
  when they fail; they now also drop those commands from the journal, so
  recording does not replay an undone edit.
- Recording pauses while a replayable command runs: a script that plays an
  action no longer flushes its earlier steps into the recording and loses
  its own entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 17:53:25 -04:00
d523405627 scorecard: FILE-216-5 save-path tests are in the tree (#3476)
Every existing save path (layered TIFF, print PDF, ACO/ASE, .shc, Smart
Filters in PSD, atomic-save failure) already has a save-and-read-back
test; SVG and Photoshop PDF have no writer yet (FILE-215-10).

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 17:48:52 -04:00
cc772a03c1 fix(export): quick-export every selected layer as a separate PNG (#3462)
Enable Layers context-menu Quick Export as PNG for a multi-layer selection. Capture each selected source before showing one destination prompt and write separate numbered PNG siblings with sanitized layer names, without silently replacing existing sibling files.

Add actual PNG encoding and cancellation regressions, preserve the captured selection when the dialog is open, and update context-menu enablement tests.

Co-authored-by: kotulsky <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 17:48:03 -04:00
Valentin KleinandClaude Opus 5.5 8f7cf009bb Type Mask: Shift/Alt at commit add to or subtract from the selection; no Layers row for the working text (#3036) (#3069)
* Tools: Horizontal and Vertical Type Mask (#1055)

The Type flyout (T, Shift+T cycle) gains Vertical Type Mask and Horizontal
Type Mask, in Photoshop's order. They type like the Type tools, with the
canvas under Quick Mask's colour and the glyphs clear while editing. On
commit the glyph coverage replaces the selection; no layer is left behind
and the whole session is one "Type Mask" history step. Escape always
cancels and leaves the selection unchanged.

The commit runs a new engine command, type.createSelection: a type layer's
glyphs (optionally removing that layer, the tools' hidden working text) or
type.create's keys directly, with new/add/subtract/intersect and an
anti-aliasing override. type.create's layer building is shared through
type_cmds::new_text_layer.

Original dashed-T icons (ATTRIBUTION.md), tool label translations in every
catalog, README tool list and the gaps/parity docs updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Type Mask: Shift/Alt at commit combine with the selection; no Layers row for the working text (#3036)

Committing a Type Mask with Shift held (click outside, Cmd+Shift+Enter or
the check button) adds the glyphs to the selection, Alt subtracts them and
Shift+Alt intersects, as in Photoshop; without modifiers it still replaces.
The Layers panel no longer lists the hidden working text layer while a
Type Mask session is open (layer_tree_ui::panel_rows).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 17:43:56 -04:00
Timothy DalyandClaude Opus 5.5 5e5a0f6d2d Layers: clip groups follow New Layer, Arrange, Reorder and Delete (#2203) (#3090)
Adding, moving or deleting layers never touched Layer::clipped, so a
new layer above a clipping base split its group and became the base of
the layers clipped above it, and moving or deleting a base left its
clipped layers clipping to whatever ended up below them.

The new clip_group module applies Photoshop's rules, measured on #2203:
a layer added or moved joins the clip group it lands in; a clipped
layer moved stays clipped while it still sits on a clip group; the
layers clipped to a base that moves away or is deleted are released;
and a clipped run left with nothing below it is released. They are
applied by layer.new.layer (new clipToPrevious param, Photoshop's Use
Previous Layer to Create Clipping Mask), layer.arrange.*, layer.moveTo
(Layers panel drags, batches and ⌥-drag copies) and layer.delete.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 17:43:30 -04:00
kotulskyandkotulsky 7c2e8c3d95 fix(actions): fill the resizable panel with the step list (#3460)
Remove the 320-point list height cap and nested dock scrolling. Reserve space for the footer while filling the available panel height.

Add a panel-height regression test and check recording autoscroll against the visible footer instead of a fixed coordinate.

Co-authored-by: kotulsky <[email protected]>
2026-10-11 17:41:04 -04:00
buivanvu94 17167e27d6 fix(transform): identity transform makes feathered selection edges translucent (#3079) (#3159) 2026-10-11 17:31:25 -04:00
Valentin KleinandClaude Opus 5.5 911f69d7b5 Artboard tool: '+' buttons add a board beside the selected one; ⇧ keeps proportions (#3033) (#3046)
* Tools: Artboard tool (#2858)

Photoshop's Artboard tool in the Move flyout (V, ⇧V cycles Move ↔ Artboard):
dragging on an empty spot draws a new board (`layer.new.artboard`), clicking a
board selects it, dragging it moves it with its contents, and the selected
board's edge and corner handles resize it (`layer.artboard.set`,
moveContents: false). Each gesture is one undo step. Options bar: Size preset,
W/H, Make Portrait, Make Landscape, Add New Artboard. Original toolbar glyph
(assets/icons/artboard.svg, ATTRIBUTION.md row).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Artboard tool: '+' buttons add a board beside the selected one; ⇧ keeps proportions (#3033)

With the Artboard tool, the selected board shows a "+" button beside each
side. A click adds an empty board of the same size (background and preset
copied) on that side, the 100 px artboard gap away and past any board in
the way; ⌥-click adds a copy with its contents instead. A board left of or
above the canvas origin shifts the whole document right/down and grows the
canvas, so it stays visible. Both go through the new engine command
`layer.artboard.addBeside` {layer?, side, duplicate} (one undo step).

⇧ while dragging a corner handle keeps the board's aspect ratio: the
opposite corner stays and the board scales by the larger axis factor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 17:30:35 -04:00
72bf3e13b6 i18n(cs): translate the dynamic labels the Czech catalog was missing (#3454)
* i18n(cs): translate dynamic labels the literal scanner can't see

The Czech catalog covered every enforced key (menus, tl! literals, blend
modes, preferences) but not the labels built at run time: filter and
Filter Gallery parameter names and choices humanized from their keys,
Camera Raw controls, the Flame / Picture Frame / Tree render filters,
measurement columns, file info fields and the macOS application menu.
Those showed in English under Czech.

Adds 853 entries (2,441 -> 3,294) for keys that the other catalogs
already translate and that still exist in the code. Existing entries are
unchanged. Translated clean-room from the plain meaning of the English
labels, with the terminology already used in cs.tsv; no proprietary
localisation was consulted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): credit the Czech catalog in ATTRIBUTION.md and LICENSE-translations.txt

cs.tsv is a bundled translation asset but had no row in ATTRIBUTION.md
and was not named in LICENSE-translations.txt. Add both, worded like the
other catalogs (PhotoCraft contributors, original translations, MIT OR
Apache-2.0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): terminology review fixes for the new dynamic labels

Changes from an independent review pass over the added block:

- "Create By" (De-Interlace: how the missing lines are made) reads
  "Vytvořit pomocí", not "Vytvořil" (author)
- luminance is "jas" in Camera Raw, as in the existing "Luminance" label
  ("Detail jasu", "HSL – jas", "Jas")
- slider labels are nouns, like the existing "Redukce šumu" (Reduce Color
  Noise, Sharpen Details, Lighten Grout)
- grain and flame choices agree in gender with their neighbours; "Shadow"
  matches "Highlight"/"Světla" as "Stíny"; "At" is "Pozice"; "Water Paper"
  is "Mokrý papír"; "Leaves" is "listů" everywhere

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* contributors: add my own people.toml entry

Own entry only, as AGENTS.md describes: credited by the name on my public
GitHub profile (sync_github_name), otherwise by @username.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): drop three rows that main added in the meantime

"Columns", "Margin" and "Automatic" were added to cs.tsv on main while this
branch was open, with the same translations, so the appended block no longer
needs them (the catalog has no duplicate keys).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n (cs): translate two strings that are still missing from cs.tsv

"Drag (lasso) or click points (polygonal) ..." and "The current gradient
(pick one in Window > Gradients)" exist in the other catalogs but not yet
in cs.tsv on main.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* i18n (cs): translate context-menu, channel and layer-style labels

These labels are rendered through tl!() with a variable, so the literal-based coverage test does not see them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Localize Czech status messages and notice wrappers

Translate shell messages before interpolating file names and engine errors.
Use the existing plural API for counted objects and preserve English fallback.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Localize Czech UI labels and hardware information

Translate brush controls, accessibility names and rasterization prompts at
render sites. Preserve adapter, driver and display/profile identifiers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Localize Czech composed labels and distinguish Navigator zoom

Translate profile, preset and shortcut messages before interpolation, and use
a Navigator context for the zoom level. Keep shortcut warning state separate
from translated text and preserve document names and shortcut codes.
Cover remaining visible counts and add rendering/glyph regression tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fix Czech UI localization review follow-ups

Keep copied System Info and API diagnostics in English while localizing the
on-screen text. Avoid double translation of accessible names, honor command-id
shortcut labels, and translate stored auto backend values only for display.

Refine Czech warning punctuation and catalog wording, simplify template blocks,
and correct the documented catalog count to 3,522 rows. Add four regression tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* people.toml: keep axlecoffee's sync_github_name with their entry

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Losminek <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 17:23:27 -04:00
buivanvu94 680518b425 fix(image): arbitrary canvas rotation moves position-locked children in groups (#3078) (#3155) 2026-10-11 17:21:19 -04:00
Valentin KleinandClaude Opus 5.5 55c1847f89 Paths: Stroke Path with any brush-based tool and Simulate Pressure (#2978) (#3039)
* Paths: Stroke Path with any brush-based tool and Simulate Pressure (#2978)

path.stroke now takes every brush-based tool of Photoshop's Stroke Path
dialog: besides the Brush, Pencil and Eraser it renders itself, the
Background Eraser, Clone and Pattern Stamp, Healing and Spot Healing
Brush, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color
Replacement and Mixer Brush run their paint.* command along each
subpath, in one history step, with only path.stroke journalled.

simulatePressure resamples each subpath and ramps the pressure from 0 at
its start to full at the middle and back to 0 at its end, so a brush
whose size follows pen pressure tapers at both ends.

The Stroke Path dialog (Pen/Path Selection right-click menu, the Paths
panel row menu, Alt-click on the panel's Stroke button) asks for the
tool and Simulate Pressure, as in Photoshop. Scorecard TOOL-214-11 done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Automation: classify path.stroke's params as a document vector path (#2978)

The new Stroke Path params doc says the tools run "along the path", which
registry_filesystem_path_params_are_classified reads as a possible host
file path. path.stroke strokes a document path and forwards only to
paint.* commands that take no files, so it joins the vector-path list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 17:18:39 -04:00
6a4c48aea7 fix(warp): Perspective Warp moves only the selected part of a linked mask (#3083) (#3148)
With a selection, Perspective Warp moved only the selected pixels but warped
the whole linked layer mask, so unselected pixels changed visibility. The mask
now follows the same split as Free Transform (#205): the selected region of a
linked mask moves with the pixels and the rest stays put.


Claude-Session: https://claude.ai/code/session_015Vepmc5pt6MikxbsDj21Bu

Co-authored-by: Leel Wasanatha <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 17:16:55 -04:00
David MannandClaude Opus 5.5 9e378277e8 Crop tool: switching to another tool commits the pending crop (#3368) (#3451)
Leaving the Crop tool kept a drawn frame pending, so picking another tool
from the toolbar or by its key left the image uncropped. As in Photoshop,
the per-frame crop sync now commits a drawn frame (as Enter would) once the
current tool is no longer Crop; the untouched default frame is still just
dropped. The pen's eraser end and a gesture in progress keep the frame
pending; held tools (Space, Cmd) never change the current tool.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-11 17:16:18 -04:00
Diego Chagas 18f787f04d SVG: say when text had no font to use instead of opening an empty drawing (#3168)
With no font installed at all (a bare CI image, a minimal container) usvg drops every <text>
while parsing, so nothing reaches the conversion and the file opened as "nothing to draw". The
parser now notes when a drawing has text and the font database has no faces, and the import
warns that the text needs a font and was dropped. Fixes the FreeBSD svg test, which has been red
since the reader landed.
2026-10-11 17:09:21 -04:00
prekabrekiandprekabreki e762c784fb Keep transform controls with moved selected pixels (#3402) (#3436)
Co-authored-by: prekabreki <[email protected]>
2026-10-11 17:09:15 -04:00
Sir Starch d9ecd60fb3 automation: deny edit.installedProfiles, it scans the OS profile folders (#3763)
edit.installedProfiles lists ICC profiles from the OS and user profile
directories, so automation must not run it, the same as the other
profile commands that read ambient paths. Without a policy the registry
check in workspace::tests fails, which has kept CI red on main since the
command landed.
2026-10-11 17:08:47 -04:00
Sir Starch 40d7e6a1d8 fix(history): read pixels from locked history states (#3076) (#3186) 2026-10-11 17:06:15 -04:00
prekabrekiandprekabreki f9e94aa535 Keep the Color panel selected when switching themes (#3371) (#3433)
* Keep the Color panel selected when switching themes (#3371)

* Scope Camera Raw color checks to its settings panel (#3371)

---------

Co-authored-by: prekabreki <[email protected]>
2026-10-11 17:02:38 -04:00
Sir Starch 2bbe6c3fdc fix(filters): process untouched Reveal All masks (#3082) (#3156) 2026-10-11 16:59:55 -04:00
David MannandClaude Opus 5.5 cee1033112 Properties: a new adjustment or fill layer shows its settings, not its mask (#3369) (#3429)
Creating an adjustment or fill layer still targets its mask (#2166), so
painting and Invert edit the mask, but Properties now shows the layer's
own settings, as in Photoshop. A new UiState.properties_layer remembers
the layer; clicking its mask thumbnail, targeting the pixels or selecting
another layer clears it and Properties shows the mask controls again.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-11 16:55:33 -04:00
cc75ed52c1 fix(cli): skip recorded batch view and save steps (#3058) (#3143)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 16:54:24 -04:00
Valentin KleinandClaude Opus 5.5 3674ed62bd Single Row/Column Marquee: History names the step after the tool (#3031) (#3035)
select.rect takes an optional `line` ("row"|"column"); the canvas sends it
for the Single Row / Single Column Marquee, so History records
"Single Row Marquee" / "Single Column Marquee" instead of
"Rectangular Marquee". An unknown `line` is an error.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 16:52:17 -04:00
Sir Starch 06dcdc1267 fix(mode): restore indexed pixels after clearing transparency (#3080) (#3153) 2026-10-11 16:50:58 -04:00
a97cfd103e Fix Camera Raw preview color management (#3427)
* Fix Camera Raw preview color management

* Apply canvas color management to refined previews

* Camera Raw detail preview: clippy and rustfmt

allow too_many_arguments on DetailPreview::paint (the display joins seven
existing params) and as_chunks for the RGBA8 rows (clippy 1.99).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 16:47:56 -04:00
88ffd89e9f fix(crop): unlock Background when extending canvas (#3081) (#3158)
* fix(crop): unlock Background when extending canvas (#3081)

* Crop: fill an extended Background with the background colour

Photoshop's Crop tool keeps the Background when the frame extends past
the canvas and fills the added area with the background colour, as an
opaque Canvas Size extension does. Do that instead of converting the
Background to a normal layer; other layers still get transparent pixels.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 16:46:09 -04:00
Valentin KleinandClaude Opus 5.5 62e0335116 Transform Path: Distort, Perspective and Warp apply to paths (#3027) (#3032)
* Transform: Distort, Perspective and Warp keep shape layers live (#3009)

Edit › Transform › Distort / Perspective and Warp on a shape layer let the
user edit the box or mesh and then refused at commit ("needs a rasterized
shape"). Photoshop maps the shape's path and keeps it a shape.

- photocraft-vector: new `map` module. `map_points` sends every anchor and
  control point through a map (Distort / Perspective: exact for straight
  segments, exact end tangents for curves). `map_path` follows a curved map
  (Warp), halving each segment until the mapped control points follow the
  mapped curve within a tolerance (at most 64 pieces a segment, bounded in
  total); straight segments whose image is straight stay straight.
- engine: `transform_layer` and `warp_layer` map a shape's path instead of
  refusing; a live rectangle/ellipse/polygon/line becomes a plain path. A
  linked vector mask now follows Distort / Perspective / Warp too. A map that
  sends a point to infinity is an error, not a corrupt path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Transform Path: Distort, Perspective and Warp apply to paths (#3027)

path.transform accepted only an affine matrix, so the Free Transform
Path commit refused any box pulled out of a parallelogram ("Distort and
Perspective can't be applied to a path"), and Warp was not offered on a
path at all. path.transform now also takes a `quad` (with an optional
`rect` frame, default the path's control bounds) and a warp (`style`,
`mesh` or `warp`, as edit.transform.warp), validated (finite numbers,
magnitude at most 1e6, non-degenerate quad) and mapped with the
vector::map helpers from #3025. A parallelogram quad stays affine, so a
live shape stays live. The UI commit sends the quad or warp instead of
refusing, and Transform Path offers Warp; each is one undo step.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 16:43:13 -04:00
rafi612 014dd5f25d fix(ui): drop doubled options-bar borders reintroduced in UI.9 (#2226) (#3425) 2026-10-11 16:40:36 -04:00
f155374ac3 fix(type): navigate adjacent line with large leading (#3066) (#3141)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 16:38:14 -04:00
76c02862c6 Toolbox: make the colour swap arrow clearer (#3416)
* Toolbox: bolder Switch Colors arrow with filled heads

* Toolbox: match the reference Switch Colors glyph

A bold diagonal curve from the icon's top-right to its bottom-left with
filled heads, measured from the reference glyph, replacing the quarter
arc. Geometry extracted to swap_arrow.rs with unit tests.

* Toolbox: correct the swap glyph reference and arrow directions

* Fix formatting and Clippy checks for swap glyph

* swap_arrow: drop the test's env-var PNG dump

Tests shouldn't read env vars to write files; the render assertions stay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 16:32:18 -04:00
Sir Starch b66ebb84d2 fix(type): count normalized insert text caret (#3074) (#3138) 2026-10-11 16:31:51 -04:00
c234865b17 fix(type): respect Lock All on text edits (#3092) (#3132)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 16:26:10 -04:00
7aba2bd305 Type: scan system fonts off the UI thread (#3021) (#3030)
* Type: scan system fonts off the UI thread (#3021)

The first `photocraft_text::shared()` call scans every installed font, and
nothing made that call before the Type tool's options bar drew its font
menu, so the scan ran inside a UI frame (over 60 s on some Macs, #2518).

- photocraft-text: `warm_shared()` starts the scan on a background thread;
  `try_shared()` returns the engine without blocking (None while the scan
  runs, started there if nobody warmed it; built in place on the web, in
  tests, if the thread can't start or the worker died). `shared()` keeps
  its blocking behaviour for engine commands.
- The desktop app warms the fonts at start-up.
- Font menus that draw every frame (options bar, Character, Glyphs and the
  Character/Paragraph Styles family menus) show a disabled "Loading fonts…"
  box and repaint until the scan is done. "Loading fonts…" is in all 16
  catalogs.

Complements #2644 (CoreText discovery on macOS): this changes where the
scan runs, not how fonts are discovered.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Type: axis sliders wait for the background font scan too

#2996 (landed on main) added axis_sliders, which called the blocking
photocraft_text::shared() every frame; use try_shared() so the Character
section doesn't stall while the scan runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 16:25:57 -04:00
buivanvu94 3e45d769fa fix(ui): focus and select hex field when color picker opens (#3375) (#3408) 2026-10-11 16:21:57 -04:00
Sir Starch a893113502 fix(gradient): respect Lock All on Gradient Fills (#3093) (#3120) 2026-10-11 16:19:40 -04:00
Valentin KleinandClaude Opus 5.5 8458cf7095 Transform: Distort, Perspective and Warp keep shape layers live (#3009) (#3025)
Edit › Transform › Distort / Perspective and Warp on a shape layer let the
user edit the box or mesh and then refused at commit ("needs a rasterized
shape"). Photoshop maps the shape's path and keeps it a shape.

- photocraft-vector: new `map` module. `map_points` sends every anchor and
  control point through a map (Distort / Perspective: exact for straight
  segments, exact end tangents for curves). `map_path` follows a curved map
  (Warp), halving each segment until the mapped control points follow the
  mapped curve within a tolerance (at most 64 pieces a segment, bounded in
  total); straight segments whose image is straight stay straight.
- engine: `transform_layer` and `warp_layer` map a shape's path instead of
  refusing; a live rectangle/ellipse/polygon/line becomes a plain path. A
  linked vector mask now follows Distort / Perspective / Warp too. A map that
  sends a point to infinity is an error, not a corrupt path.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 16:16:04 -04:00
Sir Starch f435eb0b55 fix(paint): respect Lock All on layer masks (#3094) (#3111) 2026-10-11 16:15:08 -04:00
b3993e89b3 Linux: say so when no file dialog can open (#3354); read ldconfig on non-English systems (#3397)
* feat(linux): say so when no file dialog can open (#3354)

File › Open / Save / Export did nothing on a minimal Wayland session
(labwc, Void) and said nothing: rfd loads libdbus-1 for the XDG file
chooser portal and falls back to zenity, and when neither works it only
logs and answers "nothing picked", which the app took for Cancel.

A background probe now looks once for the pieces (libdbus in the linker
cache, the portal's FileChooser interface on the session bus, zenity on
PATH). When a dialog comes back empty and none of them is there, the
shell answers with the new FileDialogAnswer::Unavailable and the status
bar tells the user what to install. The probe only explains an empty
answer; it never blocks a dialog, and anything it can't tell counts as
present.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* fix(linux): read the ldconfig cache on non-English systems

The startup library check and the new file dialog probe parse
`ldconfig -p`, but accepted the listing only when its first line
contained "libs found in cache". On a German system the header is
"5522 Bibliotheken im Cache ... gefunden", so the cache was treated as
unreadable and the check silently fell back to a directory search.

Run ldconfig with LC_ALL=C, and accept any listing that starts with a
count. Test: a translated header is a valid listing.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* file_dialog_probe: no dead-code errors off Linux

Findings, problem and on_path are only used by the Linux probe (and the
tests); the empty non-Linux start() was never called. Windows/macOS
clippy -D warnings failed on them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 16:14:47 -04:00
5f55a29d2b Color: honour the EXIF sRGB tag on open; wire Ignore EXIF Profile Tag (#204) (#3026)
A file with no embedded ICC profile whose EXIF ColorSpace tag says sRGB
(what cameras write) now opens as sRGB, as in Photoshop: it is tagged
sRGB before the Color Settings policy runs, so it is kept, reported as a
mismatch, or converted like any embedded profile. Before, it was read as
untagged and took the working space, so with a wide working space such
as Display P3 its colours were reinterpreted.

Preferences › File Handling › Ignore EXIF Profile Tag (off by default)
restores the untagged reading, and is now shown in the dialog.

photocraft_codecs::exif_color_space reads the tag from the Exif sub-IFD,
bounds-checked; anything malformed reads as no tag. Settings that do
nothing: 43 → 42 of 150.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 16:07:03 -04:00
56b192453e i18n: translate the Select and Mask dialog labels (#3014) (#3015)
Smart Radius, Shift Edge, Decontaminate, Output and the Refine Edge
title had no catalog rows, so the Select and Mask dialog stayed partly
English in every language; Greek and Polish also missed Modify's
Apply At Canvas Bounds. A new test checks every generated select.*
dialog (params, choices, title) in all registered languages.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 16:01:04 -04:00
57cba5ef8e Window: a window saved while minimized reopens at the minimum size, not 160 x 64 (#3380)
On Windows, eframe saves a minimized window's size (160 pt wide, raised to
64 pt tall), and the minimum size isn't applied to a restored window, so
PhotoCraft reopened as a 160 x 64 strip on every launch. A window_builder
hook grows a restored window to the minimum size, keeping its centre.

Co-authored-by: Katt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 16:00:11 -04:00
b1900ace28 Installed ICC profiles in the profile menus, and Mirror in Print (#3011)
* Installed ICC profiles in the profile menus, and Mirror in Print

- photocraft_engine::installed_profiles: scans the OS colour profile
  folders (Windows, macOS, Linux), bounded and cached; new
  edit.installedProfiles command.
- Print's Printer Profile and the Proof Setup, Convert to Profile and
  Assign Profile dialogs list the installed profiles after the
  built-ins; a profile given by path that isn't listed shows by name.
- file.print emulsionDown mirrors the page (PDF and preview), with a
  Functions › Emulsion Down (mirror) checkbox.
- Print dialog: cm/mm/in, Height and Width fields, Print Resolution.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Print dialog: translate Emulsion Down, Functions, Print Resolution in every catalog; cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 15:55:11 -04:00
bbb05cabfb fix(shapes): options bar Fill/Stroke edit the selected shape (#3347) (#3370)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 15:54:38 -04:00
539bf7ba14 Color panel: HSB on sRGB values, like Photoshop (#3323) (#3327)
The Color panel converted between the foreground and its hue, saturation and
brightness with egui's `Hsva`, which works in linear light. So a 50% grey
(128) read as Brightness 22%, and the colour field's left edge halfway down
was drawn as 188, not 128. Photoshop's HSB, and the Color Picker dialog's,
work on the sRGB-encoded values.

`srgb_hsva` / `hsva_srgb` now use the Color Picker's `rgb_to_hsv` /
`hsv_to_rgb`, and the field, hue strip, HSB slider tracks and swatch draw
through a new `hsva_color32` instead of egui's linear `Color32::from(Hsva)`.
`Hsva` only holds the numbers now.

Co-authored-by: lloyd <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 15:45:50 -04:00
Valentin KleinandClaude Opus 5.5 d9445c7d1d Free Transform: ⌘-drag of a corner scales editable type instead of distorting it (#3010) (#3012)
Distort and Perspective are greyed for editable type (#2701) and the engine
refuses them at commit, but the box's ⌘ / ⌘⌥⇧ corner drags didn't look at the
layer, so the box distorted and the commit then failed. On a box over live type
those drags now act as a plain corner drag (⌥ and ⇧ keep their meaning).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 15:42:43 -04:00
4ecf8ea6b9 feat(ui): Motion Blur and other filter angles get the angle dial (#3152) (#3407)
Move Drop Shadow's angle dial out of layer_style.rs into a shared
widgets::angle_dial_row that takes the param's range and uses the
dialogs' value_field. The field keeps Motion Blur's -360..360, and it
takes the dialog's opening focus. The filter dialog uses the dial for
direction angles that count counter-clockwise from three o'clock:
Motion Blur, Emboss, Oil Paint, Lighting Effects, Relight and Global
Light. Rotation amounts (Twirl, Rotate Arbitrary, Crop, Lens Correction,
Blur Gallery) and Flame's up-zero angle keep their sliders.

Arrow keys on the focused dial wrap round only when the range is the
dial's own -180..180 (Drop Shadow); on a wider range they step on, so
Motion Blur's 270° goes to 271°, not -89°.

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 15:38:26 -04:00
67747dfd02 Type: Warp on live type takes the warp styles and stays editable, no prompt (#3004) (#3008)
* Type: ask to rasterize before Warp on live type (#3004)

Edit › Transform › Warp (the menu, or the warp toggle of an open transform
box) on editable type opened Warp mode, let the user shape the mesh, then
failed on commit with "Warp needs rasterized type". It now opens Photoshop's
"This type layer must be rasterized before proceeding…" prompt, the one the
pixel tools already use. OK applies an open transform box, rasterizes the
type (its own history state) and opens Warp on the pixels; Cancel does
nothing. The prompt's continuation is a menu command from an allow-list,
run with the egui context right after the confirm (control channel, OK
button) or on the next frame.

Distort and Perspective stay greyed for type (#2701), Puppet Warp and
Perspective Warp stay greyed for non-pixel layers, as in Photoshop.

Scorecard TYPE-218-9 -> done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Type: Warp on live type takes the warp styles, no rasterize prompt (#3004)

Photoshop 2026 keeps Edit › Transform › Warp enabled on live type and asks
nothing: the mesh can't be dragged, only the options bar's warp styles
(Warp Text's) apply, and the type stays editable. The earlier version of
this change asked to rasterize first; that is gone (and with it the prompt
continuation, which nothing else used).

Warp mode on a type layer now starts from the layer's own Warp Text style
over the unwarped type, ignores mesh drags and splits (Split, Grid and the
Custom style are greyed/hidden, the split menu items are greyed), and the
commit runs edit.transform.warp, which on type sets the Warp Text: one
history step, recordable, the layer stays Text. None takes a warp off. A
box scaled or rotated before toggling Warp is applied first.

Scorecard TYPE-218-9 note updated: Photoshop doesn't prompt for Warp;
Distort and Perspective stay greyed (#2701).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 15:35:47 -04:00
Valentin KleinandClaude Opus 5.5 bd3be48785 Pen: Alt breaks a handle while drawing, and close-drag pulls out the first anchor's handles (#3306) (#3314)
Alt during a drag unlinks the handle pair (only the outgoing one keeps following),
Alt-press on the last anchor's outgoing handle turns that handle alone, and pressing
the first anchor now closes on release, so a drag pulls out that anchor's handles
(a stand-in knot folded into the first one on commit). A plain click still closes
without touching the first anchor's handles. Still one History step per path.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 15:29:33 -04:00
KnottyDyes 2d6ff3f6cc Inspect: report each layer's vector mask (#2980)
`hasMask` in document inspection covers only raster masks, so a layer
with a vector mask looked unmasked to an agent. Layers, groups included,
now also report `hasVectorMask` and `vectorMaskEnabled` (null when there
is no vector mask). `hasMask` keeps its meaning.
2026-10-11 15:21:03 -04:00
28874bbfad Select and Mask: Output To New Document, with or without a layer mask (#2998) (#3007)
* Select and Mask: Output To New Document, with or without a layer mask (#2998)

select.refineEdge takes output newDocument / newDocumentWithMask: a new
document like the source (size, mode, depth, resolution, profile) with
the active layer cut out by the refined edge, or with the matte as a
layer mask. The source document is left untouched. The dialog's Output
choice lists all six targets, translated in every catalog.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n: drop the duplicate pt-br New Layer row (main already has it)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 15:16:45 -04:00
8a72978549 File Handling: wire Image Previews to embed a PSD thumbnail (#204) (#2971)
* File Handling: wire Image Previews to embed a PSD thumbnail (#204)

Preferences > File Handling > Image Previews is live for PSD/PSB saves. With
Always Save (the default) and Ask When Saving, the file carries Photoshop's
thumbnail image resource (1036: the 28-byte kJpegRGB header and a JFIF stream,
at most 160 px on the long side); Never Save writes none. The thumbnail is the
reduced composite converted to sRGB through the document's profile with
photocraft-cms (8/16/32-bit; Gray, CMYK and Lab become RGB), over white where
transparent. Ask When Saving has no Save As checkbox yet, so it saves the
preview, as Photoshop's checkbox starts on.

The preference reaches Save, Save As, Save a Copy and automation saves in the
app (ExportSettings.image_previews), and the engine's headless saves
(file.saveACopy, batch, Layers/Comps/Artboards to Files) through SaveOpts.
photocraft_io::ExportOptions gains image_previews (default on).

Settings that do nothing: 32 of 153 (#204).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* File Handling: rustfmt the Image Previews save path

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 15:14:49 -04:00
f92f13490b Fix/3144 taskbar maximized (#3308)
* Window frame: trim a caption-less maximize clear of the taskbar (#3144)

* Credit axlecoffee in the About window

* rustfmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 15:08:18 -04:00
58406c38da Cycle Color Lookup LUTs with keyboard and wheel (#3304)
* Preview Color Lookup LUT selection while cycling

* Test Color Lookup keyboard and wheel cycling

* rustfmt; drop a useless into_iter clippy flags

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 14:57:43 -04:00
Valentin KleinandClaude Opus 5.5 b54fdfd94f Tests: panic_hunt reruns a timed-out command before calling it hung (#2994) (#2997)
The first type.create starts the shared text engine, which scans every
system font once (3.5-5 s under load). panic_hunt billed that to
type.create against its 4 s deadline and failed intermittently. A real
hang reproduces, one-time setup does not: a timeout now counts only if a
rerun on a fresh session times out too.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 14:54:14 -04:00
Valentin KleinandClaude Opus 5.5 139df7ae85 Type: variable font axis sliders; optical size follows the type size (#2985) (#2996)
The Character section (Properties and Window > Character) shows one slider
per axis of the style's variable font below the font style (Weight, Width,
Slant, Italic, or the font's own tag), setting type.setStyle variations; a
drag is one history step. Optical size has no slider: the layout now sets
opsz to the type size unless the style sets it, as CSS font-optical-sizing
auto. Picking a font style or weight resets the wght axis to it, so an
earlier slider value no longer overrides the style the dropdown shows.

Scorecard TYPE-218-4 -> done.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 14:46:26 -04:00
Dan HiornsandClaude Opus 5.5 bb5d26e052 Free Transform: right-click W or H to pick their unit (#3235) (#3301)
As in Photoshop, right-clicking the W or H field of the Free Transform
(and Free Transform Path) options bar opens a menu of units: Pixels,
Inches, Centimeters, Millimeters, Points, Picas and Percent, the
current one checked. W and H then show the box's size in that unit at
the document's resolution (1200 px at 300 ppi is 10.16 cm), and a
value typed in it scales the box to that length; Percent, the default,
is the scale as before. The pick is remembered with the dialog
settings (`dialogs["edit.freeTransform"].sizeUnit`).

The menu is the rulers' unit menu (`rulers::unit_menu`), the
conversion is the Properties panel's `LenUnit`, and the size limits and
the link toggle work on the scale as before. Length fields are wider
(84 pt) so "2116.67 mm" fits; Percent keeps its 66 pt.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 14:40:14 -04:00
76c7d723f4 Move tool: double-click type on the canvas to edit it (#1132) (#3300)
Since Photoshop CC 2019 a double-click on a type layer with the Move tool starts
editing its text without switching tools by hand. PhotoCraft only offered this
from the Layers panel thumbnail. A double-click with the selected Move tool now
picks the topmost visible type layer under the pointer (the Type tool's own hit
test), makes it active and opens an edit session with the caret on the glyph
there, switching to the Type tool. Elsewhere the double-click does nothing, ⌘
held over another tool doesn't count, and an open transform box keeps its
double-click (commit).

The type tests' harness steps a quarter second per frame, past egui's
double-click delay, so the new test uses a 60 fps harness.

Co-authored-by: lloyd <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 14:28:05 -04:00
Valentin KleinandClaude Opus 5.5 65e8d5f020 GPU canvas: price the display textures before building them (#2934) (#3299)
The GPU canvas built a full-resolution, mipmapped texture set covering the
whole declared canvas (DocTextures::new) with only per-texture side limits,
so a document's size alone decided how much GPU memory was committed: a
300000x300000 canvas asks for hundreds of gigabytes.

canvas_texture_bytes prices the set in closed form (every tile and mip
level) and DocTextures::new refuses one over canvas_budget (a quarter of
RAM, at least MIN_GPU_BUDGET) without creating anything. refresh reports
"over-budget" and ensure_gpu then draws the document on the reduced CPU
canvas, so a supported large document still displays.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 14:16:27 -04:00
myangaa1 e5dbcab335 Open several files in name order, keeping it for background opens (#3248) (#3293)
Files opened together (File > Open with several files, paths on the
command line, the OS's "open these documents") appeared in random tab
order: each one opens in the background and its tab was added when it
finished decoding, so small files came first. The paths were also used
in the order the picker returned them.

`open_paths` now sorts the paths naturally (`File_2` before `File_10`,
case-insensitively) and opens them as a set: every background open
carries its position (`OpenOrder`), and when it finishes its document is
moved after the members before it that have already opened, so the set
reads in order however long each file takes. Members opened at once
(preset files) take their place immediately. The web build sorts the
picked files' contents the same way.

Tests: `natural_cmp`, a set opened synchronously, and a set whose
background opens finish out of order, mixed with a tab dropped at a
slot and an open from a forgotten set.
2026-10-11 13:51:46 -04:00
Gert Pellin - GPEandswitch87 e26442657f ui: Dust & Scratches previews at full resolution, as it applies (#3265) (#3287)
A 1/4 proxy averages away the specks the filter exists to remove, so the
preview showed an untouched image, at a scale that upscaled back to blocky
— while `radius` stayed in document pixels and covered k times the area it
covers in the result. OK always applied at full resolution, so only the
interactive feedback lied; add the filter to FULL_RESOLUTION_PREVIEW and
place its regression test on that path.

Co-authored-by: switch87 <[email protected]>
2026-10-11 13:39:11 -04:00
Valentin KleinandClaude Opus 5.5 740dd3019f Rulers: stay level and fully ticked on a rotated view; guides turn with the image (#3233) (#3282)
* Rulers: stay level and fully ticked on a rotated view; guides turn with the image (#3233, #3277)

The rulers measured along the rotated document axes, so at most angles the
ticks were squeezed into a few pixels (none at 90°) and the rest of the
ruler was empty. They now measure with the view minus its rotation: same
zoom, flip and pixel aspect, same document point under the canvas centre.

Guides were drawn as screen-level lines through the screen position of
(pos, 0), so on a rotated view they no longer marked their document
coordinate while hit-testing still used it. They are now drawn along the
document line across the clip rect.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Rulers: anchor a rotated view's rulers at the document origin (#3233)

Photoshop 2026 keeps the rulers level at zoom scale on a rotated view, with 0
at the screen position of the document origin (where the rotated image's
top-left corner lands), not at the unrotated frame through the canvas centre.
ruler_xform now re-centres the level mapping so the origin projects where the
rotated view draws it; tick spacing still follows zoom, flip and pixel aspect.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Rulers: label distances before the origin without a minus sign (#3233)

Photoshop's rulers print the distance from the origin, so ticks left of /
above it read "1000 500 0 500 1000", not "-1000 -500 0". The label is now
the absolute value (extracted into `ruler_label`), for every view.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 13:27:41 -04:00
Gert Pellin - GPEandswitch87 0144cb283d ui: keep the Color panel knob in the corner it was dragged to (#3228) (#3275)
The SV field re-derives Hsva from the colour every frame, and black reads
back as s = 0 — so a drag that bottoms out into black drew the knob at the
bottom-left one frame later, although the colour it picked was right.

Remember what the field was showing (hue *and* saturation) and restore both
only when the colour cannot carry them: both for black, the hue alone for a
grey, whose saturation is genuinely zero.

Co-authored-by: switch87 <[email protected]>
2026-10-11 13:16:02 -04:00
a35af4e279 Add FITS read/write (astronomy images) (#2956)
* Add FITS read/write codec

FITS (the astronomy format) opens and saves as a flat image: the primary
HDU or first IMAGE extension; gray, or RGB when NAXIS3 = 3; BITPIX 8/16/
32/64/-32/-64 with BSCALE/BZERO/BLANK; rows follow ROWORDER (bottom-up by
default). Camera U16 data stays exact; float data is normalised to 0..1.
Header cards round-trip as text metadata (HIERARCH for long names).
Tile-compressed (fpack) files are refused as unsupported.

Wired into File > Open, Save As and the batch commands as .fits/.fit/.fts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Test FITS open and save through photocraft-io

Gray 16-bit, RGB 8-bit and RGB 32-bit float documents round-trip exactly,
and header cards travel as the document's text metadata.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* FITS: hostile-header regression test (absurd axes, bad BITPIX, no END, HDU chains, overflowing sizes)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 13:15:22 -04:00
f8af27d261 Prevent white flash when opening the screen color picker (#3256)
* Avoid white flash when opening screen color picker

* Normalize screen picker source line endings

* rustfmt; doc comment on viewport_builder

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 13:04:55 -04:00
Gert Pellin - GPEandswitch87 308ef63294 raw: charge the lossless-JPEG intermediate against max_alloc (#2925) (#3194)
Co-authored-by: switch87 <[email protected]>
2026-10-11 12:52:41 -04:00
9441484d16 Quick Mask: an empty start and Select All stay apart (#2743) (#2922)
* Keep Quick Mask's empty start and Select All apart (#2743)

Quick Mask stored "no selection" as an all-white mask, the same as Select
All. With Color Indicates Selected Areas that white was coloured over the
whole canvas, and leaving Quick Mask turned any all-white mask (a real
Select All too) into no selection.

The document now records that Quick Mask was entered with no selection.
The empty mask is white for Masked Areas and black for Selected Areas, so
neither shows colour; switching the option on an untouched empty mask
keeps it empty. On exit only that untouched white start becomes no
selection, so Select All survives the round trip. The flag is saved with
the document.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Quick Mask tests: pass the active layer to channel_view::render (new main signature)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 12:51:18 -04:00
b814fd5241 Zoom and Hand tools: right-click the canvas for the view menu (#3242) (#3255)
Right-clicking the image with the Zoom or Hand tool opens Zoom In, Zoom Out,
Fit on Screen, Fill Screen, 100%, 200% and Print Size. Zoom In/Out step about
the right-clicked point (or centre it with Zoom Clicked Point to Center); the
other rows run their View menu command. Outside the image the pasteboard menu
still wins. The canvas keeps the view a menu row sets instead of writing its
frame copy back over it. Agents get the same menu through ui.pointer and
ui.context.choose.

Co-authored-by: lloyd <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 12:50:01 -04:00
a7f26522ff i18n(pt-br): translate 782 missing UI, filter, and tool strings (#3254)
Co-authored-by: AlastorIRL <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 12:42:10 -04:00
Brennan StehlingandClaude Opus 5.5 2b19987bf1 Menus: a submenu stays open while the pointer heads for it (#1218) (#3251)
In the in-window menu bar (Windows, Linux, --in-window-menus), moving from a
submenu's row toward one of its lower items crosses the rows below. egui keeps
the submenu open only while the pointer moves in a straight line at it: a
bowed path or a pause on the way closed it, and the crossed rows lit up as if
chosen.

As in macOS and Photoshop menus, the submenu now stays open while the pointer
is inside the triangle from where it left the row to the submenu's near edge,
until it rests on another row for 0.3 s or moves away. Its row stays lit and
the crossed rows don't light up; when the submenu lets go, the row under the
pointer takes the highlight. Clicks, keys and leaving the triangle behave as
before.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-11 12:34:12 -04:00
Tanish Mankuandjerrykimo da5abd10f9 Native brush outline and crosshair cursors on macOS, X11 and Wayland (#1343) (#3243)
* Native brush outline and crosshair cursors on macOS, X11 and Wayland (#1343)

The brush outline and crosshairs were OS cursor bitmaps only on Windows; on
macOS and Linux the app painted them, so they trailed the pointer by the
render, present and compositor latency and jumped to catch up on slow frames.
tool_cursor now hands the OS the bitmap on every desktop root viewport.

macOS takes NSCursor images in logical points, so the bitmap scales with the
UI zoom only there; Windows, X11 and Wayland take physical pixels. Off Windows
bitmaps stay within 255 px (X servers and hardware cursor planes), and a
larger tip falls back to the painted outline plus a small OS crosshair.

The Pencil's grid-snapped square and the pipette stay painted, and the Hand
bitmap stays Windows-only (the other platforms draw their own hands).

Co-authored-by: jerrykimo <[email protected]>

* Cursor test: the Hand is a bitmap only on Windows; elsewhere the OS draws Grab

---------

Co-authored-by: jerrykimo <[email protected]>
2026-10-11 12:21:40 -04:00
Myosh1 3f0970923d Add built-in rainbow gradient presets (#2916)
Add a "Rainbows" group to the built-in Gradients panel with five presets: Rainbow,
Pastel Rainbow, Neon Rainbow, Oil Slick and Rainbow Fade. The three hue ramps sample 13
evenly spaced hues (red 0 deg to magenta 300 deg) so the transitions are smooth rather
than the seven coarse ROYGBIV points; Rainbow Fade reuses the classic ramp with
transparent ends. All colours are original (clean-room).

Covered by a new engine test, presets::tests::rainbow_gradient_presets.
2026-10-11 12:18:19 -04:00
28622aabfc Move dock tabs between groups individually (#3239)
* Report which dock tab leaves its strip

* Carry dragged dock tab identity

* Expose dock panel name normalization

* Move individual tabs across native dock groups

* Document cross-group dock tab drops

* Test individual tab drops between dock groups

* Resolve a dropped tab by its original index; rustfmt

The strip reports visible indices, so a reordered group moved the wrong
panel. Adds a regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 12:10:27 -04:00
David MannandClaude Opus 5.5 66c0b59a23 Layers: Combine Shapes merges the selected shape layers (#2400) (#2906)
Layer › Combine Shapes › Unite / Subtract Front Shape / Intersect Shape
Areas / Exclude Overlapping Shapes only changed the operations between the
components of the active layer. With two single-shape layers selected (the
report's case) the active layer had one component, so nothing happened.

With two or more shape layers selected and no `layer`/`subpath` param, the
commands now merge them into the top-most layer in one history step: the
bottom layer's components keep their operations and every component of the
layers above takes the chosen one, in stacking order, then the other layers
are removed. Merge Shape Components merges them the same way (each layer
combined) and bakes the result. Selected non-shape layers are left alone,
locked layers refuse the merge, and one selected layer behaves as before.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-11 12:05:57 -04:00
Valentin KleinandClaude Opus 5.5 c1bd296dcf Select and Mask: Refine Edge Brush (#2972) (#2989)
* Select and Mask: live preview in Photoshop's view modes (#1754)

The Select and Mask dialog had no preview of the refined selection. It now
previews live in Photoshop's view modes: Onion Skin (default), Marching
Ants, Overlay, On Black, On White, Black & White and On Layers, with a
per-view Opacity, Show Edge (J) and Show Original (P). F cycles the views,
O/M/V/A/T/K/Y pick one and holding X shows the image without a view.

The view state lives in the dialog's fields, so ui.dialog.set drives it.
The preview runs select.refineEdge on the proxy with output=selection and
builds the view from it (veil fill layers, a layer mask, or the refined
selection, whose marching ants the canvas draws scaled back up), through
the existing filter-preview worker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Select and Mask: Refine Edge Brush (#2972)

Select and Mask had no Refine Edge Brush. select.refineEdge now takes
refineStrokes: [{"points":[[x,y],...],"size":px,"mode":"add|subtract"}],
applied in painting order. Added areas become unknown and take a colour
estimate: each pixel's colour projected on the line between the mean known
foreground and background colours around it (normalised convolution over
a box of the brush size, four times as far where none are near), so hair
or fur beyond the edge-detection band joins the selection. Subtracted
areas keep the original edge. Malformed or oversized strokes are rejected
(stroke / point / swept-area limits), never a panic.

The dialog gets the brush: Refine Edge Brush (R), Mode (Expand Detection
Area / Restore Original Edge, Alt swaps), Size ([ and ]) and Clear Brush
Strokes. With it on, dragging on the canvas paints strokes into the
dialog's refineStrokes field, so the live preview, Show Edge and OK use
them, and ui.dialog.set / agents drive them like any other param.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 12:00:25 -04:00
3360f6e442 Speed up Tilt-Shift with existing per-level halo trimming (#2880)
Co-authored-by: optimalbytee <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 11:58:04 -04:00
Dylan M. Taylor 19f427aa00 ci: refactor workflows to use storytold/craft-common-actions (#3432)
* ci: refactor workflows to use reusable artcraft-common-actions

* ci: point reusable workflows to storytold/craft-common-actions

* ci: pin storytold/craft-common-actions to commit 27a978f and pass secrets explicitly

* ci: use @main (unpinned) for craft-common-actions with explanation comment
2026-10-11 11:50:48 -04:00
myangaa1 d10ded55d6 Clip the checker under rounded colour swatches to their corners (#3208) (#3363)
The colour swatches (Layer Style's Stroke, Color Overlay and the rest,
and every `color_swatch` / `color_swatch_button`) painted a square
checkerboard under a rounded fill, so the checker's light cells showed
at the four corners, white specks on the dark themes.

The checker under a rounded swatch is now a repeating two-by-two tile
textured onto a rect with the swatch's corner radius: one shared texture
per context, nearest-filtered so it never blurs, scaled so a cell stays
4 pt. `checker` itself is unchanged for the square previews.
2026-10-11 11:48:13 -04:00
5025fd2895 Color Sampler tool (#1046) (#2753)
* Color Sampler tool (#1046)

Add the Color Sampler to the Eyedropper (I) flyout: click to pin numbered
sample points to canvas pixels, drag to move, Alt-click (or drag off-canvas)
to remove, Clear All in the options bar, at most 10 per document. Each point
reads one composite pixel (RGB 0-255 and naive device CMYK, same as the
pointer readout) and the Info panel lists them under their number with the
position in the ruler unit; the readouts refresh when the document changes.

Points are per-document engine view state (DocState.color_samplers): they
belong to their document, are discarded on close, and are not saved to
.pcraft or PSD. They are driven by commands shared by the UI, CLI, control
channel and MCP (view.colorSamplers.add/.move/.delete/.clear/.list); the
mutations change no pixels and add no History step.

Points follow the canvas geometry (crop, Canvas Size, Image Size, Image
rotation/flip, rotated crop) through a pending Session.sampler_map that
Session::edit applies before culling the points that land outside the new
canvas; the count removed is reported in the status bar.

- engine: new sampler_cmds.rs (commands + shared readout helpers) and the
  sampler_map wiring in lib.rs, image_cmds.rs, mode_cmds.rs, commands.rs,
  analysis_cmds.rs (compound rolls points back on error).
- ui-egui: Tool::ColorSampler + original sampler.svg icon, toolbar slot,
  Info panel list, options bar, pointer handling, overlay markers, cursor.
- docs/scorecard.md regenerated (TOOL-1649-1 no longer says the tool is
  missing). No menu item, so parity is unchanged (627/627).

* Color Sampler follow-up: tool count, README, i18n, roadmap

The full ui-egui suite (not just the filtered tests) surfaced these gaps:

- state.rs: Tool::ALL.len() assertion 52 -> 53.
- README.md: "52 tools" -> "53 tools" and add Color Sampler to the list,
  so readme_tool_list_matches_tool_all passes.
- i18n: the options-bar hint, "{n} of {max} sample points" and
  "No document open" need entries in every catalog that claims complete
  menus (every_tl_literal_is_translated); added to all 16 (coverage
  1584/1584). The translations were drafted alongside the tool.
- docs/roadmap.md: drop Color Sampler from the missing-tools list and note
  it landed.

* Color Sampler: fit main's new tools and Image Size resample type

Reset Tool covers ColorSampler, the test ViewXform sets aspect, and
Image Size checks Method::None instead of an Option.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 11:43:09 -04:00
d22a9fac6e fix(ui): Global Light opens with stale values and overwrites document setting (#3217)
Populate Layer › Layer Style › Global Light dialog fields from the
active document's shared global lighting rather than schema defaults or
remembered values from other documents. This ensures opening Global Light
and confirming unchanged preserves the active document's lighting.

Fixes #3054.

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 11:36:23 -04:00
Valentin KleinandClaude Opus 5.5 7fd5715dbd Type menu: Anti-Alias › None first and checked; checks follow the edited layer (#2983) (#2984)
- menu_catalog: add Type › Anti-Alias › None before Sharp, as in Photoshop.
  It used to come from the engine list, appended after Windows and built
  without a checked state, so a layer set to None showed no check.
- view_cmds::type_checked reads type_tool::target_text (the edited layer,
  else the active or a selected type layer), as the options bar and the
  Type commands do, not only the active layer.
- Anti-alias and orientation items stay check items (Some(false)) with no
  type layer, so the native menu doesn't rebuild.
- Parity floor 629 -> 630; docs/parity-checklist.md regenerated.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 11:35:38 -04:00
Valentin KleinandClaude Opus 5.5 fd351918e5 PSD: cap the layer tree for psd_to_document; layered TIFF checks group depth (#2940) (#2975)
The file-open path rejects PSDs nested past MAX_GROUP_DEPTH before
conversion, but the public psd_to_document built file.layer_tree() to the
file's full depth (~16000 levels) before Ctx::build capped it, and layered
TIFF reached it with no preflight at all.

- photocraft-psd: PsdFile::layer_tree_max_depth(n) builds the tree
  iteratively and drops the children of groups nested n deep, so walking
  or dropping it recursively is bounded. layer_tree() is the uncapped case.
- psd_to_document uses it with MAX_GROUP_DEPTH, the same cap Ctx::build
  and apply_link_groups apply, so imports are unchanged.
- Layered TIFF rejects nesting past the cap with the same error as a PSD
  (shared psd_import::check_group_depth).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 11:20:32 -04:00
buivanvu94 6a2aaebe99 fix(ui): unchanged Custom Proof Setup replaces active document proof profile (#3213)
Populate View › Proof Setup dialog fields from the active document's
current proofing condition rather than schema defaults or remembered
values from other documents. This ensures opening Custom Proof Setup and
confirming unchanged preserves the active proof profile and condition.

Fixes #3055.
2026-10-11 11:18:41 -04:00
d8d8d9f3d2 Tools: Convert Point tool in the Pen flyout (#3204) (#3211)
Convert Point is a tool of its own, built on the existing path.convertPoint
edit that Pen + Alt already drives. A click makes a smooth anchor a corner, a
drag from an anchor pulls out smooth handles, a drag on a handle moves it
alone. The tool selects the anchor it converts so its handles show; a press on
empty canvas or a segment does nothing, and Cmd/Ctrl is Direct Selection, as
with the Pen. It shares the Pen's key (P).

Original glyph with an ATTRIBUTION.md row; tool name in all catalogs; README
tool list and the G6 / ui-parity / roadmap counts updated (tools 56 of 68, the
earlier 53 was stale).

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 11:09:38 -04:00
c0110fb4d2 fix(engine): allow targeting layer mask and vector mask via channel.target (#2458) (#2705)
* fix(engine): allow targeting layer mask and vector mask via channel.target (#2458)

* fix(ui): apply channel target actions before syncing mask targets in channels panel

---------

Co-authored-by: huudinh1401 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 11:06:57 -04:00
deb419eeb2 fix: macOS Monterey crash on Intel Iris Pro (disable wgpu indirect validation) (#3171)
* GPU startup: skip wgpu indirect-call validation shaders (#3107)

wgpu compiles its indirect-call validation compute shaders inside
request_device. On Intel Iris Pro (Metal GPUFamily 1, Monterey) the Metal
compiler hits an internal error on them, which wgpu-core reports as
Device(Lost), so the window device can't be created in any mode, including
--safe-gpu and PHOTOCRAFT_CPU_CANVAS. PhotoCraft issues no indirect draws or
dispatches, so drop the flag; WGPU_VALIDATION_INDIRECT_CALL=1 still re-enables it.

* gpu_startup: skip indirect-call validation only on Intel Macs

Keep wgpu's default validation on Apple silicon, Windows and Linux; only Intel Macs,
where Metal's compiler crashed on the validation shaders (#3107), skip them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 11:00:01 -04:00
a1de9ce4c8 fix(ui): respect native desktop scale under Auto UI scaling (#1278) (#3165)
* fix(ui): respect native desktop scale under Auto UI scaling (#1278)

* UI scale: drop the now-unused monitor size, update docs and scorecard

Merge main; Auto no longer reads the monitor size, so remove the parameter and its
computation, simplify the test, and update ui-design.md and UI-217-9 to match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 10:53:55 -04:00
AyanandBrandon Thomas acce8e0e99 Five exact-output speedups: dense Extrude 160s to 0.39s (#2685)
* Rasterize Extrude blocks and scatter Wind streaks once

* Prepare Spin Blur rotations and fixed-channel sampling

* Share Lens Correction interpolation across color and alpha

* Make wide prepress traps independent of radius

* Add full-operation timing for five imaging algorithms

* Record 24 full-operation benchmarks and exact-output checks

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 10:50:45 -04:00
Valentin KleinandClaude Opus 5.5 0aaf5b60fe Select and Mask: live preview in Photoshop's view modes (#1754) (#2970)
The Select and Mask dialog had no preview of the refined selection. It now
previews live in Photoshop's view modes: Onion Skin (default), Marching
Ants, Overlay, On Black, On White, Black & White and On Layers, with a
per-view Opacity, Show Edge (J) and Show Original (P). F cycles the views,
O/M/V/A/T/K/Y pick one and holding X shows the image without a view.

The view state lives in the dialog's fields, so ui.dialog.set drives it.
The preview runs select.refineEdge on the proxy with output=selection and
builds the view from it (veil fill layers, a layer mask, or the refined
selection, whose marching ants the canvas draws scaled back up), through
the existing filter-preview worker.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 10:48:26 -04:00
d67e28c118 fix(zoom): Alt-click with the Zoom tool on desktops that take Alt+click (#3137) (#3164)
Desktops that move windows with Alt+drag grab every Alt+left press, so a
Zoom tool Alt-click never arrived and nothing happened. Watch the Zoom
tool for that grab (alt_grab) so the status bar explains it, and let a
latched Alt (Window > Modifier Keys) zoom out: the click, cursor and zoom
rectangle now honour it.


Claude-Session: https://claude.ai/code/session_01JgB5X7gyFEFo4oDW6vH4VN

Co-authored-by: Leel Wasanatha <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 10:47:37 -04:00
Elvis33LE 2c3d972f18 Speed up large content-aware scale operations (#2596) 2026-10-11 10:46:43 -04:00
LessaandBrandon Thomas 53d09f5850 Preserve HDR range in float adjustments and stack statistics (#2592)
* Preserve HDR range in float adjustments and stack statistics

* Cover HDR exposure round trips and Levels record order

* Report the backend used by GPU parity tests

* Compare float PSD oracles at native depth and preserve signed Exposure

* Retain merged alpha metadata when decoding float references

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 10:44:55 -04:00
Valentin KleinandClaude Opus 5.5 989644cabd Type tool: right-click menu while editing text (#2968) (#2969)
* Type: Edit › Paste, Copy and Select › All work on the text being typed (#2893)

While editing type, Edit › Cut already worked on the selected characters (#1355), but the other
menu rows still ran their pixel commands: Edit › Paste tried to paste an image (and did nothing
with text on the clipboard), Edit › Copy copied rendered pixels, and Select › All selected the
canvas. Route them through the type editor like the keyboard: Paste asks the window for the
clipboard text, which arrives as a Paste event and replaces the selection; Copy copies the
selected characters; Select › All selects every character. Copy is enabled for a non-empty
character selection, Paste and Select › All while typing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Type tool: right-click menu while editing text (#2968)

A right-click inside an on-canvas type edit opened nothing: the Type tool
had no canvas menu, and the inline type editor is not an egui TextEdit, so
the text-field menu doesn't reach it. It now opens Photoshop's type edit
menu (canvas_tool_menu.rs TYPE_EDIT_MENU), built from existing commands:
Undo, Cut, Copy, Paste and Select All (dispatched as the Edit/Select menu
items, which act on the text being edited), Check Spelling..., Find and
Replace Text..., Faux Bold/Italic (type.setStyle on the edit's selection,
checked), Rasterize Type, Create Work Path, Convert to Shape (these and the
paragraph/point conversions end the edit first), Horizontal/Vertical and
the anti-alias modes (checked), Convert to Paragraph/Point Text and
Warp Text.... The right-click keeps the text selection. While the menu is
open the keyboard belongs to it: Esc closes only the menu instead of
committing the edit. Agents open it through ui.pointer as for the other
canvas menus.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 10:44:36 -04:00
0f8b370621 i18n(es): native-style review of the Spanish catalog (#3154)
Aligns the Spanish UI with the terminology a Spanish-speaking Photoshop user already knows,
fixes mistranslations and makes the register consistent. 351 rows changed out of 2,457.

- Dodge/Burn were swapped (tools, Color Dodge/Burn, Paint.NET variants).
- "Constrain proportions" read "Construir proporciones" (build) instead of "Restringir".
- Feather and Fade shared one label, as did Artboard and Canvas.
- Photoshop terms: Mesa de trabajo, Motivo, Ajuste preestablecido, Métodos abreviados,
  Cuadrícula, Sector, Deformación de posición libre, Tampón de clonar, Calar, menú Vista…
- Formal "usted" throughout (the catalog mixed tú and usted).

docs/localization-es.md records the terminology so later additions stay consistent.


Claude-Session: https://claude.ai/code/session_012JC2QZ1Qc5KQMBswS38GKy

Co-authored-by: Diego Ospina <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 10:43:15 -04:00
Valentin KleinandClaude Opus 5.5 0fb4bbf1db PSD: don't inflate an over-budget ZIP merged image at parse time (#2926) (#2967)
validate_planes bounded its zlib loop by the uncapped declared size, so a
PSD/PSB declaring more than MAX_DECODED_BYTES of merged image could make
PsdFile::from_bytes decompress far past the decode budget before any
error. decode_planes refuses such a layout with LimitExceeded anyway, so
the stream is now kept verbatim without inflating it, like an unknown
compression method. A layered file whose merged composite is too large
still opens (the importer only warns when the composite can't be decoded).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 10:40:31 -04:00
buivanvu94 1fdb0378a3 fix(ui): respect explicit dropdown defaults in schema dialogs (#3056) (#3149) 2026-10-11 10:36:15 -04:00
Brennan StehlingandClaude Opus 5.5 16bdcbd54e Window menu: list the open documents, the active one checked (#2991) (#3147)
Photoshop's Window menu ends with the open documents; PhotoCraft's had no
list in either menu bar (#1264 got the tab overflow menu only). Window now
ends with a separator and one row per document in tab order, labelled with
its name and checked when active; choosing one brings it forward. The ids
are window.document.<index>, so the rows also work over ui.menu.invoke.

- In-window menu bar: the rows come from menus::menu_items, after Window's
  last item. Names are shown as they are, never translated.
- macOS menu bar: the rows follow Bring All to Front, where a Mac app lists
  its windows. Opening or closing a document rebuilds only the Window menu:
  AppKit adds its own items there (window tiling, the window list), so muda
  can't insert rows by position, and the other menus stay as they are.
  Switching documents moves the check in place. The menu state hash now
  includes the documents' names, so a Save As rename shows up.

Tested in a Tart guest with three generated files (.psd, .png, .tif) in
both menu bars: on main neither lists them; with this change both do, and
choosing a row switches the document and moves the check.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-11 10:31:26 -04:00
kayrockscreenprintingandClaude Opus 5.5 1f742629bb Dialogs: keep the live dialog in front of older ones (#3140)
Only the last dialog takes input, but egui only lets the modal drawn on top
take input, and it raises an area that is pressed or wasn't drawn the frame
before. With several stacked dialogs (three files opened together, each with
an Embedded Profile Mismatch prompt) an older prompt could end up in front:
greyed out, with the live one blocked behind it, so nothing could answer
either and the app had to be quit. Raise the live dialog when another one
is above it.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 10:25:29 -04:00
d45b3718ce New Document: presets follow Units & Rulers › Preset Resolutions (#204) (#3126)
Preferences › Units & Rulers › New Document Preset Resolutions did nothing:
Print Resolution was hidden as unread, and the File › New presets always used
300 / 72 ppi. As in Photoshop, print and photo presets now keep their size in
inches at the Print Resolution (Letter at 200 ppi is 1700 x 2200 px), and
screen presets keep their pixels at the Screen Resolution. The Clipboard
preset keeps the copied pixels. Values that are not positive and finite (a
hand-edited preferences file) leave the preset as listed, and sizes clamp to
the file.new limit.

Print Resolution is now shown in the Preferences dialog; settings that do
nothing: 43 -> 42 of 150.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 10:15:40 -04:00
Valentin KleinandClaude Opus 5.5 7b88189e2d Type: Edit › Paste, Copy and Select › All work on the text being typed (#2893) (#2960)
While editing type, Edit › Cut already worked on the selected characters (#1355), but the other
menu rows still ran their pixel commands: Edit › Paste tried to paste an image (and did nothing
with text on the clipboard), Edit › Copy copied rendered pixels, and Select › All selected the
canvas. Route them through the type editor like the keyboard: Paste asks the window for the
clipboard text, which arrives as a Paste event and replaces the selection; Copy copies the
selected characters; Select › All selects every character. Copy is enabled for a non-empty
character selection, Paste and Select › All while typing.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 10:09:30 -04:00
ade5799165 Mirror the shell for right-to-left UI languages (DIST-220-4) (#3114)
* Mirror the shell for right-to-left UI languages (DIST-220-4)

Arabic, Hebrew, Persian and Urdu read right to left, but the window's
chrome was hard-wired left to right, so an RTL catalog (#2505) would
put Arabic labels into a left-to-right layout.

The reading direction now follows the language code
(i18n::dir_for_code: ar, ckb, dv, fa, he, ps, sd, ug, ur, yi), so a
catalog needs no extra setting and the LANGUAGES rows are unchanged.
In a right-to-left language the shell mirrors:

- the menu bar starts at the right with File; menus open under their
  title's right edge, and the arrow keys step through them in screen
  order
- the toolbox docks on the right, the panel dock and its rail on the
  left; tool flyouts open towards the canvas and their corner marks
  and the header chevrons follow
- the title, options and status bars read from the right, with the
  workspace controls and the Fit/progress group at the left end; the
  title and window-drag gap use the free span between them

New module direction.rs holds the helpers (start_panel/end_panel,
row/trailing layouts, horizontal_centered, the popup alignment). Left
to right, every change lays out as before.

No RTL catalog ships yet, so PHOTOCRAFT_UI_DIRECTION=rtl forces the
mirrored layout for review (read once, native only). Panel interiors,
dialogs, menu rows, submenus and document tabs stay left to right, and
egui still draws UI labels without Arabic shaping or bidi reordering;
docs/localization.md and the parity docs say so.

Adds Lucide's chevron-left (the status bar's info menu arrow points
left in RTL; Timeline's Previous frame button asked for it too and drew
the fallback square).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Localization docs: egui shapes Arabic words; what's missing is a font and bidi word order

egui 0.36 shapes right-to-left runs with HarfRust, so letters join within
a word. The gaps are an Arabic fallback font in the UI and paragraph bidi
(words are placed left to right; emilk/egui#8576, #8577).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: MathMattTech <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 10:06:18 -04:00
Valentin KleinandClaude Opus 5.5 1a54384d80 Rulers: remember View › Rulers for new documents; guides as f64 (#2918) (#2954)
View › Rulers (⌘R) now writes unitsAndRulers.showRulers, which is applied
at launch and whenever the preference changes, so new and opened documents
show the rulers as last set, as in Photoshop. The Preferences dialog doesn't
list it: the View menu sets it.

Guides are Vec<f64> (doc, New Guide/Move Guide, guide layouts, artboard and
canvas geometry, snapping, PSD resource 1032), so a guide placed in ruler
units or read from a PSD's 1/32 px positions keeps its exact place.

Scorecard UI-217-20 done (part of #217).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 10:05:13 -04:00
2d2e4993a1 fix(ui): reduced suffix spacing width in the value field to prevent label overflow (#3040) (#3084)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 09:59:53 -04:00
Tanish Manku 75101ddce2 8-bit documents: soft, low-flow brush strokes are dithered instead of banded (#3237)
Brush phase 6c. A stroke composites in float, then each pixel is rounded to 8 bits, so a soft,
low-flow stroke's gentle gradient collapses into flat bands (the audit counted 35 levels against
119 at 16-bit). The pixels the stroke changes now get the same deterministic per-pixel offset of
under half a level on every channel before quantisation:
- fractional values round up or down in proportion, so bands become fine grain;
- a value already on an 8-bit level rounds back to itself, so exact colours never change, and
  pixels the stroke doesn't touch are left alone;
- the offset depends only on the pixel's position, so the live preview, the commit and a replay
  agree.
16-bit and float targets are unchanged.
2026-10-11 06:58:47 -07:00
52e130d481 Fix canvas context menus closing immediately on trackpad taps (#3029)
* Fix canvas context menus closing immediately on trackpad taps

Ignore outside-click dismissal during each menu's opening frame.
Share the guard across canvas tool and layer menus, including control-channel openings.
Add regression coverage for quick taps, repeated reopening, dismissal, and selection/history preservation.

* Share popup dismissal guard with the brush picker

* Merge main: pass the context to main's new control-channel Free Transform menu opener

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 09:52:26 -04:00
30bd8a5598 Fix Shape Stroke controls, popup interactions and paint colours (#3019)
Co-authored-by: optimalbytee <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 09:46:44 -04:00
3cbd727b85 Tests: the marquee ellipse check walks several dash periods of the curve (#3018)
* Tests: the marquee ellipse check walks several dash periods of the curve

The old check sampled ~12 positions along a 28 px arc of a 4-on/4-off ants
pattern: a margin of one sample, so renderer, antialiasing or dash phase
decided pass or fail. Walk the true ellipse around each edge midpoint over
±0.3 rad instead, with the ±2 physical px band hugging the curve, so the
check sees the dashes wherever the phase puts them (#253 follow-up).

* rustfmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 09:40:44 -04:00
585131440a Pixel grid: fade the line colour across mid-tones instead of flipping at one luma (#2990)
* Pixel grid: fade the line colour across mid-tones instead of switching at one luma

The grid line was a full white line over pixels at or below luma 0.55 and a weaker
black one above it. On an image whose tones sit near that cut, neighbouring cells
landed on either side and the grid showed bright, dark and different-strength lines
in patches that traced the 0.55 contour.

The line is now a white layer and a black layer weighted by a smoothstep over luma
0.35 to 0.75, so mid-tones get a faint line that varies smoothly and dark and light
pixels keep the old white and black lines. The GPU shader and the CPU path
(pixel_grid.rs) use the same band; the CPU share is rounded to eighths so equal-colour
runs still merge into long segments.

Tests: unit tests for the fade and mid-tone evenness, and a GPU render test that
fails on the old shader (grid line 30 levels off its pixel at grey 0x87).

Co-Authored-By: Claude <[email protected]>

* Pixel grid: test the line over opaque white too (the #2461 review case)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 09:35:34 -04:00
Harrison O'Connor-Hoover 7a6058e6b4 control: allow requests that operate an open Camera Raw dialog (#2988)
Preserve profile, competing-dialog, crop, discard and authorization gates. Add control-handler regressions for RAW preview, commit and cancel.

Prepared with Codex assistance.
2026-10-11 09:26:46 -04:00
Valentin KleinandClaude Opus 5.5 885b754414 Text fields: right-click edit menu (#2921) (#2952)
* Text fields: right-click edit menu (#2921)

Right-clicking in any text field (layer rename, a number field being
typed into, dialog and panel fields) opens Undo, Cut, Copy, Paste,
Delete and Select All at the pointer, acting on that field. A
right-click inside the selection keeps it, Esc closes only the menu,
and clicking the menu doesn't take the field's focus (the layer rename
would commit). The right-click never reaches the canvas or tool menus.

An egui plugin (text_field_menu.rs) opens and closes the menu for
every TextEdit; the app draws it before any field, so a chosen item is
handed to the field as its keyboard input in the same pass. Paste asks
the window for the clipboard text like Cmd+V in a field. No spelling
suggestions: there is no spell checker (UI-217-8 stays partial).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Text field menu: correct the spell-checker note (#2921)

PhotoCraft has a spell checker (edit.checkSpelling with a suggest
action); it just isn't wired into the text-field context menu yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Context-menu parity doc: same spell-checker correction (#2921)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 09:25:19 -04:00
1234ba4c6f Type: wire Show Font Names in English (#204) (#2981)
Preferences > Type > Show Font Names in English (default on) now drives the
font menus (Type options bar, Character panel, style and Glyphs panels). With
it off, a family whose name table carries a non-English family name (e.g.
"MS Gothic" -> "MS ゴシック", "Microsoft YaHei" -> "微软雅黑") is listed by
that native name, sorted by the shown label, and the search matches either
name. Choosing it still applies the English family, so documents and PSD
output never change with the preference.

- text: FontDb::localized_family_names() reads each family's first face
  (typographic family name, else family name) and a pure localized_name()
  picks the first non-English record.
- ui-egui: sync_font_names() publishes the labels to the egui context once a
  frame (cached per font generation); family_picker_in shows them.
- prefs: the row is no longer hidden; scorecard: dead settings 43 -> 42.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 09:21:55 -04:00
Valentin KleinandClaude Opus 5.5 7c96e9e120 Layer Style: contour picker and Contour Editor (#2912) (#2949)
Every effect with a contour (Drop/Inner Shadow, Outer/Inner Glow, Satin,
Bevel & Emboss Gloss Contour and Contour element) now shows a contour
thumbnail with a preset picker and an Anti-aliased checkbox. Clicking the
thumbnail opens the Contour Editor: add/drag/delete points (the shared
point-curve editor), Corner per point, Input/Output, Preset, and Load…/Save…
of .shc contour files, read and written from Adobe's public File Formats
Specification (Contours). Edits go to the dialog's pending params, so the
preview follows and OK applies them in the one layer.layerStyle.replace.

- doc: Contour::Custom gains per-point corner flags (serde default).
- compose: contour_curve_lut splits the spline at corner points; CPU and
  GPU effects use it.
- engine: the 12 standard presets with our own control points (older names
  still accepted); `contour` params also take a curve object
  {name, points, corners}; antiAlias params; Satin contour; the bevel
  Contour element edits in place; contours_from_shc / contour_to_shc.
- io: PSD contour points read and write the Cnty (continuity) flag.
- psd: shc.rs parser/writer.
- scorecard FILE-215-15 missing -> partial.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 09:21:18 -04:00
6601bbc3e7 Layers: Pattern Fill dialog for new and edited pattern fill layers (#2908) (#2979)
* Layers: Pattern Fill dialog for new and edited pattern fill layers (#2908)

Layer > New Fill Layer > Pattern... created the layer with default
settings and no dialog, and double-clicking a Pattern Fill thumbnail only
opened Properties, which has no pattern controls, so a pattern fill could
not be adjusted after creation.

Both now open Photoshop's Pattern Fill dialog: the pattern swatch picker,
Snap to Origin, Angle, Scale and Link with Layer, previewed live on the
canvas from a document snapshot. OK runs one engine command, so it is one
History step; Cancel changes nothing (a new layer is not created).

- engine: new `layer.fill.pattern.set` (pattern_fill_cmds) edits a Pattern
  Fill's pattern, scale, angle, link and phase in one undo step, validating
  every param; `preview` applies it or `layer.newFillLayer.pattern` to a
  copy of the document for the dialog. `new_fill_layer`'s edit is shared
  as `insert_fill_layer` so the preview is exactly what OK commits.
- ui: pattern_fill_ui (dialog body, OK, canvas preview), routed from the
  menu item (no params) and Layer Content Options; explicit params still
  run the engine directly. Catalog entries for the new strings.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Pattern Fill test: pick the swatch picker's Patterns button (main added a Patterns dock tab)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 09:16:18 -04:00
60339cf675 app.open: open directory .pcraft through the automation read root (#2490) (#2581)
* app.open: open directory .pcraft through the automation read root (#2490)

The native on-disk format is a directory, but the automation read path
serves regular files only, so agents could not open the files the app
itself writes. The format crate's storage seam is now public (ByteSource
+ load_bytes_source); the workspace opens the .pcraft subdirectory through
the held capability and loads through it. app.open tries the directory
form for .pcraft paths and falls back to the bytes path for the
single-file (zip) form; every other format is unchanged.

* app.open .pcraft: review fixes (#2581)

read_entry now bounds the read itself (the stat length is only a buffer
hint) and both directory sources reject non-regular entries, so a crafted
bundle with a FIFO entry can no longer block the open and stream unbounded.
The desktop opener runs under the crash guard like its import sibling, the
zip fallback is structural (Ok(None) instead of an error-message match),
a directory-form document no longer arms a save-back target the file-only
automation writer could never replace, and the open status is translated
(Opened {name}, 16 locales).

* read_entry: saturating max+1 so a usize::MAX budget can't overflow

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 09:12:59 -04:00
10fb9233d5 Tools: wire Enable Flick Panning for the Hand tool (#204) (#2964)
* Tools: wire Enable Flick Panning for the Hand tool (#204)

Preferences > Tools > Enable Flick Panning (default on) was never read.
Like Photoshop, a Hand drag (the selected Hand, the Space-held Hand or a
middle-button drag) released while the pointer is still moving now keeps
the view gliding that way and slows smoothly to a stop; a click, new drag
or key press stops it. Off, the view stops where the drag ended.

flick_pan.rs holds the pure state: the release velocity from the last
80 ms of drag steps, an exponential friction step (tau 0.18 s, so a fast
flick rests in under a second), a start/stop speed threshold, and clamps
for huge, NaN or infinite numbers. The canvas drives it per frame with
request_repaint only while gliding; with Overscroll off the glide is
clamped like the scrollbars and stops at the pan limit.

Settings that do nothing: 43 -> 42 of 149 (docs/scorecard.md).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Preferences: show Enable Flick Panning now that the Hand tool reads it (#204)

Remove tools.enableFlickPanning from prefs::HIDDEN_UNTIL_IMPLEMENTED so the
prefs_usage test passes and the dialog shows it; regenerate the scorecard
(settings that do nothing: 36 of 153) and mark flick panning done in
docs/ui-parity.md.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 09:03:11 -04:00
cb9513c718 Channels: keep RGB off while an alpha or mask is shown, and select from that channel. (#2555)
* Channels: keep RGB off while an alpha or mask is shown, and select from that channel.

Co-authored-by: Cursor <[email protected]>

* Channels: rustfmt the RGB-off view check.

Co-authored-by: Cursor <[email protected]>

* channel view: pass the active layer to render in main's new tests

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 09:03:05 -04:00
026432815c Preferences: wire Tools › Show Transformation Values (#204) (#2953)
* Preferences: wire Tools › Show Transformation Values (#204)

The size and angle readouts beside the pointer (marquee W/H, Crop frame
W/H and angle, Crop Straighten angle) now go through
canvas::draw_value_readout, which draws them only while
tools.showTransformationValues is on, as in Photoshop. The brush HUD
isn't a transformation value and keeps drawing.

The preference leaves HIDDEN_UNTIL_IMPLEMENTED, so Preferences › Tools
shows it (its label is already translated). Settings that do nothing:
43 → 42 of 149.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Contributors: add my display name

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 08:57:49 -04:00
55a617cd66 Place: wire Always Create Smart Objects When Placing (#204) (#2543)
* feat(engine): Always Create Smart Objects When Placing gates the Place layer kind (#204)

* scorecard: regenerate after wiring Always Create Smart Objects When Placing

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 08:51:33 -04:00
a0ff3a01f2 Smart Objects: linked smart objects follow their files while open (#2510)
* Smart Objects: linked smart objects follow their files while open

As Photoshop documents ("Linked Smart Objects update automatically when
the Photoshop document is open, provided the source file has changed"),
a linked smart object whose file another app saves is re-rendered
without Update Modified Content. The desktop app stamps the active
document's linked files (size + modification time) on a worker thread
every two seconds and when its window comes back to the front; each
changed file is one Update Modified Content undo step, independent of
the selected layer. Stamps are kept per document; a file that can't be
read yet leaves no step and is tried again; files changed while the
document was closed still wait for Update Modified Content.
layer.smartObjects.updateChanged runs one look (refused over the
control channel like the other layer.smartObjects commands).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Smart Objects: a linked file that can't be read is tried again once it changes, not on every look

A linked file the automatic update couldn't read (still being written, or a
format smart objects don't read) kept its old stamp, so every two-second look
saw it as changed and read it again on the UI thread. It now keeps its new
stamp and is tried again once it changes again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Katt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 08:42:52 -04:00
David MannandClaude Opus 5.5 f781cb70fc Layers: right-click an effect row for the layer style menu (#2846) (#2950)
Right-clicking the "Effects" row or an effect row under a layer did nothing.
Like Photoshop, it now opens the layer style menu for that layer: Blending
Options, Copy/Paste/Clear Layer Style, Global Light, Create Layer, Hide All
Effects and Scale Effects. Items run the existing commands with menu-item
params (dialogs open as from Layer > Layer Style), selecting the right-clicked
layer first. The item loop of the layer row menu is shared.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-11 08:37:34 -04:00
509b596805 Dropdowns: type a letter to jump to an item, Enter to choose (#1481) (#2948)
As in Photoshop's pop-up menus, typing a letter in an open dropdown list
jumps to the next option starting with it (the same letter again cycles
through them), letters typed within a second match a longer prefix, and
Enter closes the list on the option shown. Matching is case-insensitive
on the translated labels (Unicode lowercase, no byte slicing). While a
dropdown list is open it owns the keyboard like an open menu, so its
letters no longer reach the tool shortcuts.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 08:33:29 -04:00
Ahmed Hosny 3e3e580217 MCP bridge: reconnect before idle sockets die, retry reads, actionable timeouts (#2487) (#2507)
* MCP bridge: reconnect before idle sockets die, retry reads, actionable timeouts (#2487)

The app closes idle control connections after 30s (IO_TIMEOUT) while the
bridge kept one persistent connection, so the first call after a pause
failed with "operation may have completed". The bridge now drops and
reconnects before sending once the connection has been idle 25s, so a
request is never written to a socket the app may have dropped.

The default call timeout drops from 60s to 55s, strictly below the app's
60s reply deadline, so the bridge's own error — naming the method and the
likely causes — is the one callers see instead of a race between the
app's deadline reply and the caller's own cutoff.

Idempotent read methods (ui.inspect and friends) get one automatic retry
on a transport failure; edits keep #1007 semantics and are never resent.
A timed-out call is never retried (it would only double the wait).

* MCP bridge: caller-vouched read retries, per-failure wording, docs contract (#2487 review)

The retry decision moves from a hand-maintained method list — most of whose
entries were engine command ids that never travel as control-protocol
methods, so they could never match — to the call sites that know a call is
a read: call never resends (#1007), call_read retries once on a transport
failure, and the MCP server opts its pure-read tools in. Failures are
worded by what they prove: a connection that could never be established is
"the request was not sent", not "may have completed"; a read timeout says
a read may be retried safely instead of demanding a state inspection. The
55s client cap, the read-retry exception, and the idle reconnect are now
documented in the control protocol and the security book.
2026-10-11 08:29:35 -04:00
ecbd3d78be Toolbar: Pro themes draw tool glyphs at two thirds of the button (#2665) (#2932)
The Pro toolbar drew each tool glyph at 16 px in a 30 px button (the
generic icon-button proportion), which reads small and thin next to
Photoshop's toolbar. Pro themes now draw tool glyphs at 20 px; the other
themes keep the icon-button size.


Claude-Session: https://claude.ai/code/session_01CVtZHu998NDhf4Z8QvS5pd

Co-authored-by: ngrafton2006 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 08:28:38 -04:00
UnemarsandClaude Opus 5.5 0b4b1e4286 Image Size: Photoshop's resampling, measured (#2451)
* Image Size: Photoshop's resampling, measured

Photoshop 25.4's Image Size was measured as a black box (synthetic 16-bit
images in, exact RAW out); every method but Preserve Details' enlargement is
linear, so each was taken apart from its impulse responses.

- Bicubic is the Keys cubic at a = -0.75, not Catmull-Rom.
- Bicubic Smoother (stretched x1.15, a = -0.625) and Bicubic Sharper
  (x1.05, a = -1), with a growing with the reduction, and Bicubic Automatic.
- Reducing widens the filter by 1/s; below 1/4 the image is first averaged
  down to four times the target. Bilinear is never widened and averages
  whole pixels below 1/2. Positions are rounded to 1/128 pixel and stop at
  the edge pixel's centre.
- Two passes, the smaller scale first, clipped and stored between them; the
  bicubic filter is designed for the height's scale and serves both axes.
  Bicubic Automatic splits a mixed resize into Sharper, then Smoother.
- Image Size and Fit Image take automatic, bicubicSmoother, bicubicSharper
  and bicubicAutomatic; the dialog lists Photoshop's methods and opens on
  the interpolation preference.

On 225 probes the mean error falls from 240-550 to under 0.5 levels of
32768; 8-bit results are identical to Photoshop's for 99 % of values.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Format: one rustfmt change main needs

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-11 08:25:21 -04:00
Valentin KleinandClaude Opus 5.5 7107c80042 perf: pasting a layer recomposites only where it draws (#2901) (#2917)
* perf: Duplicate Layer recomposites only where the copy draws (#2883)

Duplicating a layer reported no damage, so the canvas recomposited the
whole document after every Duplicate Layer (P8/P9). The copy itself was
already cheap (tiles are shared Arcs). Report the copy's change bounds
instead, through the step_damage walk extended to bounded additions:
self-contained added layers (not an adjustment, not a new clipping base,
no video or excluded channels) contribute their change bounds; anything
else still recomposites everything.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* perf: pasting a layer recomposites only where it draws (#2901)

Paste (and Paste in Place, Paste Into, Paste Outside) inserted the
pasted layer through Session::edit, which reports no damage, so every
paste recomposited the whole document (P10/P11). Capture the document
before the paste and report the new layer's change bounds with
note_insert, as Duplicate Layer does (#2884). Anything that isn't
self-contained (a new clipping base, video, excluded channels) still
recomposites everything.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 08:24:51 -04:00
ec28fdd03d Add Photoshop-style guide layout dialog and live preview (#2930)
* feat(ui): add guide layout dialog with live preview

* test(ui): restore path helper used by save dialog assertions

* chore(i18n): avoid conflicts with appended catalog entries

* chore: avoid append conflict for contributor credit

* Merge main: one people.toml entry for Skyfuller1303, drop the duplicate joined helper

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 08:23:03 -04:00
Valentin KleinandClaude Opus 5.5 42e4af6416 Tools: Frame tool (#2914) (#2915)
The Frame tool (K, its own toolbar slot after the Crop group) draws a
rectangular or elliptical frame; the options bar picks the shape, Shift
constrains to a square or circle and Alt draws from the centre. A frame
drawn over the selected pixel layer's content takes that layer in;
otherwise it is an empty frame.

Frames are built as Frame from Layers builds them: a group clipped by a
layer mask (rectangular or anti-aliased elliptical). The new engine
command layer.new.frame does it in one Session::edit, so one undo step.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 08:20:15 -04:00
Valentin KleinandClaude Opus 5.5 614d06892c perf: marquee selections on large documents are built row by row (#2888) (#2907)
The Elliptical Marquee tested and wrote every pixel one at a time
(Surface::write_pixel), single-threaded, with no shared full tiles. The
add/subtract/intersect modes read both selections over the whole canvas
into f32 buffers. On 6000x4000 an ellipse took ~0.6-1.1 s and a mode
combination ~0.3-0.5 s.

ellipse_surface builds the shape per row: a run of fully selected pixels
(bounded analytically, checked with the exact f32 tests at both ends)
and edge pixels that get the original per-pixel coverage test. Tiles are
built in parallel, and fully selected tiles share one tile.
combine_surfaces maps two GRAY8 selections tile by tile through a
256x256 byte table, sharing tiles that come through unchanged. Both
produce exactly the old bytes (equivalence test against the old
per-pixel code).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 08:11:17 -04:00
984bc5c715 scorecard: twenty rows describe work that is already in the tree (#2894)
* scorecard: eight Open bugs rows describe work that is already in the tree

AGENTS.md sends contributors to the scorecard's missing and partial rows when
picking work, so a stale row costs someone a session: they sit down to write a
test that is already there. These eight ask for work that exists and is covered
by passing tests.

#205 / #207, mask and channel transforms:
- BUG-205-4 ("no raster-mask test"): linked_raster_mask_moves_with_the_pixels.
- BUG-205-5 ("the other two not implemented"): all three cases are covered, by
  linked_mask_with_a_selection_moves_only_the_selected_region,
  unlinked_mask_stays_put and targeted_unlinked_mask_transforms_alone.
- BUG-207-4 ("transform() has no target handling"): edit.transform takes target
  (pixels, mask, quickMask or {channel: i}) and documents it in its params doc;
  targeted_alpha_channel_transforms_alone covers the alpha channel.

#206, kerning — the whole section:
- BUG-206-1: CharStyle has both `kerning: Kerning` and `kern: f32`.
- BUG-206-2 / BUG-206-3: io/tests/psd_kerning.rs round-trips manual, Off and
  Optical kerning, and reads the AutoKerning flag and Kerning value of every
  character back out of the written TySh.
- BUG-206-4: Alt+Left/Right at a collapsed caret calls kern_pair, and the
  Character panel field parses Metrics / Optical / a manual value; both tested.
- BUG-206-5 stays partial, not done: the round trips are covered, but no oracle
  corpus file is dedicated to kerning values, which that row also asks for.

FILE-216-5 keeps its missing status (no save-path tests for layered TIFF, PDF,
SVG, ACO/ASE, .shc or Smart Filters), but its note claimed there is no
atomic-save failure-injection test; format/src/atomic/tests.rs has two, and
BUG-203-6 already records them as done.

docs/scorecard.md regenerated with cargo xtask scorecard; Open bugs moves from
22/2/8 to 29/2/1.

* scorecard: the Type section's kerning and Thai rows are out of date too

TYPE-218-6 ("Optical renders as Metrics; Alt+arrow moves by word") is done:
Alt+Left/Right at a collapsed caret calls kern_pair, optical kerning is computed
from the glyph outlines in text/src/optical.rs and applied by layout.rs when the
run's mode is Optical, and both modes round-trip through PSD. Covered by
type_tool_alt_arrows_kern_the_pair, optical_matches_photoshop,
optical_kerning_tightens_open_pairs, txt2_carries_optical_kerning and
io/tests/psd_kerning.rs. The row points at #206, whose own rows are in the same
state.

TYPE-218-3 goes to partial, not done: Thai is covered (THAI_FAMILIES in fonts.rs
and thai_in_latin_font_falls_back_to_installed_thai_font, #1909), but Khmer and
Indic have no fallback list and there are still no per-script golden tests.

Unchanged because they read correctly: TYPE-218-1 (TextShape is still Point and
Box), TYPE-218-2 (no direction UI), TYPE-218-4 (the axes in the shell are the
brush's), TYPE-218-8 (no triple or quadruple click) and TYPE-218-9.

* scorecard: Tools and Distribution rows are out of date too

TOOL-213-7 ("Live stroke only for Brush and Eraser"): canvas.rs strokes_live
covers Brush, Pencil, Eraser, Blur, Sharpen, Smudge, Dodge, Burn and Sponge,
and live_retouch_command adds the Clone Stamp, Healing Brush and History Brush.

TOOL-214-8 ("ruler only feeds straighten"): image.rotation.arbitrary opens
seeded with the measured ruler angle and the direction that straightens it;
arbitrary_rotation_starts_at_the_ruler_angle checks 5.7106 deg within 1e-3 and
the direction for three lines.

TOOL-214-5 goes to partial, not done ("No context menu in canvas.rs or
transform_tool.rs"): TRANSFORM_MENU does open on a right click during a
transform, with Free Transform, Scale, Rotate, Skew, Distort, Perspective and
Warp, and three tests cover it — but the row also asks for Flip and
Rotate 90/180, which are not there.

DIST-220-2 ("release.yml only x86_64 and i686 msvc"): the Windows matrix has
{ arch: arm64, target: aarch64-pc-windows-msvc }, and windows-arm64.yml
installs that MSI on a Windows 11 ARM64 runner, checks the binaries are ARM64
and runs the CLI natively. Signing takes the same path as x64 (DIST-2).

Unchanged because they read correctly: the whole Automation section (ABI_VERSION
is still 1 with Kind::Filter only, there is no ONNX dependency, no such xtask
check, and agent_tasks.rs really does run ten scripted tasks), TOOL-213-12,
TOOL-214-4, TOOL-214-6, DIST-220-1 and DIST-220-3.

* scorecard: Workspace and UI and File compatibility rows are out of date too

UI-217-9 ("prefs.rs UiScale unused"): prefs::UiScale offers Auto plus 75 to 300
percent, display_scale resolves it and sync_display_scale applies it with
ctx.set_zoom_factor; being a preference, it is remembered. The zoom_factor
assert the note cites is in a canvas-zoom test, checking that zooming the
document does not scale the interface.

FILE-216-1 ("No corpus step in ci.yml; in progress in #190"): ci.yml has a
corpus job on every PR and on main, pinned, sha256-verified and cached by the
pins. #190 is merged.

UI-217-22 and UI-217-23 go to partial, not done:
- layer.stampVisible merges the visible layers into a new layer and leaves the
  originals, and layer.stampDown exists, but neither has a menu entry and
  Alt+Merge is still missing.
- layer.copyToDocument copies layers into another document keeping masks,
  styles and blending (#589), but there is still no copy/paste layer clipboard.

UI-217-11 keeps missing; only its note changes, from "five themes" to the eight
ThemeKind has. No Soft dark/Soft light, previews or outlined knobs.

Unchanged because they read correctly: UI-217-20 (guides are still Vec<f32> and
there is no rulers preference), FILE-215-6 (SmartObject.transform is still an
Affine), FILE-215-19 (no JPEG Options dialog), and the rest of both sections.

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 08:10:23 -04:00
a874b149f2 Themes: Photoshop's light-gray and light Pro brightness levels (#2661) (#2892)
Photoshop has four interface brightness levels; PhotoCraft had the two
darkest (Pro, Pro Medium Gray). Add the other two with the Pro layout:

- Pro (Light Gray), id proLightGray: #B8B8B8 panels.
- Pro (Light), id proLight: #F0F0F0 panels.

They are light themes: Preferences > Interface lists them under Light
Theme, Window > Theme has an entry for each, and the legacy
interface.theme preference selects and migrates them. ThemeKind::is_pro
replaces the hard-coded Pro | ProMedium checks so the dock keeps the Pro
tab layout on every Pro level. Labels are translated in every catalog.

Tests check the panel greys, ids and names, the darkest-to-lightest
order, and WCAG contrast of text, icons and accent text on every surface.


Claude-Session: https://claude.ai/code/session_01CVtZHu998NDhf4Z8QvS5pd

Co-authored-by: ngrafton2006 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 08:09:05 -04:00
Valentin KleinandClaude Opus 5.5 e7c5df0d69 perf: keep resident GPU tiles when a brush dab grows a layer (#2900) (#2902)
A dab that painted past a layer's stored tiles changed its resident page
region, which recreated the texture and converted and uploaded every tile
of the layer in that page cell again. Copy the overlap from the old
texture on the GPU instead (in its own submission, ahead of the queued
tile writes) and keep its tile map, so only new or changed tiles upload.

32-bit float RGB/gray tiles also convert to RGBA16F straight from their
samples (same bytes as the general path) instead of decoding into a float
buffer and converting pixel by pixel.

P16 (32-bit, 20 layers) brush dab + refresh, median of 6 alternating runs:
p50 8.9 -> 3.1 ms, p95 27.2 -> 7.5 ms. P13 is unchanged (~1.6 / ~4.5 ms).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 08:01:03 -04:00
David MannandClaude Opus 5.5 167ea87ef1 Status bar: buttons sit inside the bar with centred labels (#2823) (#2876)
The Fit button was a full-size 30 pt button in the 30 pt Studio bar and
the zoom field a 24 pt box in the 24 pt Pro bar, so both touched or
overflowed the bar's edges. Inside every value field the theme's 24 pt
interact height and 4 pt button padding made the number taller than its
slot, so it sat low and, in a narrow box, spilled out of the left edge.

The status bar's controls now take a compact height (22 pt in Studio,
18 pt in Pro) from status_bar_heights, leaving even margins, through
new compact_value_field and compact_button widgets. A value field's
number slot is at least one text row tall and the number widget is
sized to it, so the digits sit 1 pt above the box's centre as intended.

With the bar at its true height the canvas shifted by 1 pt, which showed
that the live lasso ants were not on pixel centres; they are now snapped
like the marquee's.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-11 08:00:18 -04:00
Valentin KleinandClaude Opus 5.5 3e90c81e3c perf: Duplicate Layer recomposites only where the copy draws (#2883) (#2884)
Duplicating a layer reported no damage, so the canvas recomposited the
whole document after every Duplicate Layer (P8/P9). The copy itself was
already cheap (tiles are shared Arcs). Report the copy's change bounds
instead, through the step_damage walk extended to bounded additions:
self-contained added layers (not an adjustment, not a new clipping base,
no video or excluded channels) contribute their change bounds; anything
else still recomposites everything.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 07:56:05 -04:00
SkyfullerandBrandon Thomas 51f0a287b1 Refine gradient stop controls in Properties and Gradient Editor (#2859)
* feat(ui): refine gradient fill properties

* feat(ui): use combined stops in Gradient Editor

* test(ui): restore cross-platform save path helper

* Refine Properties with a shared gradient ramp

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 07:54:47 -04:00
Valentin KleinandClaude Opus 5.5 9b3c6359ae perf: Select > Modify > Feather/Smooth on 24 MP within budget (#2873) (#2882)
The blur itself was already parallel (9-15 ms on 24 MP); most of the
command was serial glue around it. Modify copied the mask into a padded
buffer and back out sample by sample even with no padding, and combine
built a full-canvas byte buffer, scanned it, then copied it into tiles
on one thread.

- modify: use the mask as is when the selection is clear of the canvas
  edge (pad 0); pad and crop row by row otherwise.
- combine / mask_to_surface: fill selection tiles in parallel straight
  from the mask, a row at a time; fully selected tiles share one
  copy-on-write tile.

Bit-identical: the per-sample oracles (combine, now with whole tiles,
and the old pad/crop) are compared in tests.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 07:48:51 -04:00
c732ecd5b0 Dropdowns: press, drag onto an option and release to choose it (#2735) (#2854)
A dropdown needed two clicks: egui's ComboBox opens its list on a whole
click and its rows only take clicks, so press-drag-release (as the menus
do since #775) chose nothing. press_menu::PressCombo gives combo boxes the
gesture without replacing egui's widget:

- after the box, a primary press on it opens the closed list (egui counts
  a popup opened in a pass as open, so it is drawn from the next frame);
- a row released on by that press-drag is chosen and closes the list;
- on the click that ends the press (pointer still on the box), egui would
  toggle the list shut, so it is closed just before the box and egui's
  toggle reopens it, drawn that frame: a plain click still leaves the list
  open for a second click.

widgets::dropdown (and its hovered/wheel variants), dropdown_with_tooltips,
the font family picker, the kerning presets, the Gradient Map presets, the
shape stroke choices and the credits sort all use it.

Co-authored-by: lloyd <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 07:46:46 -04:00
Valentin KleinandClaude Opus 5.5 a030d19437 perf: repeated Select Subject answers from the last mask (#2865) (#2870)
Select Subject recomputed superpixels, saliency, GrabCut and the
full-resolution re-cut on every call (P29: 260-370 ms on 24 MP here,
693 ms p95 in the baseline). The session now keeps the last result,
keyed by the pixels it came from: `same_pixels` (tile pointers) against
a weakly held document, plus the sampled target (composite or layer).
Selection-only edits such as Deselect keep it valid; the mode
(replace/add/subtract/intersect) is still applied each time. One entry
per session, dropped on pixel edits and when its document closes.

Repeat: 7-10 ms p95 (was 270-370 ms). First run unchanged.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 07:44:00 -04:00
David MannandClaude Opus 5.5 79e8ad35a6 Text fields: drag-selecting in a single-line field follows the pointer's x (#1946) (#2821)
egui's TextEdit picks the character under the pointer with
Galley::cursor_from_pos, which returns the start of the text when the
pointer is more than 5 points above the first row and the end when it is
below the last one, for single-line fields too. So dragging up selected
everything left of the anchor and dragging down everything right of it.

A small egui plugin, installed by PhotocraftApp::setup_context, keeps the
pointer's y on the text row of the focused single-line field while the
primary button pressed in it is held, before egui sees the input. The x is
untouched, so the selection follows it, as in Photoshop and native fields.
It covers every single-line TextEdit, number fields being typed into
included; a multi-line field (taller than two widget heights) keeps its
vertical drag.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-11 07:41:27 -04:00
1d425ce8f9 Actions: check boxes switch single steps on and off (#2855) (#2866)
Photoshop's Actions panel has a check column: an unchecked step is skipped
by playback, Batch and droplets. PhotoCraft could reorder and delete single
steps but always ran every step.

- Action gains `disabled` (0-based step indices, omitted from actions.json
  when empty), kept in step with actions.move and actions.delete.
- New command actions.toggle {action, step?, enabled?}: one step, or every
  step like the action's own check; bad indices and types are errors.
- actions.play, the desktop playback path and the steps handed to Batch and
  Create Droplet skip unchecked steps; actions.get reports `disabled`.
- Panel: a check box per step, dimmed label when off, "2/3 steps" count.

Part of #219 (AUTO-219-2).

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 07:39:35 -04:00
Valentin KleinandClaude Opus 5.5 017d1aea1c Tools: Perspective Crop (#1043) (#2864)
New Perspective Crop tool in the Crop flyout (C): drag a box or click four
corners, drag corners independently onto a skewed object, perspective grid
(Show Grid), Enter commits, Esc cancels. W/H/Resolution come from the Crop
tool's fields (Front Image, Clear), or the quad's mean side lengths.

Engine: image.perspectiveCrop {corners, width?, height?, resolution?,
interpolation?} maps the quad onto an upright canvas through the
quad-to-rectangle homography (Heckbert's square-to-quad map, inverted):
every raster layer, mask, alpha channel and the Quick Mask, one undo step.
The Background stays opaque over the background colour; type, shape, fill
and smart object layers are rasterized first; vector geometry follows the
nearest affine map. Non-convex, self-crossing, counter-clockwise or
degenerate quads are refused with an error.

algo: warp_surface_clipped bounds the per-tile warp by the new canvas even
when a layer reaches past the map's horizon; convex_quad, quad_size,
quad_to_rect.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 07:28:11 -04:00
2e0c426692 Tools: Artboard tool (#2858) (#2862)
Photoshop's Artboard tool in the Move flyout (V, ⇧V cycles Move ↔ Artboard):
dragging on an empty spot draws a new board (`layer.new.artboard`), clicking a
board selects it, dragging it moves it with its contents, and the selected
board's edge and corner handles resize it (`layer.artboard.set`,
moveContents: false). Each gesture is one undo step. Options bar: Size preset,
W/H, Make Portrait, Make Landscape, Add New Artboard. Original toolbar glyph
(assets/icons/artboard.svg, ATTRIBUTION.md row).

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 07:12:53 -04:00
1f64daeba4 Speed up large feathered mask refreshes (#2417)
* Speed up large feathered mask refreshes

* Format preference label for workspace check

* gpu test: allow float noise on a one-code vector-mask parity step

The combined mask is cached as U16 now; one pixel lands exactly one 8-bit
code apart (1.0000075/255), within the <=1/255 parity rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 07:09:04 -04:00
5866cd2cf6 Tools: Horizontal and Vertical Type Mask (#1055) (#2861)
The Type flyout (T, Shift+T cycle) gains Vertical Type Mask and Horizontal
Type Mask, in Photoshop's order. They type like the Type tools, with the
canvas under Quick Mask's colour and the glyphs clear while editing. On
commit the glyph coverage replaces the selection; no layer is left behind
and the whole session is one "Type Mask" history step. Escape always
cancels and leaves the selection unchanged.

The commit runs a new engine command, type.createSelection: a type layer's
glyphs (optionally removing that layer, the tools' hidden working text) or
type.create's keys directly, with new/add/subtract/intersect and an
anti-aliasing override. type.create's layer building is shared through
type_cmds::new_text_layer.

Original dashed-T icons (ATTRIBUTION.md), tool label translations in every
catalog, README tool list and the gaps/parity docs updated.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 07:06:10 -04:00
c436aa7294 Tools: Freeform Pen and Curvature Pen (#1054) (#2856)
The Pen flyout (P / Shift+P) now holds Pen, Freeform Pen and Curvature Pen.

Freeform Pen: a drag draws freehand; on release the trace is fitted with
cubic Beziers within the options bar's Curve Fit (default 2 px) by
photocraft_vector::trace::fit_trace (Schneider, "An Algorithm for
Automatically Fitting Digitized Curves", Graphics Gems 1990, the fitting
Make Work Path already uses), keeping turns sharper than 60 degrees as
corners. Releasing on the start point closes the path.

Curvature Pen: each click adds a smooth point and the path runs through
every point (Catmull-Rom style handles from
photocraft_vector::edit::curvature_knots); dragging a point moves it,
double-clicking toggles corner/smooth, clicking the first point closes,
Enter/Esc finish and Backspace removes the last point, as with the Pen.

Both commit through the Pen's path: a shape layer in Shape mode, else the
targeted vector mask, else the work path, as one History step.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 06:56:44 -04:00
3af4c46a18 View: Pattern Preview tiles the document around the canvas (#1067) (#2803)
View > Pattern Preview only toggled a flag that nothing read. With it on, the
canvas now draws the document repeated around itself as a seamless tile, like
Photoshop, on the GPU canvas and the CPU fallback:

- pattern_preview.rs works out which copies cover the visible area (at most
  31 per axis, centred on the view).
- GPU: each copy is another paint callback over the same document texture,
  offset by whole document sizes in the shader (ViewParams::offset, the spare
  view-uniform slots), so nothing is composited again and seams are exact.
- CPU: the same texture drawn again with a shifted view mapping.
- The drop shadow is off while tiling; selection, guides and other overlays
  stay on the document itself.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 06:51:50 -04:00
bacc825d33 Move tool: drag a marquee from an empty spot to select the layers it touches (#2844) (#2852)
With Auto-Select on (or Cmd held with it off), a Move-tool drag that starts where
no layer has pixels (an empty spot, or the pasteboard) now draws a marquee instead
of moving the previously selected layer. Releasing selects every layer whose
content touches it (Auto-Select: Group selects their outermost groups); Shift adds.

New engine command layer.selectInRect; the UI side lives in move_box.rs.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 06:47:53 -04:00
20dab123fb Free Transform: oriented rotate cursor and live transform readout (#1767) (#2809)
The rotate zone drew its own fixed arc with hard-coded black and white,
and the angle was bare white text that vanished over light images. W/H
and the move offset were not shown at all.

The rotate zone now uses the Crop tool's turn cursor (theme tokens),
bent round the nearest corner through the view, so it follows a turned
or flipped view. While dragging, the shared rounded readout beside the
pointer shows the angle (document-relative, one decimal), W/H in
percent while scaling, or the offset while moving, like Photoshop's
Show Transformation Values. live_readout() exposes the value for tests.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 06:40:41 -04:00
Valentin KleinandClaude Opus 5.5 7609834df8 Channels: Edit › Transform works on a targeted alpha channel (#2835) (#2845)
edit.transform without a "target" (or "layer") param now follows the
Channels panel: a targeted alpha channel or the Quick Mask transforms
instead of the layer. Edit › Transform › Rotate 180°/90° and Flip
Horizontal/Vertical are routed to the panel target like the paint and
filter commands, so they turn a targeted alpha channel, the Quick Mask or
an unlinked layer mask within its frame (one undo step). The Background
no longer greys the transforms when a channel is targeted.

Flips scorecard row BUG-207-4.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 06:38:36 -04:00
d79fc5e8ef Free Transform: right-click menu with the transform modes, rotate and flip (#2832) (#2840)
The Free Transform context menu listed only the modes. It now follows
Photoshop's order: the modes, then Content-Aware Scale and Puppet Warp
(greyed while a box is open), Rotate 180°, Rotate 90° CW and CCW, and Flip
Horizontal and Vertical.

The Rotate and Flip items, whether chosen from this menu, Edit › Transform,
a shortcut or the control channel, now turn or mirror the live box about its
reference point without committing it (transform_tool::intercept). Before,
they ran the engine preset on the layer under the open box. They are greyed
while warping. Distort and Perspective are greyed over a box on editable
type, matching #2701. A control-channel right-click during a transform opens
the same menu as the canvas.

Scorecard TOOL-214-5 is now done.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 06:30:33 -04:00
830541ded2 Options bar: Reset Tool and Reset All Tools (#2825) (#2830)
* Options bar: Reset Tool and Reset All Tools (#2825)

Right-click the tool icon at the far left of the options bar for Reset
Tool (the current tool's options back to their defaults) and Reset All
Tools (asks "Reset all tools to their default settings?", then resets
every tool's options), as in Photoshop. Both are shell commands,
tool.reset and tool.resetAll, so the control channel can run them;
tool.resetAll opens the confirmation as a dialog, or skips it with
{"confirmed": true}.

ToolOptions is one struct, so tool_reset::reset_options maps each tool
to its fields; fields shared between tools (Tolerance, Anti-alias,
Feather, Strength, ...) reset with any tool that shows them. Selection
tools also go back to New Selection, and painting tools get the default
brush (colours kept).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reset Tool: cover Color Replacement, the anchor point tools and the crop custom ratio

Tools and options that landed on main since the branch was cut.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 06:26:26 -04:00
203b5796b4 Tools: remember tool options between launches (#2814) (#2822)
* Tools: remember tool options between launches (#2814)

The options-bar settings in ToolOptions (Move > Auto-Select, marquee
Feather, tolerance, gradient style, crop ratio, eyedropper sample, ...)
only went through serde for Tool Presets, so every launch started from
the defaults. Photoshop keeps each tool's options between sessions.

Preferences gain `toolOptions` (shell-owned JSON, like brushPicker): the
fields that differ from their defaults, saved once the pointer is up and
restored at launch field by field. An unknown key is ignored; a field
that doesn't read back (wrong type, a number out of f32 range) keeps its
default with a log warning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Merge upstream/main into fix/2814-persist-tool-options; regenerate docs/scorecard.md

The branch adds a preference, so the prefs audit count in docs/scorecard.md changes
(CI's xtask scorecard staleness test).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 06:20:17 -04:00
mattyandBrandon Thomas ac19db1046 TGA: targa options asks for 24 or 32 bits/pixel, same as in Photoshop (#2760)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 06:17:53 -04:00
Valentin KleinandClaude Opus 5.5 273ff014e3 Layers: double-click a shape layer's thumbnail to pick its fill colour (#2812) (#2820)
Like Photoshop, double-clicking a solid-colour shape layer's thumbnail (or
Layer > Layer Content Options...) opens the Color Picker on the shape's fill.
The canvas previews the pick, Cancel changes nothing and OK commits one
undoable shape.edit with the new fill (keeping the fill's alpha). Gradient,
pattern or no-fill shapes keep opening their Properties controls.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 06:12:57 -04:00
Valentin KleinandClaude Opus 5.5 1608b7b309 Spot Healing: Content-Aware dab no longer scans every patch in full (#2771) (#2805)
A Content-Aware Spot Healing dab spent ~70 % of its time in inpaint's
onion_peel: at the coarsest pyramid level every hole pixel computed the
full 7x7 SSD against every valid source patch. The pyramid and the
sampling window scale with the dab, so this cost ~200-450 ms whatever
the brush size.

The scan is still exhaustive and picks exactly the same source (first
minimum in source order): the target's known offsets and samples are
gathered once, the filled neighbours' sources (shifted, as in PatchMatch
propagation; every 16th source at the hole's edge) give an upper bound,
and each candidate's sum is abandoned once it can no longer win. Sums
keep their order and only grow, so the result is bit-identical.

PatchMatch: the vote weight exp(-cost/2s^2) is computed once per target
instead of once per covered pixel, and dist has a fast path (row slices,
same summation order) for patches fully inside a level with no void.

retouch_bench (6016x6016 8-bit, best of 3 rounds x 5 dabs, loaded
machine): 50 px 178 -> 63 ms, 100 px 190 -> 75 ms, 200 px 226 -> 118 ms,
300 px 239 -> 186 ms; 4.5x fewer instructions. Healed pixels of all
three Spot Healing types are bit-identical at 8 and 16 bit.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 06:08:21 -04:00
Valentin KleinandClaude Opus 5.5 b7b3117aea Droplets: carry the actions their Play Action steps call (#2794) (#2800)
* Batch: a failed step inside a called action fails the file and the script (#2779)

Scripts (File › Scripts › Browse, Script Events) ignored the `failed` entry that
`actions.play` returns when a step inside the called action fails, so they reported
ok and kept going. Batch and droplets ran each file in a scratch session without
the actions list, so any nested action call failed with "no action named". The
scratch session now gets the caller's actions and playback stack (an action that
batches itself is caught as recursive), and both runners check nested_failure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Droplets: carry the actions their Play Action steps call (#2794)

createDroplet saved only the chosen action's own steps, so a droplet whose
action plays another action failed on every file when run outside the
creating session (photocraft-cli droplet and the .command shim run it in a
fresh Session with no actions).

createDroplet now embeds the called actions, followed transitively with a
seen-set and the 16-level playback cap, under "calledActions" (not
"actions", which the CLI reads as an action set). Index references become
names. runDroplet passes them to file.automate.batch, whose per-file
sessions then play from them. Droplets without the key behave as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Droplets test: build Actions from JSON so the test survives new Action fields

#2866 adds Action.disabled; a struct literal here would stop compiling once both land.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 06:06:20 -04:00
Valentin KleinandClaude Opus 5.5 009bef76e7 CLI: batch plays an action from an Actions set with the whole set loaded (#2786) (#2792)
`batch --actions` ran each file in a fresh headless session with no
actions, so a step that plays another action (`actions.play`) failed for
every file, and the Actions panel's own actions.json could not be passed
at all. `--actions` now also takes an Actions set; `--action <name>`
picks the action to play and every per-file session gets the whole set.
A failed step inside a called action fails the file instead of saving it.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 06:01:07 -04:00
80519e1a17 Type: ⇧⌘> / ⇧⌘< change the type size (and work on Nordic/German layouts) (#2402)
* feat(type): Cmd+Shift+> / < change the type size, Alt for 10 pt steps

Photoshop's type size shortcuts: the selected characters while typing,
else the whole active type layer, in the points the layer shows. The
period and comma keys match by position so the shortcuts also work on
Nordic and German layouts, where Shift+. types a colon.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(type): bad size steps fall back or clamp

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 05:56:28 -04:00
aa509ca966 UI fonts: lazy fallback for Thai, Arabic, Indic and other scripts (#2275) (#2758)
Layer names (and any other UI text) in scripts the bundled Inter lacks
showed missing-glyph boxes even when the canvas found a fallback font.
The lazy UI loader only knew CJK plus a short hard-coded list of Thai
font paths, so any other script, or a Thai font at another path, never
got a fallback.

photocraft_text::scripts classifies 20 scripts and picks candidate files
by name (Noto, Windows, macOS and common Linux families) from a listing
of the platform font directories, made once per process on first need.
The UI loader tries a script once when one of its characters is missing,
reads at most a few candidates, and registers the first face whose cmap
really maps the character. Latin text loads nothing; the web build has
no candidates and does nothing.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 05:55:39 -04:00
2189a1610e fix(crop): stabilize resizing and apply ratio changes immediately (#3206)
Compute snapped handles from press-time geometry to avoid feedback from
Auto Center Preview. Paint the image and crop frame with the same camera.

Apply ratio and size options immediately as centred rectangles contained
in the current frame. Respect saved ratios, keep Swap and X consistent,
and let Enter apply output sizes without an initial resize.

Use container padding for the options bar's text allowance so right-aligned
crop actions do not introduce horizontal overflow.

Add regression coverage for handle snapping, rendered frames, preset/Enter
and Swap/X interactions, and options-bar scrolling at multiple UI scales.
Enable public GitHub profile name syncing for TheTeslak's contributor credit.

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 05:54:09 -04:00
d96bb50161 Add Anchor Point and Delete Anchor Point tools (#1044) (#2756)
Paths could be reshaped after drawing since #865, but the number of
anchors could not change. Two new engine commands do that, and two tools
in the Pen flyout drive them on the canvas.

- photocraft_vector::edit::add_anchor splits the segment at t with de
  Casteljau, so a curve keeps its shape and gets a smooth anchor; a
  straight segment gets a corner on the line. delete_anchor joins the
  neighbours keeping their handles, drops an emptied subpath and refuses
  to remove a path's only anchor.
- path.addAnchor / path.deleteAnchor take the same targets as the other
  point edits (work path, saved path by name, shape layer path, vector
  mask) and record one history step each.
- Tool::AddAnchorPoint / DeleteAnchorPoint join the P group after the Pen.
  They act on Direct Selection's paths, highlight the segment or anchor
  under the pointer, show a +/- cursor badge, swap with Alt and turn into
  Direct Selection with Cmd/Ctrl. An edit clears a Direct Selection on the
  same path so it never points at a shifted anchor.
- Icons derived from Lucide pen-tool (ATTRIBUTION.md), hints and tool
  names in all 16 catalogs, README tool list, roadmap.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 05:48:07 -04:00
303b7849e8 raw: fit non-DNG colour to the camera's embedded JPEG (#2135)
* raw: fit non-DNG colour to the camera's embedded JPEG

* raw look: clippy (as_chunks) and rustfmt after merging main

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 05:45:46 -04:00
1d67cae1ba Keep custom crop ratio fields editable (#3209)
* Keep custom crop ratio input fields

* Persist custom crop ratio values

* Wire custom ratio edits to persistent option state

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 05:41:44 -04:00
59da288daa fix(type): preserve formatting for trailing empty paragraphs (#3198)
* fix(type): preserve formatting for trailing empty paragraphs

Represent an explicitly styled terminal empty paragraph with a zero-byte paragraph run, keep it through normalization, style only the caret's paragraph, and transfer that style when text is inserted at EOF. Cover line geometry, typing, and PSD text serialization.

* fix(type): retain imported terminal paragraph marker style

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 05:36:52 -04:00
11817fcb12 Test Move layer edges across bit depths and view modes (#2738)
* Test Move layer edges across bit depths and view modes

* Layer Edges tests: set ViewXform's new aspect field after merging main

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 05:36:25 -04:00
468b8f2792 Crop tool: New / Delete Crop Preset saves and removes user presets (#1919) (#2723)
* Crop tool: New / Delete Crop Preset saves and removes user presets (#1919)

The Crop options-bar dropdown ends with New Crop Preset... and Delete Crop
Preset..., as in Photoshop. A crop preset is a "crop" tool preset
(tool.presets.*, persisted with the preferences), so it also shows in the
Tool Presets panel. New saves W x H x Resolution (W, H, resolution and
unit) or a ratio under a name made from the values; it is greyed out with
nothing to save. Delete lists the saved crop presets for a multi-select;
built-in size presets stay. The dropdown shows the preset the fields hold.

Engine: tool preset names are checked (1-255 chars) and the store capped;
saved tool presets load entry by entry so a damaged one is skipped; a
multi-name delete is all or nothing. ui.dialog.open gains newCropPreset /
deleteCropPreset.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Regenerate the scorecard after rebasing onto main

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 05:31:19 -04:00
8a9f4722d2 fix(shapes): preserve transformed outline on unchanged live geometry edits (#3197)
* fix(shapes): preserve transformed outline on unchanged live geometry edit

A nonuniform scale stores an anisotropic outline but live rounded rectangles only store scalar corner radii. Avoid regenerating the path when all live values are unchanged, preserving transformed corners and PSD vector source. Cover no-op edits, real radius edits and undo at all depths.

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 05:23:55 -04:00
073e1cc1d2 Add the Color Replacement tool to the Brush toolbar group (#1045) (#2719)
The engine already had paint.colorReplacement, but the desktop UI had no
tool for it: no Tool entry, no toolbar slot, no options bar and no stroke
routing, so only agents and the CLI could use it.

Tool::ColorReplacement joins the Brush (B) flyout after the Mixer Brush,
so B / Shift+B cycle to it and ui.set / ui.inspect name it. Its options bar
has Mode, Sampling (Continuous / Once / Background Swatch), Limits,
Tolerance and Anti-alias, all mapped to the command's params, with the
foreground as the replacement colour. Strokes are drawn live through
LiveDab, which can now preview the stroke's finishing dab, so the preview
at the last move matches the commit. The command refuses a mask, channel
or Quick Mask target instead of silently recolouring the layer. New icon
derived from Lucide's brush; label translated in all 16 catalogs.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 05:20:00 -04:00
Nigel Ihza Firdausy d8217b3476 fix(image): keep smart-filter masks aligned through Image Size, Canvas Size and Crop (#3195) 2026-10-11 05:18:52 -04:00
094d0776d1 Improve zoomed Liquify preview detail (#2715)
* Improve zoomed Liquify preview detail

* Record Liquify quick benchmark results

* Keep the roadmap as on main; record the Liquify numbers in target-app-parity.md

The branch carried an old copy of the roadmap's parity tables, which have moved
to docs/target-app-parity.md on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 05:03:10 -04:00
09d079278e fix(video): retain original footage for Restore Frame and Show Altered Video (#3192)
* fix(video): retain original footage for restore and comparison (#3059, #3060)

* Clamp original-frame inserts to the original stack; cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 05:02:29 -04:00
Reynold HuandBrandon Thomas 67e3d9be9f feat(ui): Font Preview Size drives the font menu samples (#204) (#2668)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 04:52:17 -04:00
6cfed3a7dc fix(masks): bake feathered coverage when applying pixel masks (#3044) (#3191)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 04:49:03 -04:00
e46f119e03 i18n test: scan past small test modules; translate what it was missing (#2660)
every_tl_literal_is_translated cut each source file at its first `#[cfg(test)] mod`, so a small
test module early in a file hid every tl!("…") after it. panels.rs has one around line 540,
which left most of the toolbar options, the Layers panel and the Properties panel unchecked:
112 literals were never scanned.

The scan now removes each test module on its own (brace counting; a #[cfg(test)] on a single
item still doesn't count), with a unit test for the helper.

The strings it now finds are translated: 69 in Russian (most of the Layers panel and toolbar
tooltips), and the crop, lasso, zoom and fill hints in cs, de, es, fr, id, it, ja, ko, pl, pt-br,
uk, zh-hans and zh-hant. Translations reuse each catalog's existing terms; a native review is
welcome.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 04:39:45 -04:00
01833cfac2 fix(actions): avoid replaying Browse script edits twice (#3190)
* fix(actions): avoid replaying Browse scripts twice (#3057)

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 04:38:07 -04:00
21326ded43 fix(vector): preserve scaled live-line thickness during endpoint edits (#3184)
* fix(vector): keep scaled live-line weight after editing endpoints (#3063)

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 04:31:47 -04:00
Reynold HuandBrandon Thomas 93f2ff835a feat(ui): Beep When Done plays the platform beep for finished jobs (#204) (#2658)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 04:29:59 -04:00
a9aabcdfde fix(vector): pivot explicit path transforms on target layer (#3062) (#3183)
* fix(vector): pivot explicit path transforms on target layer (#3062)

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 04:23:08 -04:00
233237e9dc Reject bad params in the control channel's synthetic input methods (#2449) (#2656)
ui.pointer, ui.click/ui.move, ui.key and ui.screenshot read every value
with as_f64/as_bool/as_str and fell back to a default on any other type,
and an unknown button or event kind fell through to a left click or a
move. A typo such as "button":"ritgh" ran a different action and still
replied ok.

Each method now validates its whole request before acting, like ui.set:
unknown fields (top-level, under modifiers, or in an event), wrong JSON
types, unknown button/kind/tool values (the error lists the accepted
ones) and out-of-range pressure, tilt and rotation return an error that
names the parameter, and nothing is queued or applied. Null fields still
mean omitted, and valid calls behave as before.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 04:18:18 -04:00
f6dd0aa6f3 fix(io): preserve group fill opacity in OpenRaster exports (#3181)
* fix(io): preserve group fill opacity when exporting OpenRaster (#3048)

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 04:16:30 -04:00
458870dadc Auto-Blend Stack Images: fuse the merged layer per pyramid level by region energy, with halo control (#2044)
* Auto-Align Layers: register focus and exposure brackets by intensity when there is nothing to match

Feature matching fails outright on layers that nearly coincide (a focus bracket: sub-pixel shifts, up to a few percent of scale from focus breathing, much of every frame defocused). `photocraft_algo::direct` registers the target to the reference coarse-to-fine on a Gaussian pyramid of the luminance, the cost the mean-removed RMS of the warped difference over the pixels both cover, by a bounded Nelder-Mead search with a per-level schedule; the pose is a similarity about the centre, affine or projective per the projection, and resolution independent, so the search stops short of full resolution. `edit.autoAlignLayers` gets `registration`: auto (features, then intensity when nothing matches), features, intensity; layers register outward from the reference, each to the previous one aligned.

Closes #2064.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Intensity registration: reject a no-fit, search on coarsened planes

Review follow-up on #2065:
- `direct::cost` also returns the correlation of the reference with the
  warped target over the overlap; `Registration.correlation` carries it.
  Unlike the mean-removed RMS it is exposure independent, so it tells a
  bracket (near 1) from unrelated pictures (near 0).
- `register_direct` fails with the existing "couldn't find enough matching
  detail" error when a layer's best pose overlaps its neighbour by less than
  a quarter of the plane or correlates below 0.5, instead of placing it at
  whatever pose the search box ended at.
- The luminance planes are built at the search scale (`luma_alpha` with the
  reduction factor, ≤ 2048 px across) and the warp of each registered layer
  runs there too; the pose is resolution independent and its matrix at full
  resolution places the layer. Nothing full-resolution is held.
- The reference index is checked once with `get`; no unclamped indexing.
- Tests: correlation at an exposure step, for unrelated textures and a flat
  plane; the engine rejects unrelated layers and a mostly empty one.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Auto-Blend Stack Images: fuse the merged layer per pyramid level by region energy, with halo control

The merged layer of Edit › Auto-Blend Layers › Stack Images was the per-pixel masks blended with a multiresolution spline, so a wrong pick in the mask reached every scale. `pyramid::fuse_stack` fuses the layers on the Laplacian pyramid instead: per coefficient the layer with the largest region energy of its luminance band wins (Adelson et al. 1984's multifocus composite with Wang & Chang 2011's rules), the residual follows local deviation + entropy, and with halo control the levels coarser than the guide are weighed by the guide's energy so a bright object's defocused glow stays out. `haloControl` (0..8, default 2) on `edit.autoBlendLayers`; the masks and the panorama method are unchanged.

Closes #2043.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 04:13:11 -04:00
5c9d9116bc fix(layers): select Shift ranges in visible panel row order (#3041) (#3180)
* fix(layers): select Shift ranges in visible panel row order (#3041)

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 04:12:27 -04:00
Lyraedan f11380d5bd Double-clicking a mask thumbnail in the Layers panel now opens that mask's settings (#2654)
* Double-click a layer mask thumbnail to open its settings

Double-clicking a mask thumbnail in the Layers panel now opens that mask's settings in the Properties panel, matching Photoshop. When the Preferences ▸ Tools ▸ "Double Click Layer Mask Launches Select and Mask" option is on (the current default) a pixel mask still launches Select and Mask, exactly as before; with it off, double-clicking targets the mask and opens its Properties (Density/Feather). Vector masks now behave consistently too: double-clicking one targets it and opens a new Vector Mask Properties section.

* Fixed syntax issue from merge

* Fixed missing closed brace in ui tests
2026-10-11 04:11:35 -04:00
ragtuxandClaude Fable 5.1 ec60f43b5b Auto-Align Layers: register focus and exposure brackets by intensity when there is nothing to match (#2065)
* Auto-Align Layers: register focus and exposure brackets by intensity when there is nothing to match

Feature matching fails outright on layers that nearly coincide (a focus bracket: sub-pixel shifts, up to a few percent of scale from focus breathing, much of every frame defocused). `photocraft_algo::direct` registers the target to the reference coarse-to-fine on a Gaussian pyramid of the luminance, the cost the mean-removed RMS of the warped difference over the pixels both cover, by a bounded Nelder-Mead search with a per-level schedule; the pose is a similarity about the centre, affine or projective per the projection, and resolution independent, so the search stops short of full resolution. `edit.autoAlignLayers` gets `registration`: auto (features, then intensity when nothing matches), features, intensity; layers register outward from the reference, each to the previous one aligned.

Closes #2064.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Intensity registration: reject a no-fit, search on coarsened planes

Review follow-up on #2065:
- `direct::cost` also returns the correlation of the reference with the
  warped target over the overlap; `Registration.correlation` carries it.
  Unlike the mean-removed RMS it is exposure independent, so it tells a
  bracket (near 1) from unrelated pictures (near 0).
- `register_direct` fails with the existing "couldn't find enough matching
  detail" error when a layer's best pose overlaps its neighbour by less than
  a quarter of the plane or correlates below 0.5, instead of placing it at
  whatever pose the search box ended at.
- The luminance planes are built at the search scale (`luma_alpha` with the
  reduction factor, ≤ 2048 px across) and the warp of each registered layer
  runs there too; the pose is resolution independent and its matrix at full
  resolution places the layer. Nothing full-resolution is held.
- The reference index is checked once with `get`; no unclamped indexing.
- Tests: correlation at an exposure step, for unrelated textures and a flat
  plane; the engine rejects unrelated layers and a mostly empty one.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
2026-10-11 04:02:26 -04:00
Nigel Ihza Firdausy 37929405df fix(history): restore empty layer target on undo and redo (#3042) (#3179) 2026-10-11 04:02:23 -04:00
Reynold HuandBrandon Thomas fa2fe1c90f feat(ui): the brush HUD honors Vary Round Brush Hardness and Brush Preview Color (#204) (#2640)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 03:59:04 -04:00
64ec252dbe fix(layers): remap linked-layer groups when copying between documents (#3178)
* fix(layers): remap link groups when copying across documents (#3045)

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 03:48:33 -04:00
cf83e05821 fix(psd): Improve interoperability and decoding (#1955)
* fix(psd): Align global tagged blocks to four bytes

Use four-byte defaults for global blocks and streamed layer information.
Read global payloads without full copies while preserving block order,
explicit padding and the first layer candidate. Keep two-byte layer
alignment; test canonical padding and lossless PSD/PSB parsing.

* fix(psd): Preserve transparent composite colours and precision

* fix(psd): Check ZIP integrity and bound layer previews

* fix(io): Use document CMYK profiles for PSD fill pixels

Generated fill pixels used the default CMYK separation even when the PSD
embedded a different profile. Scope layer export to the document colour
space so cached pixels and the composite use the same profile.

Check native cached samples against an explicit ICC transform at 8 and
16 bits.

* io: refuse an empty RGB composite before splitting it into planes

chunks_exact(0) panics; an empty decoded composite now returns an error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 03:46:52 -04:00
cfd12263af Rulers: keep tick marks and labels out of the origin corner (#2617)
* Rulers: clip tick marks and labels outside the origin corner

* Rulers test: set ViewXform's new aspect field after merging main

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 03:46:29 -04:00
Nigel Ihza Firdausy 3188866b25 fix(masks): retain off-canvas alpha in From Transparency (#3043) (#3177) 2026-10-11 03:43:18 -04:00
2785699464 fix(type): use the correct line at soft-wrap caret boundaries (#3174)
* fix(type): use the next visual line at shared wrap boundaries

At soft-wrap and forced-break character offsets, resolve the caret's visual line from the last matching line rather than the preceding one. Make line-edge navigation share that choice and add regression tests for wrapped, forced and paragraph breaks.

* test(type): use actual break characters in caret boundary regressions

* fix(type): preserve the visual line when hit testing a shared wrap offset

Keep caret index preference on the following line, but use pointer geometry for click-hit line identity at an adjacent line's end.

* Update the caret round-trip test for wrap-boundary lines; cargo fmt

The existing round-trip helper expected the first line containing a
shared soft-wrap offset; the caret now reports the following line, where
it is drawn and where hit testing lands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 03:37:27 -04:00
Reynold HuandBrandon Thomas de58a0a778 feat(ui): the Type units preference drives the type metric units (#204) (#2587)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 03:37:06 -04:00
334ae5779c Enhanced Controls: wire Zoom with Trackpad Pinch (#204) (#2577)
* feat(ui): Zoom with Trackpad Pinch gates the canvas pinch (#204)

* Navigator: pass the pinch preference to wheel_nav::read (new caller on main)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 03:26:07 -04:00
ee3839955b fix(type): exclude text inside hidden groups from automatic hit testing (#3173)
* fix(type): skip text in hidden ancestor groups during automatic hit testing

Honor the effective visibility of every ancestor when locating a type layer by point. Explicit layer targeting remains available, with a regression test for nested hidden groups.

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 03:17:46 -04:00
Fabian GhenofandClaude Opus 5.5 c54b3c4a02 Render Video: animated GIFs keep their transparency (#3061) (#3162)
Animated GIF export quantised every frame with no transparent index, so a
transparent document came out opaque black. Each frame now does what Save for
Web's GIF does: pixels under 50% opacity get a transparent index, the rest are
drawn opaque, and the palette comes from the visible pixels with one entry
kept for transparency.

The encoder also left every frame in place (disposal 1). A frame with a
transparent index is now cleared before the next one (disposal 2); otherwise
earlier frames would show through it once transparency works.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 03:12:26 -04:00
LuniiyaandBrandon Thomas e44d96e1d4 Favorite themes from the appearance button's right-click menu (#2445)
* feat(ui): favorite themes from the appearance button's context menu

Hovering a theme in Preferences > Interface shows a star; clicking it saves
the theme to interface.favoriteThemes (filled accent star once favorited).
Right-clicking the title-bar appearance button opens a menu with Appearance
Settings, then the favorite light themes and the favorite dark themes.

* Regenerate the scorecard for the favorite themes pref

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 03:09:47 -04:00
f9c5486ffe fix(shortcuts): reject malformed bindings and correctly display Plus (#3006)
* fix(shortcuts): reject malformed key bindings and format Plus

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 03:05:09 -04:00
Ahmed Hosny c25630b5fa app.save: encode on the save worker, not the UI thread (#2488) (#2517)
* app.save: encode on the save worker, not the UI thread (#2488)

The automation save ran export+write inline inside the control drain,
freezing the window and every queued control request while a large
document encoded — and overrunning the 60s reply deadline. It now uses
the same #2017 background path as File > Save when background jobs are
on: the encode and the capability-scoped write run on a worker, the
document is locked, and the control reply waits on the job (wait: false
answers {job, pending} at once). Tests and the web keep the inline path.

The save job's result now carries the path alongside the warnings, so
waiting callers get the same {path, warnings} reply both ways.

* app.save: never fire saveDocument hooks from automation saves; review fixes (#2488)

Automation saves complete in the job tick, long after run_waiting lifted
its synchronous event suppression, so the background branch fired the
user's saveDocument script bindings and Image Assets — the exact hooks
docs/control-protocol.md promises never run for automation. SaveJob now
carries an automation flag and records through saved_automation, which
skips document_saved on every path; the inline fallback records through
it too, so both modes behave the same. A regression test installs a
saveDocument binding and asserts it fires for an interactive save and
not for app.save.

The desktop's two save workers collapse into one save_through parameterized
by the write step (drift between interactive and automation saves), the
Saved status/notices are translated (Saved {name}, 16 locales), the pending
reply carries warnings like file.save's, and the success payload is built
at one site.
2026-10-11 02:54:14 -04:00
Nigel Ihza Firdausy d5bab13674 fix(transform): commit Free Transform on an outside click (#2909)
* fix(transform): accept a free transform on an outside click (#2851)

* fix(transform): accept outside clicks in the rotation zone (#2851)
2026-10-11 02:51:59 -04:00
Nigel Ihza Firdausy 03d45a80ee fix(brush): preserve pen pressure when joining Shift-click strokes (#2827) (#2890) 2026-10-11 02:46:01 -04:00
Tanish Manku c6a525cc99 Releasing a brush stroke no longer freezes: the commit takes the pixels the live stroke already drew (P32: 136 ms → 0.8 ms) (#2131)
* Releasing a brush stroke no longer freezes: the commit takes the pixels the live stroke already drew (P32: 136 ms → 0.8 ms)

Brush phase 4. On release the canvas dropped its live stroke and ran `paint.stroke` over every
point again (the whole stroke re-rendered), then re-composited the stroke's bounding box, although
the canvas already showed exactly those pixels. Long strokes froze for 100–250 ms at mouse-up
(#2068).

- `Session::offer_live_stroke` hands the finished live stroke to the next command. A
  `paint.stroke` / `paint.pencil` whose command, document revision, params, seed and points match
  it exactly takes its pixels instead of rendering (result `"fromLive": true`). Anything else
  ignores the offer and renders as before. It still runs through the normal dispatch
  (authorization, journal, one history step), and a replay renders identical pixels.
- The canvas feeds the release frame's last points to the live stroke first, then remembers the
  stroke's per-step damage for one revision (`CommittedStroke`): each canvas cache re-composites
  only the steps it hadn't shown, usually nothing, instead of the bounding box.
- P32 (brush release on a long stroke) becomes measurable: perf_scenarios times a 600-point
  200 px soft stroke on 24 MP. 136 ms → 0.83 ms on the GPU canvas, 257 ms → 0.71 ms on the CPU
  canvas (RTX 5090, release). Budget 16 ms, not enforced until a baseline run.
- Scorecard: TOOL-213-10 (⌃⌥-drag resize with readout) is done; TOOL-213-7 (live strokes for every
  brush-based retouch tool) is partial (Spot Healing, Mixer Brush, Background Eraser and Pattern
  Stamp still aren't live).

* Mask view test: a commit that takes the live stroke uploads nothing it already showed
2026-10-11 02:42:12 -04:00
ea4579ea11 fix(canvas): update Move transform-control cursors on first hover (#2887)
* fix(canvas): show Move transform control cursors before first interaction (#2871)

* Fix the Move transform-controls cursor test after merging main

ViewXform gained an aspect field on main, and the rotation-band probe sat
within the top-centre handle's grab radius; probe between handles instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 02:39:28 -04:00
1ccdac4c94 Show camera data in File Info (#2424) (#2692)
File Info only read the editable XMP description fields, so the camera
settings stored in the file's EXIF block (JPEG APP1, PSD resource 1058)
never reached the dialog or file.fileInfo.

file.fileInfo now returns a read-only "camera" object (make, model, date
taken, exposure, f-stop, ISO, focal length, 35 mm focal length, lens),
formatted for display (1/250 s, f/8, ISO 400, 33.1 mm). It reads the
existing photocraft_algo::exif parser, which gains DateTimeOriginal, and
falls back to the XMP tiff:/exif:/aux: properties when there is no EXIF
block. The dialog shows the values in a Camera Data section; labels are
translated in all 16 catalogs.

The EXIF reader now uses checked offset arithmetic and requires a tag's
whole value to lie inside the payload, so hostile counts and offsets
cannot overflow on 32-bit targets (wasm) or read past the data.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-11 02:26:29 -04:00
e59bb2909b feat(ui): allow disabling Studio canvas background dots (#2317)
* feat(prefs): persist an optional canvas dot pattern setting (#2264)

* feat(canvas): respect interface canvas dot preference (#2264)

* test(prefs): cover canvas dot toggle persistence and reset (#2264)

* Translate the Show canvas dots preference and regenerate the scorecard

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 02:15:06 -04:00
Elvis33LE 29f1ff9e90 Design: bounded GPU stack prefix reuse for property edits (#1164)
* docs: design bounded GPU stack prefix reuse

* docs: advanced blending stays on the CPU; cache admits whole grid chunks and serves partial rects
2026-10-11 02:08:08 -04:00
a8ad82dd46 GPU composite: reuse unchanged lower-stack chunks for property edits (#1169)
* perf(gpu): reuse unchanged lower-stack composite chunks

* test(gpu): verify half-float composite checkpoint reuse

* docs: record measured GPU composite reuse gains and limits

* perf(gpu): admit whole grid chunks, serve partial damage as sub-rect copies

Cache entries were keyed by the exact damage rectangle, so brush strokes
(a new partial rect every frame) filled the budget with entries that
never hit again. Entries are now whole chunk-aligned, chunk-sized grid
cells: a capture merges into the cell it overlaps at the rectangle's
offset, a read is served as a sub-rect copy of the covered part, and
coverage is tracked per cell so a resume only happens where every pixel
of the requested rectangle is cached. After a full render, any in-bounds
partial rectangle hits.

Regression test: two series of disjoint strokes inside the same chunks
leave composite_cache_bytes unchanged (no entry-per-rectangle growth),
a full refresh still finds its chunks and a top-layer edit afterwards
reuses them. The old partial-damage test now expects the covered-chunk
hit and checks outside-the-document renders admit nothing.

* docs: record the GPU reuse measurement in target-app-parity.md

The honest assessment moved from roadmap.md to target-app-parity.md on
main; keep main's roadmap and add only the dated measurement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 02:07:48 -04:00
skylar taylor-barrick 97136485f0 Merge pull request #3097 from skylartaylor/codex/ui-suite-integration-20261010
Adopt shared docking while preserving panel controls and workspaces
2026-10-10 21:40:26 -06:00
skylar taylor-barrick d0a18cfd83 UI.9: keep browser bundle under size budget on current main 2026-10-10 20:56:34 -06:00
Brandon ThomasandClaude Opus 5.5 7926161595 Release prep 0.7.0: Linux riscv64 tarball + version bump (#2965)
* Release prep 0.7.0: add Linux riscv64 tar.gz to the release; bump to 0.7.0

- release.yml: new linux-riscv64 job, ported from GridCraft: cross-compiled on ubuntu-24.04
  against ports.ubuntu.com riscv64 libs, tar.gz only, photocraft-cli --version smoke-tested
  under QEMU. The draft-release job now needs it, so SHA256SUMS.txt covers it.
- packaging/linux/package.sh: CROSS_ARCH / CROSS_TARGET / CROSS_COMPILE / EMULATOR support.
- linux_libs: search /usr/lib/riscv64-linux-gnu on riscv64 (was the x86_64 triplet).
- README and docs/releasing.md list the riscv64 tarball.
- Version 0.6.0 -> 0.7.0 (cargo xtask version set), Cargo.lock refreshed; contributors refreshed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* canvas: crisp elliptical marquee ants again in an unrotated view

#2732 (a27d7175) built the elliptical marquee's live ants in document space and snapped every
vertex to the half-pixel grid on its own. Near the edge midpoints the nearly flat arcs became
1 px stairs, whose antialiased steps are grey, so the ants no longer contrast on white or black:
drag_preview_canvas's marquee test fails on main (ubuntu and windows). In an axis-aligned view
(rotation a multiple of 90 degrees) draw the ellipse inscribed in the snapped screen box again,
as before #2732; rotated views keep the mapped ellipse.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 21:36:30 -04:00
skylar taylor-barrick 77f50330c6 UI.9: refresh shared panel integration against current main 2026-10-10 19:30:56 -06:00
953390a36e Navigator preview fills its group; no scroll fade over dock panels (#2726) (#2818)
* Let the Navigator preview fill its dock group, drop the scroll fade (#2726)

The Navigator drew a fixed 150 pt preview inside the dock's outer
ScrollArea, so a taller group left dead space below the zoom slider,
and a shorter one scrolled with egui's scroll fade painting a dark
gradient over the thumbnail. The same fade darkened the Color field
and swatches at the bottom of their groups.

The Navigator tab now lays itself out (like Layers and History): the
preview takes the group's height above the zoom controls, keeps the
document's aspect and stays centred. The dock's outer scroll areas no
longer paint the fade; their scroll bar already shows there is more.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Navigator wheel test: point below the preview, which now fills the group

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 19:32:48 -04:00
3c70d3b34f Layer > Rasterize > Layer Style bakes effects; Rasterize Layer converts vector masks (#2245) (#2669)
* Add Layer > Rasterize > Layer Style; Rasterize Layer converts vector masks (#2245)

Nothing could bake layer effects into a layer's pixels, and Rasterize >
Layer refused a raster layer that has a vector mask.

New command layer.rasterize.layerStyle (Layer > Rasterize > Layer Style,
and in the Layers context menu). It renders the layer by itself through
the compositor at 100% opacity in Normal mode, so the effects, fill
opacity and masks end up in the pixels, including those past the canvas.
The layer's own opacity, blend mode, knockout and Blend If stay layer
properties. Type, shape, fill and Smart Object content is rasterized
first, all in one history step. With a Normal layer and Normal-mode
effects the composite is unchanged at 8, 16 and 32 bit. Effects in
another mode are evaluated against the isolated layer's transparent
backdrop, because one layer of pixels cannot hold several blend modes.

Rasterize > Layer and All Layers now also turn a vector mask into a
pixel mask ("all vector data") and leave effects live, as Photoshop
does. The menu enablement follows both changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Regenerate docs/scorecard.md after rebase (#2245)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 19:20:33 -04:00
7bea7dae1c Wake the UI when the first Linux appearance read lands late (#2798) (#2941)
The appearance worker stored the first portal/gsettings answer and
signalled readiness, but only SettingChanged updates requested a
repaint. If Read replied after the 250 ms start-up wait, an idle Auto
window kept its fallback palette until some unrelated event.

Route the initial read and later signals through one publish step that
repaints the registered context whenever the value changes, and move
the thread/wait setup into start() so a test can drive it without D-Bus.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 19:19:27 -04:00
Sir Starch bfa523f916 fix(theme): subscribe before reading Linux appearance (#2833) 2026-10-10 19:15:38 -04:00
Ehsan FazliandBrandon Thomas d9ae73e95f feat(ui): live font preview on hover (#2431)
* feat(ui): preview fonts on hover

* test(ui): exercise font preview through eframe

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 19:11:27 -04:00
325c5b3194 Tools: Single Row Marquee and Single Column Marquee (#2837) (#2848)
Both tools join the Marquee flyout (no key, outside the M / Shift+M cycle,
as in Photoshop). A click selects the one-pixel row (column) under the
pointer across the whole canvas; a press-drag moves the line until the
release. The selection goes through select.rect, so Shift adds, Alt
subtracts, Shift+Alt intersects and the options-bar modes apply; Feather
applies, Anti-alias and Style/Width/Height are greyed. Selection-mode
cursor badges, the selection right-click menu and snapping cover them.
Original row/column glyphs with an ATTRIBUTION.md row; tool names in all
catalogs; README tool list and the G6 / ui-parity rows updated.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 19:10:34 -04:00
9d3ba499ad Layer > New > Background from Layer; the Background stays at the bottom (#2626) (#2663)
* Add Background from Layer and keep the Background at the bottom (#2626)

Layer > New > Background from Layer was missing, and the Background was a
locked layer that Layer > Arrange (with an explicit layer), Reverse and
dragging in the Layers panel could move, or put other layers below.

The new layer.new.backgroundFromLayer command renders the active layer as
it looks over the background colour, drops it to the bottom and locks it
as the Background, in one undo step. It is unavailable when the document
already has a Background, and for groups and adjustment layers.

Arrange refuses to move the Background and stops other layers above it;
layer.moveTo and Reverse refuse edits that would move it off the bottom.
The Layers panel shows no drop indicator for those drops.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Parity floor 629; the empty-space drop test uses a document without a Background

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 19:09:26 -04:00
dhiaaddin 1e0f8844eb Font menus: add an Arabic sample for families that cover Arabic (#2535) 2026-10-10 19:06:05 -04:00
5b778b49f2 Move tool: highlight the layer Auto-Select would pick on rollover (#2834) (#2843)
* Move tool: highlight the layer Auto-Select would pick on rollover (#2834)

With the Move tool and Auto-Select on (or ⌘ held while it is off), hovering
the canvas outlines, in the theme accent, the layer (or group, per the
Auto-Select target) that a click there would pick. Preferences › Tools ›
Show Highlight on Rollover turns it off (on by default).

The hover asks the click's own hit test (pick_cmds::auto_select_target, now
shared with layer.pickAt), so a type layer is outlined anywhere inside its
text and fully locked layers are clicked through, as on a click. The answer
is cached per document revision and pointer pixel. Nothing is drawn while a
button is down, a drag or transform runs, or the selected pixels would move.

Part of #214 (scorecard TOOL-214-4, now partial).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Move hover: follow main's moves_selected_pixels_with rename

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 19:04:19 -04:00
Sir Starch 67e34a1d4c Themes: add Breeze Light and Breeze Dark (#2276) (#2335)
Two Studio-layout themes for KDE Plasma desktops: original colour values
chosen to sit close to Breeze's cool blue-grey surfaces and blue accent
(and its 5 px radius) so the app blends into a Plasma desktop, without
copying Breeze's colour schemes. Text readability comes first.

- theme.rs: ThemeKind::BreezeLight / BreezeDark. Every text colour (text,
  secondary, faint, accent, danger, warning) holds 4.5:1 on every surface
  and on hovered, pressed and selected states; the primary button is a
  deeper blue that takes white text and stays above 4.5:1 while it
  darkens on hover and press. Breeze's own inactive text and link blue
  are only about 2.8:1 on its light surfaces, so ours are darker. The
  close button goes red on hover.
- prefs: Theme/LightTheme::BreezeLight ("breezeLight") and
  Theme/DarkTheme::BreezeDark ("breezeDark"): Preferences > Interface,
  `prefs.set`.
- Window > Theme > Breeze Light/Dark Theme (`window.theme.breezeLight`,
  `window.theme.breezeDark`) and `ui.set {"theme": ...}` (aliases:
  breeze, kde, plasma for the light one; ...dark for the dark one).
- i18n: the four new labels in all 16 catalogs.
- docs/ui-design.md and ATTRIBUTION.md (original work, credits Breeze as
  the inspiration; Breeze's schemes are LGPL-2.0-or-later and none of
  their values, files or code are copied).
- Tests: names/aliases, surface order and blue-grey character, the
  contrast matrix for both themes, and the preference/mode selection.
2026-10-10 19:01:53 -04:00
FinnNkandClaude Opus 5.5 0c4016a4db feat(ui): hold Alt+Space to zoom out, as in Photoshop (#2877)
* feat(ui): Alt turns a held temporary Zoom In into Zoom Out

Alt reverses the Zoom tool's direction, but a held Zoom In (Cmd+Space)
ignored it: with Zoom Out unbound or rebound, Cmd+Alt+Space zoomed in.
held_tool now reports Zoom Out whenever Zoom In is the held binding and
Alt is down, unless Alt is part of the Zoom In key itself (a rebound
Alt+Z still zooms in). The default keys don't change here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(ui): hold Alt+Space to zoom out, as in Photoshop

Photoshop zooms out with Alt+Space (Option+Space on the Mac), usually
pressed as Space first, then Alt, then click. PhotoCraft's Zoom Out
(hold) default was Cmd+Alt+Space only, so Space then Alt still panned.

Zoom Out (hold) now defaults to Alt+Space. Holding Cmd+Alt+Space
matches both Cmd+Space and Alt+Space equally; the previous commit's
Alt rule resolves that to Zoom Out, so it keeps zooming out. Saved
overrides are kept. Holding Space first also avoids the Mac's Spotlight
shortcut and the Alt+Space window menu on many Linux desktops.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(contributors): credit FinnNk by GitHub profile name

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:56:04 -04:00
6911075037 Edit: Copy/Paste with no selection keeps type, shape and group layers (#2670) (#2686)
* Smart Objects: Copy/Paste with no selection keeps the smart object (#2428)

Photoshop's layer-based copy (CC 2018 on) copies the active layer whole
when there is no selection. Edit > Copy always lifted the layer's pixels,
so Paste made a raster layer from a smart object. Copy now also keeps the
smart object layer on the clipboard (with its pixels for Paste Into,
masks, channels and other apps). Paste recreates it with contents of its
own, converted to the destination's colour and depth and placed as the
pixels would be. With a selection, Copy still takes pixels.

The colour/depth/contents-id handling of layer.copyToDocument moves into
shared helpers (adapt_copies, translate_copies) used by both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Edit: Copy/Paste with no selection keeps type, shape and group layers (#2670)

Photoshop's layer-based copy, verified in Photoshop: with no pixel
selection, Copy takes a type layer, a shape layer or a group (its whole
subtree) whole, and Paste / Paste in Place recreate it instead of a
pixel layer. #2428 did this for smart objects; this extends the same
path. Pixel layers, several selected layers and any copy with a
selection still take pixels.

A group has no pixels of its own, so Copy (now enabled for a group with
no selection) puts its composite on the clipboard for Paste Into, masks
and other apps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 18:50:04 -04:00
37cb99eb1f Let dock tabs be dragged to reorder within their group (#2272) (#2774)
Dock tabs only sensed clicks, so a drag on a tab fell through to the
strip behind it and moved the whole group; there was no per-group tab
order to change.

DockLayout gains tabOrder (tab names per group, like hidden_tabs, so the
Pro/Studio Color/Swatches swap is safe). It is read leniently: unknown
groups, names and wrong types fall back to the default order instead of
dropping the saved layout. It is drawn through visible_tabs, while
dockTabs and the panel bodies keep using the original indices.

Tabs on the dock strips now sense drags: dragging one along its strip
shows an insertion line and drops it there, a plain click still selects,
and a tab dragged off the strip moves the group as the strip does.
Lock Workspace stops both. The order is part of ui.set {dock}, the
remembered panelLayout and saved workspaces.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:47:36 -04:00
Brandon ThomasandClaude Opus 5.5 9c90365c45 ui-egui tests: restore the joined helper (fixes ui-egui test build after #2924 and #2497 both removed one) (#2947)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:46:16 -04:00
Valentin KleinandClaude Opus 5.5 4916a0f088 Pencil: 1 px lines step pixel by pixel, no doubled corners (#2139) (#2806)
Small aliased tips (dabs at most a pixel apart) now walk each segment
pixel by pixel on the line between the pixels holding its ends, one dab
per pixel along the major axis at the pixel's dab centre. Distance
spacing put two dabs in a row wherever the line crossed a pixel corner,
which left L-shaped doubled pixels at every step of a Pencil line.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:45:57 -04:00
93599a1837 Smart Objects: Copy/Paste with no selection keeps the smart object (#2428) (#2653)
Photoshop's layer-based copy (CC 2018 on) copies the active layer whole
when there is no selection. Edit > Copy always lifted the layer's pixels,
so Paste made a raster layer from a smart object. Copy now also keeps the
smart object layer on the clipboard (with its pixels for Paste Into,
masks, channels and other apps). Paste recreates it with contents of its
own, converted to the destination's colour and depth and placed as the
pixels would be. With a selection, Copy still takes pixels.

The colour/depth/contents-id handling of layer.copyToDocument moves into
shared helpers (adapt_copies, translate_copies) used by both.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 18:43:46 -04:00
87f74cc8d2 Type: tabs advance to Photoshop's default tab stops (#1881) (#2733)
#1942 stopped tabs from shaping as .notdef by laying them out as a
space, so a tab was only one space wide. Layout now widens each tab to
the next default stop (every 36 pt, from the anchor of point text or the
left edge of the box). Paragraph text breaks lines with the real tab
widths: it starts from a safe upper bound (space + one interval) and
re-breaks until the widths agree, so expanded tabs never overflow the
box and lines don't wrap early. The text keeps its \t, so PSD round
trips are unchanged. Tab in the Type tool now types a tab.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:38:53 -04:00
xsvmandBrandon Thomas 13e478cc6e Filter Gallery: an unknown option is a bad-params error (#2548 follow-up) (#2599)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 18:37:25 -04:00
Brandon ThomasandClaude Opus 5.5 e1a13013b6 ui-egui tests: drop the shadowing joined closure (fixes clippy dead-code on main) (#2924)
#2782 and #2853 both fixed the save-dialog test's path expectations; together they left a
top-level joined() helper shadowed by an identical local closure, so clippy -D warnings fails
with "function joined is never used". The test now uses the documented helper.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:34:51 -04:00
7687380604 feat(prefs): add search across preference sections and settings (#2679)
* feat(prefs): search visible settings across sections (#2593)

Filter the Preferences sidebar by section and editable field labels,
switch to the first match, and show matching settings in the editor.
Keep the draft intact while searching and hide Reset Section during filtering.

* Preferences search: translate the field hint and empty state; rustfmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Merge fixups: pass the new search argument in a main test; search test uses a visible Type setting

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:32:04 -04:00
7c9e7e5ae3 Keep the type style when a data set replaces text (#2742) (#2785)
Applying a textReplacement value cleared the layer's character and
paragraph runs, so the text re-flowed from the summary fields (family,
size, colour) and lost weight, italic, tracking, underline, caps and the
rest of the run style. The new text now takes the first character's style
and the first paragraph's settings, as in Photoshop. The value is kept
verbatim, as before.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:31:50 -04:00
308c3369c0 Control: timeout errors name the likely causes (#2489) (#2497)
* Control: timeout text derives from the reply deadline (#2489 review)

The server deadline and both timeout replies now share one constant:
REPLY_DEADLINE drives the serve thread's clock and the text is built from
it, so the message can never claim a number the server no longer uses.

* Tests: drop the duplicate joined() helper left by #2782 and #2853 both landing

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:27:03 -04:00
07e7a73636 Show non-square pixels on the canvas (#2594) (#2718)
View > Pixel Aspect Ratio and its Correction toggle only stored a value:
the canvas transform (ViewXform) had no notion of pixel aspect, so the
image was always drawn with square pixels.

ViewXform now carries the displayed pixel aspect ratio and stretches
document x by it before rotation and flip. Drawing, pointer-to-document
mapping, pan and zoom-about deltas, rulers, grid, Fit/Fill on Screen,
scrollbars, the Navigator's view box and paste-in-place visibility all
go through it. Correction is on by default, as in Photoshop. A corrected
view draws through the CPU canvas path, like a flipped one, since the
GPU shader assumes square pixels. The document's pixels are unchanged.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 18:25:24 -04:00
46af2e6e30 Workspaces: preserve the embedding host menu and rail flags (#2620)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:22:30 -04:00
skylar taylor-barrick 254450f38e UI.8: pin final shared dock action labels 2026-10-10 16:20:57 -06:00
Arthur Wagner 2194c7c58f Status bar: show document dimensions in the ruler unit (#2618) 2026-10-10 18:18:19 -04:00
Valentin KleinandClaude Opus 5.5 faf2639fb8 Web: File › Open opens every selected file (#2802) (#2807)
The web file dialog called rfd's pick_file() and ignored the request's
`multiple` flag, and FileDialogAnswer could only carry one file's
contents. Pick several files when File › Open asks for them, answer
with the new ContentsMany variant, and open each as its own document,
reporting a failed file without stopping the rest (as the desktop's
multi-path open does).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:15:47 -04:00
Gustavo Ziger 1a59f6f6a3 Fix brush picker closing immediately on trackpad taps (#2772)
Ignore outside-click dismissal during the opening frame.
Add regression coverage for repeated opening after outside clicks.
2026-10-10 18:10:12 -04:00
Valentin KleinandClaude Opus 5.5 f9f65447f8 Layers: Layer via Copy duplicates every selected layer (#2777) (#2796)
With several layers selected and no pixel selection, Cmd+J now copies every
selected layer in one undo step (each copy above its original, the copies
selected), reusing Duplicate Layer's multi-layer path. With a pixel
selection it still copies the active layer's selected pixels.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:09:03 -04:00
Valentin KleinandClaude Opus 5.5 444323ee74 Warp Text: the dialog lists Style, orientation, then Bend and distortions (#2689) (#2819)
The schema dialog draws its fields in the order of the command's params
doc, which put Orientation last, below the three sliders. Photoshop's
Warp Text dialog has Style, then Horizontal/Vertical, then Bend,
Horizontal Distortion and Vertical Distortion. Reorder the params doc.

Live preview and opening with the layer's current warp already landed
in #2539 (after v0.6.0).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 18:06:09 -04:00
27e25c2cb4 Crop/marquee readout and Properties W/H/X/Y in the ruler unit (cm, mm, in…) (#2334)
* Crop / marquee size readout in the Units & Rulers unit (cm, mm, in…) as Photoshop shows it

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Properties: Transform W/H/X/Y and Canvas W/H in the Units & Rulers unit (cm, mm, in…), typed values converted back to px

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Merge origin/main: size readout test follows the trimmed unit format

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 18:03:32 -04:00
Elvis33LE 03f4cc0de1 Correct Photomerge roadmap status (#2831) 2026-10-10 17:57:51 -04:00
mroxsoandhighperfocused d9e6cee908 Tests: build save-dialog expectations with Path::join so they pass on Windows (#2745) (#2853)
Co-authored-by: highperfocused <[email protected]>
2026-10-10 17:57:41 -04:00
46d170b19b Free Transform frames the whole type layer; Distort/Perspective greyed for type (#2630) (#2701)
* Free Transform on type: whole-layer frame, grey Distort/Perspective (#2630)

With a selection active, Free Transform on a type layer framed only the
selected part of the text and the preview lifted half of the rendered
glyphs, but the engine then transformed the whole type layer, so the box
and the result disagreed. Type, shapes and smart objects always move
whole, so transform_bounds no longer intersects their frame with the
selection and the preview no longer lifts pixels out of them.

Distort and Perspective stayed enabled for editable type and then failed
on commit. They are now greyed for type layers (menu bar, marquee and
transform-box context menus), as in Photoshop, unless an unlinked mask or
channel is targeted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* transform_type_tests: set CanvasToolMenu::pasteboard (#2630)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:57:26 -04:00
a3d2a6d486 Place: wire Resize Image During Place into the implicit fit (#204) (#2538)
* feat(engine): Resize Image During Place drives the implicit Place fit (#204)

* Merge origin/main; regenerate docs/scorecard.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:53:25 -04:00
Gert Pellin - GPEandswitch87 a27d717597 canvas: the marquee hinting follows a rotated view like the release does (#2732)
The live ants for the Rectangular/Elliptical Marquee (and Object Selection)
were an axis-aligned screen box built from the two projected corners of the
drag. A rotated view projects the drag's document rectangle onto a rotated
one, and the box through two of its corners is a different shape in a
different place: on a 30 degree view a corner landed 21 x 50 px away from
where the selection it previews was committed. The release was always right,
only the hinting was drawn elsewhere (#2512).

marquee_drag_ants builds the outline in document space and maps every point
through the view instead: four corners for the rectangle, the ellipse
inscribed in it for the elliptical marquee, with as many vertices as its size
on screen asks for. Every point is snapped to the half-pixel grid like every
other ants outline (marching_ants_segments), so the lines stay crisp at any
zoom. Unrotated the mapping is only a scale, and the corners come out where
they always did.

Tests drag a marquee in a 30 degree view for both tools and check the drawn
outline against the selection the release commits: each corner is the mapped
corner of the dragged rectangle, and each point of the ellipse maps back onto
it.

Co-authored-by: switch87 <[email protected]>
2026-10-10 17:51:20 -04:00
Valentin KleinandClaude Opus 5.5 63fee8c07c wasm: gate native-only constants so wasm32 builds without dead-code warnings (#2808) (#2813)
PAR_MIN_PIXELS / PAR_CHUNK_PIXELS (photocraft-cms) and OPENABLE
(photocraft-engine) are only used by native-only code (the rayon paths
and list_images). Give them the same cfg so wasm32 check and clippy
-D warnings are clean. No behaviour change.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:48:19 -04:00
Valentin KleinandClaude Opus 5.5 1320dac5bf Spot Healing: Create Texture keeps the grain, joining blocks along min-error cuts (#2104) (#2762)
Create Texture (inpaint::synthesize) averaged each block 50/50 into the
already-synthesised overlap. Averaging two unrelated grain patterns cuts
their standard deviation by about 1/sqrt(2), so the fill came out smoother
than its surroundings (75 % of the grain for one 30 px dab), and every
overlapping stroke, which samples the previous ones, lost more (57 % after
eight). Blocks are now joined along Efros & Freeman's minimum-error
boundary cut (Image Quilting, SIGGRAPH 2001): each pixel is copied from
one block or the other, never averaged.

Content-Aware and Proximity Match already keep the grain on main since
#2202 (patch copies instead of voting blur); the new test guards all three.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:46:41 -04:00
Valentin KleinandClaude Opus 5.5 ab3e6ebe81 Brush: Wet Edges acts on the whole stroke, not each dab (#2088) (#2721)
Wet Edges multiplied every dab by its own rim profile and max-accumulated the
dabs, so the rims of neighbouring dabs showed through the stroke as a chain of
rings. Dabs now accumulate normally and record how deep they reach each pixel
(1 - rn); the stroke keeps the deepest value per pixel and applies the
wet-edge transfer to its accumulated coverage when composited (live preview,
tail preview, commit and retouch coverage alike). The interior of the stroke is
evenly light and only the stroke's own rim is darker.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:41:14 -04:00
twentymls d3ae5aad0f Smart filter edits: re-render from cached stages, in a background job (#2739)
Showing, hiding or editing a smart filter re-rendered the whole stack from the
placed source on the UI thread: on a 3000x4498 layer with five filters every
click on a filter's eye froze the window for about 1.5 s with no feedback.

- Each render keeps the placed source and the result after every visible filter
  (blake3 of the source contents, the placement and the filters so far), so an
  edit reruns only the filters from the edited one up. Edit > Purge > All drops
  them.
- Smart filter edits apply the edit at once (so bad params still fail
  immediately) and re-render as a background job when started with
  Session::start: the window keeps drawing, with progress and Esc to cancel
  between filters. Session::execute is unchanged.
2026-10-10 17:38:59 -04:00
d0127f9294 Eraser: Block mode (#2770) (#2778)
* Pencil/Eraser: round Pencil cursor and Eraser Pencil mode (#2662)

The Pencil cursor always outlined the square grid_square footprint, but the
aliased dab is a disc from 4 px on. It now draws a circle on the same
pixel-grid square when the tip is round, and the square for 1-3 px tips
whose dab really fills it.

The Eraser options bar gains Photoshop's Mode: Brush / Pencil (replacing
the blend-mode dropdown the Eraser never used). Pencil mode commits
paint.pencil with erase: true (hard, aliased, full flow), live and on
release, and shows the Pencil's cursor. Block mode is left for later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Eraser: translate the Pencil mode label in every catalog

The Eraser's Mode dropdown added tl!("Pencil"), which had no entry in the
cs, el, ko, zh-hans and zh-hant catalogs, so every_tl_literal_is_translated
failed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Eraser: Block mode (#2770)

Photoshop's Eraser Mode is Brush / Pencil / Block; #2694 added Pencil.
Block erases a hard, aliased square of 16 screen pixels, so 16 / zoom
document pixels, whatever the brush's size, hardness, opacity or flow.

- paint: BrushSettings.square (with aliased) rasterises the dab's whole
  pixel-grid square (serde: omitted when false, so saved brushes are
  unchanged).
- engine: paint.pencil "block": true builds that brush from the stroke's
  "zoom" (brush_cmds::block_size: round(16 / zoom), 1..5000 px); a zoom
  that is not a positive number is an Err. Params doc updated.
- ui: Mode dropdown gains Block; the Block-mode Eraser commits
  paint.pencil with "block": true, shows the block's square cursor and
  greys out Size/preset, Hardness, Opacity and Flow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Eraser: translate the Block mode label

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 17:35:55 -04:00
6bbfa77230 Interface: wire Dynamic Color Sliders for the colour tracks (#204) (#2531)
* feat(ui): the Dynamic Color Sliders preference controls the colour slider tracks (#204)

* Regenerate docs/scorecard.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:31:24 -04:00
5e0e9c595b Speed up large group merges (#1561) (#2664)
* Speed up large layer group merges

* Merges: bound by composite_bounds so layer effects outside the pixels are kept

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:28:53 -04:00
MarekSpodBiedry d29d81d5c0 Linux: no false missing-library warning when the linker cache can't be read (#1144) (#2503) 2026-10-10 17:19:47 -04:00
Valentin KleinandClaude Opus 5.5 5a1f6eef2e Pencil/Eraser: round Pencil cursor and Eraser Pencil mode (#2662) (#2694)
* Pencil/Eraser: round Pencil cursor and Eraser Pencil mode (#2662)

The Pencil cursor always outlined the square grid_square footprint, but the
aliased dab is a disc from 4 px on. It now draws a circle on the same
pixel-grid square when the tip is round, and the square for 1-3 px tips
whose dab really fills it.

The Eraser options bar gains Photoshop's Mode: Brush / Pencil (replacing
the blend-mode dropdown the Eraser never used). Pencil mode commits
paint.pencil with erase: true (hard, aliased, full flow), live and on
release, and shows the Pencil's cursor. Block mode is left for later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Eraser: translate the Pencil mode label in every catalog

The Eraser's Mode dropdown added tl!("Pencil"), which had no entry in the
cs, el, ko, zh-hans and zh-hant catalogs, so every_tl_literal_is_translated
failed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:14:17 -04:00
96ec16ed7d fix(compose, gpu): round dithered gradient fills to the document depth (#2755) (#2781)
A live gradient's dither adds a fraction of a level of noise, but gradient
fill layers kept it in float. Color Dodge divides by 1 - cs, so under a
bright dodge layer that sub-level noise came out as speckle several levels
high, and channels at 0 were lifted off black (coloured fringes).

Dithered gradient pixels are now rounded to the document depth's levels
(8/16-bit; float documents unchanged), as a painted gradient stores them.
Same rounding in the GPU shader. Regression tests in compose and a GPU
parity case for stacked dithered gradients under Color Dodge.


Claude-Session: https://claude.ai/code/session_01Qpa5z8GksXAFiDavFkmh4R

Co-authored-by: Leel Wasanatha <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:11:46 -04:00
ede3da019d i18n: wrap remaining hardcoded UI strings for translation (#2467)
- Wrap "PhotoCraft — Screen Color Picker" viewport title with tl!()
- Wrap "OK" button in widgets.rs with tl!()
- Add "PhotoCraft — Screen Color Picker" entry to all 14 language catalogs

Co-authored-by: seldoms <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:10:36 -04:00
994a042123 Paint a pen tap at its own pressure, not full or zero (#1798) (#2757)
A tap shorter than a UI frame left the stylus with no current sample by the
time the canvas ran: the platform had already cleared it (macOS proximity
out, a non-tablet button-up, the web's pointerleave) or set it back to
pressure 0 (X11 and macOS hover). The press then read as a mouse and painted
a full-size dab, or read the lift's 0. The same happened to the last moves of
a stroke that lifted in the frame they arrived in, which painted at full
pressure.

Stylus now drops zero-pressure samples from a frame that also had contact and
falls back to the frame's last contact sample when the feed was cleared or
reports 0. A tap (a drag still at its press point on release) paints at the
highest pressure seen since the press, so a tap spanning two frames is not
stuck at its first light sample. A mouse still paints at full pressure.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:06:44 -04:00
6cac936112 Image Size: Resample off keeps the pixel readouts honest (#2393) (#2533)
With Resample off, image.imageSize keeps the pixel dimensions and only
changes the resolution, but the dialog still accepted pixel Width/Height
edits and showed them in the Dimensions line and size estimate.

Now, as in Photoshop, with Resample off:
- width and height stay at the document's pixels (readouts included);
- in Pixels or Percent the Width/Height fields are disabled;
- in a physical unit (in, cm, mm, pt, pica) editing Width or Height
  changes the resolution to fit that size, keeping the pixels;
- the constrain chain stays linked.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 17:05:37 -04:00
817678d6a0 fix(ui): prevent Layers opacity controls from overflowing narrow docks (#2325)
* fix(ui): fit Layers opacity controls within narrow docks (#2309)

* Layers Opacity row: keep the label at the default dock width

Show the label while the blend dropdown keeps 80 px, so the default
Layers dock looks as before and only long translated labels on narrow
docks give way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 17:03:45 -04:00
Valentin KleinandClaude Opus 5.5 737d1ca753 Brush cursor: Normal Brush Tip ring on the real 50% contour (#2744) (#2747)
Since #2167 the soft tip falls off as (1 - t^2)^4, whose 50% point is at
t = sqrt(1 - 0.5^(1/4)) ~ 0.399, but the Normal Brush Tip cursor still used
the old smoothstep midpoint r * (0.5 + 0.5 * hardness). Soft brushes got a
ring up to 25% too large (size 21, hardness 0: 5.25 px instead of 4.19 px).

photocraft_paint::half_coverage_radius inverts tip_falloff, and the cursor
uses it, so the two can't drift apart again.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:58:06 -04:00
Valentin KleinandClaude Opus 5.5 14dfa38581 Actions: double-click an action name to rename it (#2032) (#2769)
Photoshop renames an action in place when its name is double-clicked in the
Actions panel. PhotoCraft had no way to rename an action at all, so every
action kept its "Action N" default name.

- New engine command `actions.rename {"action": name|index, "name": str}`.
  Empty, whitespace-only and duplicate names are rejected (the old name
  stays). Nested `actions.play` steps that call the action by name, and
  its function-key binding, follow the rename. Refused during playback.
- Actions panel: double-clicking the name opens an in-place field with the
  name selected; Enter, Tab or clicking elsewhere commits through the
  command, Esc cancels. Double-clicking elsewhere on the row still plays.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:54:36 -04:00
5963e5b7f0 Move tool: ⌘-drag with a painting tool floats the selected pixels from the control channel too (#2768) (#2776)
* Move tool: ⌘-drag temporary Move gets the drag box and snapping (#2681)

snap_ui::begin chose the snap gesture from app.ui.tool, the selected tool,
not the tool the press acts as. A ⌘-drag with a painting tool (temporary
Move) or with a selection tool outside the selection (moves the layer)
got no moving box and no smart-guide/guide/grid snapping.

The ⌘ resolution in canvas::tool_event moves into canvas::event_tool,
which begin now uses together with canvas::command_moves_layer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Move tool: ⌘-drag with a painting tool floats the selected pixels from the control channel too (#2768)

`move_ui::moves_selected_pixels` asked `app.active_tool()`, which only sees the
held-key override the canvas sets while ⌘ is down. Control-channel, MCP and test
input send ⌘ on the event, so `tool_event` resolved the Move tool but the
selected-pixel checks still saw the Brush and moved the whole layer. The press
now asks with the event's tool (`canvas::event_tool`): the floating-piece drop,
Auto-Select pick, float, lock check and snap box.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 16:50:50 -04:00
F4LCON b773a39efa Home screen: remove individual Recent entries (#2731)
Fixes #2691. The hovered row of the Home screen's Recent list shows a ×
that takes the file off the list without opening it, and right-click
offers Remove from Recent and Clear Recent Files. The change is stored in
the preferences, so it survives a restart, and the file comes back when it
is opened again. `file.removeRecent {"path"}` does the same for agents.
Rows carry their file name as their accessible label.
2026-10-10 16:49:34 -04:00
a28d786638 fix(navigator): zoom the document with the mouse wheel over the preview (#2724)
* fix(navigator): zoom with wheel over the preview (#2716)

* rustfmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:43:57 -04:00
cfe031f2a6 Batch: skip recorded view steps in batch and droplets (#2752) (#2761)
* Actions: record File › Save and Save As steps and replay them (#2032)

Save and Save As run in the desktop shell (dialogs, TIFF prompt, background
save job), outside Session::execute, so they never reached the journal that
action recording copies from. The shell now journals `file.save` {} for a save
in place and `file.saveAs` {path, tiffLayers?} once a Save As has its path
(after the dialog or the TIFF Options answer). The engine treats both as
replayable shell steps; shell playback writes them synchronously without a
dialog. Batch and droplets drop recorded saves, since their destination folder
overrides them (Photoshop's "Override Action 'Save As' Commands").

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Batch: skip recorded view steps in batch and droplets (#2752)

Actions recorded in the desktop app can hold the shell's view steps
(view.zoomIn, view.fitOnScreen, ...). Batch and Create Droplet checked
every step against the engine registry and rejected the whole action
with "unknown command". They now skip view steps, which don't change
the output, alongside the recorded saves #2746 already skips.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 16:43:36 -04:00
Valentin KleinandClaude Opus 5.5 6ff2a03f33 Actions: record File › Save and Save As steps and replay them (#2032) (#2746)
Save and Save As run in the desktop shell (dialogs, TIFF prompt, background
save job), outside Session::execute, so they never reached the journal that
action recording copies from. The shell now journals `file.save` {} for a save
in place and `file.saveAs` {path, tiffLayers?} once a Save As has its path
(after the dialog or the TIFF Options answer). The engine treats both as
replayable shell steps; shell playback writes them synchronously without a
dialog. Batch and droplets drop recorded saves, since their destination folder
overrides them (Photoshop's "Override Action 'Save As' Commands").

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:38:37 -04:00
4db47f2bcc Esc deselects when no active operation needs cancelling (#2765)
* Esc deselects when no active operation needs cancelling (#2674)

* Esc: keep the selection while a canvas drag is in progress

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: highperfocused <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:36:44 -04:00
719465dc5b Lasso: ⌘-drag outside the selection moves the layer (#2725) (#2737)
* Guides: ⌘-drag over a guide moves it with the selection tools too (#2690)

⌘ is the Move tool with any tool, and the Move tool drags a guide under the
pointer before anything else. Painting tools already got this through the
held-⌘ Move override, but the marquees, lassos and Magic Wand keep their own
tool under ⌘ (`command_moves_layer`), so a ⌘-drag over a guide moved the layer
(or drew a lasso outline) and left the guide in place.

`canvas::command_guide_at` takes the guide on a ⌘ press with a selection tool
(same hit test as the Move tool: hidden or locked guides are not hit), the
guide drag snaps like the Move tool's (never onto guides, so not back onto
itself), the Lasso hands the drag's events to the canvas, and the cursor over
a guide is the guide's double arrow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Lasso: ⌘-drag outside the selection moves the layer (#2725)

`lasso_ui::pointer` took a ⌘ press outside the selection before
`canvas::tool_event` reached `command_moves_layer`, so it drew an outline;
`canvas_input` did not forward the drag's moves and release either. The
Lasso now hands such a press to the canvas (the temporary Move tool) and
feeds it the rest of the drag, also when a locked layer refuses the move.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 16:34:43 -04:00
cf54d5e8a3 Keep the blend-mode preview between list rows (#2553) (#2612)
The Layers panel blend-mode list previews the hovered mode, but egui's
item spacing leaves a gap between rows that hovers no row, so moving the
pointer down the list flashed the layer's current mode back at every gap.

While the pointer is over the open list and between rows, report the
nearest row as hovered, so the preview moves straight from one mode to
the next.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:33:04 -04:00
Valentin KleinandClaude Opus 5.5 9f82e6522f Guides: ⌘-drag over a guide moves it with the selection tools too (#2690) (#2699)
⌘ is the Move tool with any tool, and the Move tool drags a guide under the
pointer before anything else. Painting tools already got this through the
held-⌘ Move override, but the marquees, lassos and Magic Wand keep their own
tool under ⌘ (`command_moves_layer`), so a ⌘-drag over a guide moved the layer
(or drew a lasso outline) and left the guide in place.

`canvas::command_guide_at` takes the guide on a ⌘ press with a selection tool
(same hit test as the Move tool: hidden or locked guides are not hit), the
guide drag snaps like the Move tool's (never onto guides, so not back onto
itself), the Lasso hands the drag's events to the canvas, and the cursor over
a guide is the guide's double arrow.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:28:48 -04:00
4908fde283 fix(ui): make painting symmetry available across all themes (#2704)
* fix(ui): expose painting symmetry for all themes (#2659)

Render the existing symmetry control for Brush, Pencil and Eraser
independent of palette. Add a per-theme, per-tool UI visibility test.

* rustfmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:26:54 -04:00
Valentin KleinandClaude Opus 5.5 2fac209d56 Batch: a failed step inside a called action fails the file and the script (#2779) (#2783)
Scripts (File › Scripts › Browse, Script Events) ignored the `failed` entry that
`actions.play` returns when a step inside the called action fails, so they reported
ok and kept going. Batch and droplets ran each file in a scratch session without
the actions list, so any nested action call failed with "no action named". The
scratch session now gets the caller's actions and playback stack (an action that
batches itself is caught as recursive), and both runners check nested_failure.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:25:22 -04:00
5c039af581 Selection: moving a selection outline snaps its bounds, not the pointer (#2736) (#2740)
Dragging inside a selection with a marquee or lasso (or ⌘-dragging its
pixels as a floating piece) now starts a SelectionMove snap gesture over
the selection's bounds, like the Move tool's box, instead of snapping the
pointer as a marquee corner (marquees) or not snapping at all (lasso).
The selection's own edges are left out of the targets.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 16:19:02 -04:00
Valentin KleinandClaude Opus 5.5 dfa4a2e51e Smart Objects: stacked layers sit at the contents top level (#2657) (#2676)
* Smart Objects: converting several layers keeps them at the contents top level (#2648)

Convert to Smart Object with several selected layers wrapped them in a
temporary group before embedding, so Edit Contents showed one group named
after the top layer. Photoshop puts the selected layers at the top level of
the embedded document. The embedding now goes through layers_to_smart, which
takes the layers directly; a pass-through root composites the same, so the
smart object looks unchanged. A single selected group still converts as is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Smart Objects: stacked layers sit at the contents top level (#2657)

Load Files into Stack with Create Smart Object, and Statistics with
alignment, put the loaded layers in a temporary group before embedding,
so the smart object's contents held one group named after the first file.
Photoshop puts one layer per file at the top level of the contents. Both
call sites now pass the layers to layers_to_smart. The wrapper was an
opaque Normal group of opaque Normal layers, so the composite is the same.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:17:49 -04:00
5d9e812efc feat(prefs): add intermediate UI scale options from 80% to 95% (#2678)
* feat(prefs): add 80–95% UI scale presets (#2492)

Offer finer five-percent steps between 75% and 100% for small screens.
Exercise the new values through the live preference and egui scaling test.

* Label the 80-95% UI scale choices as percentages

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Translate the 80-95% UI scale labels in every catalog

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:16:47 -04:00
Valentin KleinandClaude Opus 5.5 9bd6b8111e Smart Objects: converting several layers keeps them at the contents top level (#2648) (#2651)
Convert to Smart Object with several selected layers wrapped them in a
temporary group before embedding, so Edit Contents showed one group named
after the top layer. Photoshop puts the selected layers at the top level of
the embedded document. The embedding now goes through layers_to_smart, which
takes the layers directly; a pass-through root composites the same, so the
smart object looks unchanged. A single selected group still converts as is.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:10:36 -04:00
dfd63b0945 Move tool: ⌘-drag temporary Move gets the drag box and snapping (#2681) (#2684)
snap_ui::begin chose the snap gesture from app.ui.tool, the selected tool,
not the tool the press acts as. A ⌘-drag with a painting tool (temporary
Move) or with a selection tool outside the selection (moves the layer)
got no moving box and no smart-guide/guide/grid snapping.

The ⌘ resolution in canvas::tool_event moves into canvas::event_tool,
which begin now uses together with canvas::command_moves_layer.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 16:10:12 -04:00
7dc8bbd84a Channels: Cut with one channel targeted clears only that channel (#2698) (#2712)
* Copy and paste a single channel from the Channels panel (#2307)

With a colour channel (Red, Green, Blue, ...) targeted, Copy copied the whole
layer and Paste made a new layer, so a channel could not be copied into
another one. Now, as in Photoshop:

- Copy with a colour or alpha channel targeted copies that channel's values
  as a grayscale clip, inside the selection or across the whole canvas. With
  an alpha channel targeted, Copy needs no pixel layer.
- Paste, Paste in Place and Paste Into with a colour channel targeted write
  the clip's luminosity into that channel of the active layer, in one undo
  step. The other channels and the layer's transparency are left alone, and
  a pixel lock refuses the paste.

The logic lives in a new channel_clip module; Copy, Paste and Paste Into only
call it. Cut keeps its old behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Channels: Cut with one channel targeted clears only that channel (#2698)

With a single colour channel (e.g. Red) targeted in the Channels panel,
Edit > Cut copied and cleared every channel of the layer: `edit.cut` is not
one of the channel-routed commands, so it always ran the whole-layer path.

Now, as in Photoshop, Cut with a colour channel targeted copies that channel
as a grayscale clip (the channel Copy from #2307) and fills the cut area of
that channel only with the background colour's value for it, weighted by
selection coverage. The other channels and the layer's transparency are left
alone, and the whole cut is one undo step. With the composite targeted, Cut
is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Cut on a colour channel: reuse clear_color_channel from #2730

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Fabian Ghenof <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 16:05:08 -04:00
Valentin KleinandClaude Opus 5.5 f158cd45aa Move tool: the drag's box and snapping follow the Auto-Selected layer (#2666) (#2675)
snap_ui::begin ran on the press before the Move tool's Auto-Select
layer.pickAt, so the drag box, the snapped rect and the excluded targets
were the previously selected layers'. Another layer's box moved instead,
and with an empty layer or a group selected there was no box and no
snapping. Re-run it when the pick changed the selection.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 16:03:25 -04:00
Fabian GhenofandClaude Opus 5.5 96198fe49d Copy and paste a single channel from the Channels panel (#2307) (#2695)
With a colour channel (Red, Green, Blue, ...) targeted, Copy copied the whole
layer and Paste made a new layer, so a channel could not be copied into
another one. Now, as in Photoshop:

- Copy with a colour or alpha channel targeted copies that channel's values
  as a grayscale clip, inside the selection or across the whole canvas. With
  an alpha channel targeted, Copy needs no pixel layer.
- Paste, Paste in Place and Paste Into with a colour channel targeted write
  the clip's luminosity into that channel of the active layer, in one undo
  step. The other channels and the layer's transparency are left alone, and
  a pixel lock refuses the paste.

The logic lives in a new channel_clip module; Copy, Paste and Paste Into only
call it. Cut keeps its old behaviour.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 15:59:34 -04:00
Valentin KleinandClaude Opus 5.5 f9700ea95e Lasso: an open Free Transform box takes the drag with the Lasso selected (#2153) (#2766)
The Lasso reads its own pointer events (lasso_ui::canvas_input) and the canvas
cleared the generic drag buttons for it. With a Free Transform box open, the
press reached the box but the moves and the release were dropped (no lasso
outline was in progress), so the box never changed. The open box now owns the
pointer with the Lasso too, as it already does for the Hand (#2302).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 15:56:43 -04:00
d5694490f5 Channels: Delete with an alpha channel targeted fills that channel (#2734) (#2741)
* Channels: Delete with one channel targeted clears only that channel (#2720)

Edit > Clear ignored the Channels panel target: with a single colour channel
targeted it filled every channel of the Background with the background colour,
and made a normal layer's pixels transparent. It now sets only the targeted
channel inside the selection to the background colour's value for that channel
(partly selected pixels blend), keeps the other channels and the layer's
transparency, and stays one undo step, as Photoshop does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Channels: Delete with an alpha channel targeted fills that channel (#2734)

Edit > Clear ignored an alpha channel or Quick Mask target: it cleared the
active layer's pixels and left the channel alone, and it was disabled on a
non-pixel layer even with a channel targeted. With an alpha channel targeted
(or in Quick Mask mode) it now fills the selection (or the canvas) of that
channel with the background colour as gray, leaves the layer untouched and
stays one undo step, as Photoshop does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 15:53:09 -04:00
d537946ff6 Make the save-dialog memory test path-separator independent (#2745) (#2782)
pick_save builds the suggested path with Path::join, which uses `\` on
Windows, but save_dialogs_remember_where_each_document_was_last_saved
compared it against hard-coded "/dir/name" strings, so it failed on
windows-latest. The behaviour is correct; build the expected values with
Path::join too.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 15:51:08 -04:00
Valentin KleinandClaude Opus 5.5 db7a7885f4 Channels: Delete with one channel targeted clears only that channel (#2720) (#2730)
Edit > Clear ignored the Channels panel target: with a single colour channel
targeted it filled every channel of the Background with the background colour,
and made a normal layer's pixels transparent. It now sets only the targeted
channel inside the selection to the background colour's value for that channel
(partly selected pixels blend), keeps the other channels and the layer's
transparency, and stays one undo step, as Photoshop does.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 15:48:01 -04:00
Valentin KleinandClaude Opus 5.5 e57ee674ae PSD: warn when the Lr16/Lr32 layer block is unreadable, save one layer list (#2700) (#2709)
A 16/32-bit file whose global Lr16/Lr32/Layr block failed to parse opened
as a single Background layer from the merged image with no warning: the
parse error was discarded in PsdFile::from_bytes. The raw block stayed in
the preserved global blocks, so a PSD save wrote the document's fresh Lr16
plus the unreadable original: two layer lists in one file.

- psd: PsdFile::unreadable_layer_block() reports the kept block and its
  parse error.
- io import: a warning names the block and the error and says only the
  merged image was opened.
- io export: a preserved Lr16/Lr32/Layr block is not re-emitted when the
  document's own layers are written.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 15:42:00 -04:00
Sir StarchandClaude Sonnet 5.5 e2aa19341f PSD export: pad regenerated fill blocks to 4 bytes, as Photoshop does (#2759)
Photoshop pads every layer-level tagged block to a multiple of 4 inside the length field; all 567 Photoshop-authored fixtures in the corpora do. The exporter padded regenerated blocks to even only, so a Pattern Fill's PtFl came out 2 bytes short of the boundary for half of all pattern names and left the layer record's extra data unaligned.

The pad is applied where the fill blocks are regenerated, not in the generic loop: preserved blocks must stay byte-identical (psd_structure, roundtrip) and shmd is length-structured (comps_artboards).

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-10-10 15:39:01 -04:00
MarekSpodBiedry ab76c242a1 File > Scripts > Browse: filter the picker to script files (#2452) (#2499) 2026-10-10 15:20:22 -04:00
Benziza 0b4fe4b17f Keep As Is when reusing variable definitions (#2655) 2026-10-10 15:16:42 -04:00
Brandon ThomasandClaude Opus 5.5 939c8f2c70 Progress docs: target-app parity, gaps, alpha gate, readiness by audience (#2696)
Progress docs per craftrules standards/progress-docs.md: target-app parity (merges parity-estimate.md), gaps, roadmap with alpha gate, readiness by audience (full / mainstream / essentials) with Opus 5.5 hours, and UI, brush, format, hardware and localization parity docs. docs/parity.md is now docs/parity-checklist.md.

The Windows test failure (file_dialog::tests::save_dialogs_remember_where_each_document_was_last_saved) is pre-existing on main: the test hard-codes POSIX paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 15:09:04 -04:00
Reynold HuandBrandon Thomas 5ab78e8ce1 feat(ui): the Use Smart Quotes preference turns typed quotes typographic (#204) (#2522)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 14:55:53 -04:00
skylar taylor-barrick 99a3970399 UI.9: preserve PhotoCraft controls in shared UI migration 2026-10-10 12:51:56 -06:00
Erica FrancoandBrandon Thomas 706c730cd2 i18n(es): translate the Add Noise and Reduce Noise dialog controls (#2470)
Ten labels under Filter > Noise and Filter > Sharpen fell back to English in a
Spanish UI. Add Noise showed Distribution, Uniform, Monochromatic and Seed next
to a translated "Cantidad"; Reduce Noise showed Strength, Reduce Color Noise,
Sharpen Details and Remove Jpeg Artifact next to a translated "Conservar
detalles"; Smart Sharpen showed Reduce Noise.

Wording follows the terms the catalog already uses (Noise > Ruido, Sharpen >
Enfocar, Remove > Quitar, Amount > Cantidad) and the file's clean-room note:
written from the plain meaning of the English labels, with no localisation
resource consulted. "Gaussian" is only ever a distribution value here (Add
Noise and Lens Blur), so it reads "Gaussiana".

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 14:46:28 -04:00
Erica FrancoandBrandon Thomas 31def413cc fix(docs): Linux build prerequisites only name Debian packages (#2437)
The prerequisites listed `libxkbcommon-dev ... libgtk-3-dev`, which exist only
on Debian and Ubuntu: on Arch none of those names resolve and `pacman -S` fails
on the whole line, and on Fedora and openSUSE they all need `-devel`. Nothing
else in the repository gives the equivalents.

The app already speaks four distros at runtime: linux_libs.rs carries a
{soname, debian, fedora, arch, suse} table, reads ID and ID_LIKE from
/etc/os-release and prints the matching apt, dnf, pacman or zypper command when
a runtime library is missing. This brings the build instructions up to that.

Also adds the prerequisites to the book's Building page, which said only to
install the Rust toolchain.

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 14:35:12 -04:00
f8ea3d8423 Ruler units keep their own decimal places (#2434) (#2476)
* Ruler units keep their own decimal places (#2434)

Document sizes were shown with one decimal place whatever the unit, so a
1234 px side at 300 ppi read 4.1 in instead of 4.113 in, and millimetres,
centimetres and picas lost a place too.

`Unit::decimals` now follows Photoshop: whole pixels, one place for points
and percent, two for millimetres, centimetres and picas, three for inches.
`fmt_decimals` rounds half away from zero and drops trailing zeros, so a
value is never shown with more precision than it has: 0.7995 in reads 0.8,
never 0.799 or 0.800, and a whole number keeps no trailing .0. It guards the
zero-decimal case so 550 px cannot lose its zero.

The Info panel readout, Image Size, Canvas Size, New Document and the shape
dialog all take their precision from that one place, through the new
`widgets::value_field_prec` and `widgets::unit_decimals`.

Percent keeps its single place: it was not reported and reads better coarse.

* Pass the new decimals argument at the remaining value_field_in call (test)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 14:34:49 -04:00
0c907fb7f9 Properties ▸ Layer Mask: add Photoshop's Refine row (#2425) (#2639)
* Properties ▸ Layer Mask: add Photoshop's Refine row (#2425)

Below Density and Feather the mask section now offers Select and Mask…,
Color Range… and Invert, each dispatching the command the menu item does
(`select.selectAndMask`, `select.colorRange`, `image.adjustments.invert`)
and greyed by the same rule. Invert passes `"target":"mask"` itself rather
than relying on the shell's target routing, so it inverts the mask and can
never reach the layer's pixels (#1137).

Tests: the three controls are present and labelled in both themes and
follow the mask target; Invert inverts the mask pixel for pixel, leaves the
layer's own pixels untouched and makes one undoable step; the two dialog
buttons open the Select and Mask and Color Range dialogs. New "Refine"
label translated in the sixteen complete catalogs.

* Refine row: translate the button labels

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 14:30:23 -04:00
Gert Pellin - GPEandBrandon Thomas 9ccea32651 Layers panel: a dragged layer copies onto its own row and into the empty space below the stack (#1721) (#2525)
* Layers panel: a dragged layer copies onto its own row and into the empty space below the stack (#1721)

* rustfmt

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 14:23:22 -04:00
eab15ffdf6 Image warp: grab anywhere on the grid, Ctrl-click to cut, Warp in the transform menu (#2621)
* Image warp: grab anywhere on the grid, Ctrl-click to cut, Warp in the transform menu

Warp mode of Free Transform now works from anywhere inside the grid, not
only on its points:

- Press and drag on any part of the grid and the surface under the pointer
  follows it. The surrounding anchors bend with it, fading out with
  distance. The picture's border stays put unless the grab is made near
  it, and then the border bows through its own handles. The four corners
  never move.
- Ctrl-click (or Option-click) cuts the grid both ways at the pointer.
- Right-clicking a Free Transform box lists Warp after Perspective. The
  menu marks only the box's real current mode.
- Anchor and handle drags keep every grid line smooth through its anchors.
- Grid points are quieter: anchors are small, and a handle with its arm
  shows only near the pointer or while it is dragged.
- The preview draws the most displaced cells first and samples finer where
  the warp pulls hard, so a strong pull no longer shows as a comb.

Refs #214

* Warp options bar: Split, Grid and Warp controls with orientation and bend always shown, Reset, and the buttons right after the fields

The Warp bar now reads Split, Grid, Warp style, orientation and Bend / H / V.
The orientation and bend fields are always there and only act on a preset
style. A new Reset button puts the grid back to the default untouched one
while staying in warp mode.

Cancel and Commit sit right after the fields instead of at the far right of
the window. A bar too narrow for both pins them to the right edge and clips
the fields, so they stay reachable. The Free Transform bar shares the same
function and gets the same placement.

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 14:22:46 -04:00
Ayan 76fa217669 Quick Selection: 3.5x faster CPU strokes with hybrid graph cuts (#2436)
* Speed up Quick Selection with hybrid graph cuts

* Record Quick Selection stroke benchmarks and regression coverage
2026-10-10 14:17:48 -04:00
ac279f6268 Keep the layer's place in the stack during Free Transform (#2439) (#2480)
The Free Transform preview drew the moving pixels over the whole
document, so a layer under others jumped to the top while the box was
open. Plain Normal layers over it are now composited once on their own
and drawn over the moving pixels; the canvas under the box leaves them
out. The box still moves on the GPU mesh with no per-frame composite.

Adjustment layers and other blend modes depend on what is under them,
so the first such layer from the top, and everything under it, stays in
the document under the box as before.

Co-authored-by: Simon Geljic <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 14:16:24 -04:00
225ccc0db1 Crop tool: Photoshop's default mode turns the image behind an upright box; Use Classic Mode (P), Auto Center Preview (#1919) (#2545)
* Crop tool: Photoshop's default mode turns the image behind an upright box; Use Classic Mode (P), Auto Center Preview (#1919)

The Crop tool's gear menu gets Use Classic Mode (P toggles it while the tool shows a box; off by
default, as in Photoshop) and Auto Center Preview (on by default). In the default mode the box
stays upright on screen: a drag outside it turns the image about the box's centre (Shift 15 deg
steps, angle readout), a drag inside moves the image under the box, the arrow keys nudge the
image, Straighten turns the image so the line is level, and with Auto Center Preview a drawn or
resized box is re-centred in the canvas. Classic Mode is the previous behaviour.

The crop model and the commit are shared: crop_rect + crop_angle and one image.crop {angle}.
crop_mode.rs only drives the view: while a frame is edited the view's rotation is -crop_angle,
pivoting so the box (or the pressed point) stays put, and the user's view (a Rotate View turn,
its centre) is put back on commit, cancel, leaving the tool or switching to Classic Mode. The
untouched default frame leaves an R turn alone. The options live in ToolOptions.crop_shield
(classic_mode, auto_center_preview; ui.set cropShield). ui.pointer reads a default-mode drag's
points in the view at its press, so an up where the last move was is idempotent.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Crop default mode: match Photoshop (view upright on tool pick, live Auto Center, image-turn readout, gear menu order) (#1919)

Checked by hand against Photoshop in its default (non-classic) mode:

- Picking the Crop tool turns a Rotate View (R) turn upright at once (about the view centre),
  and the view stays upright after Enter or Esc: the save/restore of the user's view is gone.
  Classic Mode still leaves the view alone (not checked against Photoshop).
- The angle beside the pointer while the image turns is the image's turn, clockwise positive.
- Auto Center Preview keeps a box being resized centred live: the handle follows the pointer,
  the box grows on both sides, and on the image the opposite edge (with Alt the centre) stays
  put. Computed from the press, so the view following the frame can't feed back into the drag.
- Gear menu order as Photoshop's: Use Classic Mode (P), Show Cropped Area (H), Auto Center
  Preview, no separator; Classic Mode greys out the other two. Show Cropped Area then acts as on
  and H does nothing (the stored choice is kept). German: Classic-Modus verwenden, Automatische
  zentrierte Vorschau.
- Crop preview past the canvas in a turned view: each band is drawn as its turned quad (the
  screen bounding box stretched band textures and spread the checkerboard). The white corners in
  the earlier offscreen snapshot were egui_kittest clamping the repeating checker texture; the
  real app shows the checkerboard in both modes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* docs: regenerate scorecard for the crop default-mode row (#1919)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Crop default mode: the canvas keeps the view the Crop tool moves; a move starts from a centred box (#1919)

Tried by hand in the app: with Auto Center Preview on, a drag inside the box made the box wander
instead of moving the image, and a handle drag didn't keep the box's centre in place (after a
Space pan, too). Root cause: canvas_view works on a copy of the view for the frame and writes it
back at the end, so every camera change the Crop tool made during the frame (the image moving
with the pointer, the live-centred resize, Auto Center on release, the pivot while turning) was
undone, while the frame itself moved in the document. Tests driving tool_event never saw it.

- canvas_view notes the camera before the frame's input and, before writing its copy back,
  keeps a centre or rotation a tool changed meanwhile.
- With Auto Center Preview a move inside an off-centre box (after a pan) centres the box first,
  then grabs the image point now under the pointer.
- New tests/crop_default_mode.rs drives the full app UI with egui pointer and key events over
  several frames (offscreen wgpu): the box stays put while the image follows the pointer, and a
  resize after a Space pan keeps the box's centre fixed while the handle follows the pointer. Both
  failed before the fix.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Crop default mode: a moved or resized box stays where it is on screen (#1919)

Checked in Photoshop: after a Space (Hand) pan the box isn't snapped back to the middle of
the canvas. A drag inside moves only the image, the box staying wherever it is; a resize keeps the
box's centre where it was at the press (also after a pan), and its release no longer pans the box
to the middle. Auto Center Preview still centres a newly drawn box on release and X still
re-centres. Classic Mode is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Crop tool: Classic Mode turns a Rotate View turn upright too (#1919)

Checked in Photoshop: with Classic Mode on and the view turned with Rotate View (R), picking
the Crop tool also turns the view upright, and the crop frame stays on the same image area. So the
Crop tool now drives the camera in both modes: default mode keeps it at -crop_angle (the box
upright), Classic Mode at 0 with the frame drawn with its own turn. Picking the tool pivots about
the view centre; commit and cancel leave the view upright in both modes, and P switching modes
never brings the R turn back. Auto Center Preview stays default-mode only.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Regenerate the scorecard; update the crop test's header

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Crop: snap a new box's corner inside the untouched default frame in both modes (#2549 with #2545)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 14:14:19 -04:00
f521e231c3 Free Transform: refuse a locked layer up front (#2585) (#2609)
Cmd+T (and Edit > Transform, the Move tool's transform controls) on a
layer locked in place opened the box and previewed every drag; only the
commit failed. Photoshop refuses before the box opens with "Could not
complete the Free Transform command because the layer is locked."

transform_cmds::locked_for_transform applies the commit's own rule (its
own position/all lock or an enclosing group's, a group's locked layers,
never the Background, which becomes Layer 0) and transform_tool::begin
asks it first, opening the alert in the Error dialog as the Move tool's
lock message does. Translated in every catalogue.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 14:10:37 -04:00
3092d3b6f9 Tests: line-tables-only dev debuginfo, nextest GPU group, faster loop docs (#2204) (#2414)
- [profile.dev] debug = "line-tables-only", matching CI's CARGO_PROFILE_DEV_DEBUG; halves link
  time and PDB size for test binaries.
- .config/nextest.toml: optional cargo-nextest runs with the GPU tests capped at 4 concurrent
  processes (unlimited ones time out in wgpu).
- AGENTS.md / docs/development.md: iteration commands (--lib --tests, --test <file>, nextest,
  doctests separately). CI is unchanged.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 14:03:30 -04:00
AyanandBrandon Thomas 0a102eb920 Pixelate: CMYK Facet 13.7x faster, Lab halftone 5.0x faster (#2588)
* Reuse Facet quadrants and halftone dots without changing pixels

* Record full-image Pixelate timings and exact-output checks

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 14:03:03 -04:00
mroxsoandhighperfocused d59d2b509f Channels: tint single colour channel views on the canvas with Show Channels in Color (#2385) (#2574)
Interface > Show Channels in Color only reached the Channels panel
thumbnails (#1986); the canvas overlay hard-coded in_color = false, so an
isolated RGB/CMYK channel stayed gray while its thumbnail changed color.
channel_view::ensure now reads the preference (the view cache key already
carries the flag, so toggling rebuilds the texture), and a hidden Lab
Lightness goes neutral instead of black under the preference, so an
isolated a/b channel tints over mid gray like Photoshop. Lightness itself
stays grayscale (Adobe's exception).

Verified with the offscreen snapshot example: RGB green canvas goes
(128,128,128) -> (0,128,0) and CMYK cyan -> (0,176,232) when the
preference is on; unit tests cover render(), the Lab exception and the
cache key.

Co-authored-by: highperfocused <[email protected]>
2026-10-10 14:02:38 -04:00
36dbceed80 Search: an exact name match ranks first (#2160)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 14:01:27 -04:00
texjer 78f32cac26 Dialogs: Tab walks the text fields only, as in Photoshop (#1285)
In Photoshop, Tab in a dialog goes from one text field to the next (Hue →
Saturation → Lightness; Name → Width → Height → Resolution) and never stops
on sliders, dropdowns, checkboxes or buttons; the field reached has its text
selected. egui's Tab walked every focusable widget in creation order, so the
first Tab in Hue/Saturation landed on the dialog's title bar.

field_tab.rs: the dialog frame takes Tab / ⇧Tab itself, fields register as
they are laid out (widgets::number_edit and the New Document name) and focus
moves to the next one. The focus request is deferred a frame so egui's own
select-all on focus fires (requesting focus after layout never reads as
"gained focus"). New Document opens with the name selected, so typing
replaces it and Tab goes straight to Width. After an arrow-key step the
number field's text stays selected, so typing replaces the value.
2026-10-10 14:01:17 -04:00
3a29be7f5e Colour swatches open PhotoCraft's Color Picker: filter dialogs, Preferences, Note, Count, artboard (part of #2144) (#2571)
These swatches opened egui's compact popup. color_picker_ui::request_field
lets a dialog ask for the picker on any field (a key or a JSON pointer);
the Count and Note colours go through count.setGroup and a noteColor
target, the artboard background through layer.artboard.set. The Count and
Note swatches also treated their sRGB colours as linear.

Co-authored-by: Claude <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 14:01:06 -04:00
cebdbb21ea fix(ui): unify Spectrum menu spacing and hover contrast (#2323)
* fix(ui): unify Spectrum popup padding and hover contrast (#2187)

* fix(ui): unify Spectrum popup padding and hover contrast (#2187)

* fix(ui): unify Spectrum popup padding and hover contrast (#2187)

* fix(ui): unify Spectrum popup padding and hover contrast (#2187)

* fix(ui): unify Spectrum popup padding and hover contrast (#2187)

* fix(ui): remove unused menu token after sharing popup style

* test(ui): cover Spectrum popup hover contrast and theme isolation

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 14:00:56 -04:00
fa33712dd3 Speed up Iris Blur without changing output (#2578)
Co-authored-by: optimalbytee <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 14:00:53 -04:00
JeremyandClaude Opus 5.5 7e46557283 Color panel: the field and hue strip fill the panel height, like Photoshop (#2455)
The pro Color panel drew its saturation/brightness field at a fixed 120 pt, so a taller
panel left empty space under the hex/RGB readout. The dock now passes the group body height
to the field, which takes it less the readout (and a second readout line in a narrow dock).
Never below 120 pt; a non-finite height falls back to it.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 14:00:46 -04:00
caa43fa3f6 Keep plug-in menu rows under Filter › Plug-ins in every language (#2540) (#2627)
* Keep plug-in menu rows under Filter › Plug-ins in every language (#2540)

plugin_ui::insert_menu_items built the insertion path from translated
strings (tl!("Filter"), tl!("Plug-ins")), but MenuItem::path is the
untranslated English path from a command's engine spec: the renderer
groups rows by it and translates only at display time. Under any
language whose catalog translates those menu names (ja, fr, ...) the
plug-in rows got a path no menu node matched, so installed WebAssembly
plug-ins were never drawn. Take the path from the "Install Plug-in…"
item the rows sit above instead, and cover it with a test that installs
the invert.wasm fixture under a Japanese language scope.

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 14:00:36 -04:00
alexanderalberandBrandon Thomas ee4373521e Ctrl+Tab and Ctrl+Shift+Tab switch to the next and previous document (#2340) (#2353)
* Ctrl+Tab and Ctrl+Shift+Tab switch to the next and previous document (#2340)

Photoshop's document-cycling keys, on macOS too (Cmd+Tab belongs to the
system). They follow the tab order and wrap around at either end, and they
reach the documents even while a field or widget has the keyboard focus,
since nothing edits with Ctrl+Tab. Plain Tab still hides the panels.

generated with Claude Code

* Contributors: add my name for the About window

generated with Claude Code

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 14:00:26 -04:00
edd9fe12d7 Skip distant TSL-off stroke layers during composition (#2473)
* Skip distant TSL-off stroke layers during composition

* Narrow the TSL-off stroke shortcut: shape outlines count, other clipping bases keep the empty skip

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:58:04 -04:00
865c8a15f8 fix(ui): toggle color swatches when selecting or deselecting a layer mask (#2560)
* fix(ui): toggle color swatches when selecting or deselecting a layer mask (#2420)

- Call sync_mask_targets() when handling ui.maskTarget / ui.vectorMaskTarget
  clicks in the Layers panel, Channels panel, and control channel
- Automatically target the layer mask when creating new adjustment or fill layers
- In tools.defaultColors, reset to mask default colors (white/black) when a
  mask is currently targeted
- Add unit test in engine and UI harness test in mask_thumbs_ui

* rustfmt

* Rasterize prompt test: target the fill layer itself, now that a new fill layer targets its mask

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: huudinh1401 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:55:43 -04:00
Elvis33LEandBrandon Thomas ff9663bc9a EXR parts: import parts, channel groups and an AOV precomp as layers (#2338)
* EXR parts: import parts, channel groups and an AOV precomp as layers

file.exrParts lists what an EXR holds for a chooser - flat parts, prefixed
channel groups (diffuse.R/G/B), Cryptomatte layers as information;
file.openExrParts imports the chosen ones as the layers of one document
(F16 lossless as F32, linear sRGB tagged), with an optional additive
beauty precomp summed from the light-path AOV set (direct/indirect
diffuse+specular, emission; transmission/sss/volume when present) that
fails naming the missing AOVs. The codec gains decode_exr_channels for
exact named channels of one part; io shares the image_surface band writer.

File › Open EXR Parts… picks an EXR and opens a plain command form: a
checkbox per part and channel group (labels are the data's names with
size and channel count), a both/left/right view dropdown, and the
precomp checkbox. Cryptomatte layers ride along as non-rendered data for
the control channel. Form fields gain __labels for verbatim data-driven
labels; the new strings are catalogued in all sixteen complete languages.

* Regenerate parity and scorecard docs

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 13:51:06 -04:00
David MannandClaude Opus 5.5 7c18c68e24 Crop tool: W x H x Resolution mode resamples the crop to a size and resolution (#2443) (#2483)
image.crop takes optional targetWidth/targetHeight (px), resolution (ppi)
and resample: the cropped area is resampled to exactly that size (the
Image Size code path, now shared) and the resolution set, in the same
undo step, also after a turned crop. The Crop options bar gets
W x H x Resolution with unit-aware W/H fields, a px/in or px/cm
resolution, Photoshop's built-in size presets, Front Image (and I) and
Clear; the frame holds W:H while drawn or resized, X and the swap button
swap W and H.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-10 13:46:31 -04:00
ab15e4ea96 Curved shapes no longer report bounds 1 px too wide (#2537) (#2641)
* Drop f32 round-off coverage in the vector rasterizer (#2537)

Each row's cell accumulator is prefix-summed in f32. A left boundary adds
coverage and the right boundary subtracts it, but for curved or off-grid
edges the two don't cancel exactly, leaving ~1e-7 coverage in the pixel
just past the shape. Shape layers wrote the fill colour there (alpha
rounding to 0 at 8/16-bit, ~1e-7 at 32-bit), so content bounds and
shape.info reported curved shapes one pixel too wide.

Snap coverage below 1e-6 to 0 when writing a row. That is under half a
16-bit step, so 8- and 16-bit coverage values are unchanged; only the
residue pixels go away. Selections, vector masks and strokes share the
rasterizer and get the same fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Rasterizer: NaN coverage becomes 0, not full (#2537)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:41:51 -04:00
14599472af Re-render shapes when an artboard move grows the canvas (#2389) (#2623)
Shape layers render their pixels clipped to the canvas. Moving an
artboard (layer.artboard.set or layer.translate) re-rendered its shapes
before fit_canvas grew the document, so a shape moved past the old edge
came out missing or cut off until another shape edit refreshed it.

fit_canvas now re-renders every shape whenever it changes the canvas
size, which covers all its callers.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:41:47 -04:00
Harrison O'Connor-Hoover 0a7b8cab54 Create new documents by double-clicking presets (#2290) 2026-10-10 13:40:51 -04:00
Harrison O'Connor-Hoover ca3718e7b5 Route menu Cut through the active type selection (#1448) 2026-10-10 13:40:40 -04:00
Simon f5de46e60a Menus: Reveal in Finder names the platform file manager off macOS (#217) (#2586)
* Menus: name the platform file manager in Reveal in Finder off macOS

The command opens Explorer on Windows and the desktop's file manager
(xdg-open) on Linux, but the Smart Objects menu item and the document
tab menu still said "Reveal in Finder". menus::reveal_label picks
"Show in Explorer" on Windows and "Show in Folder" on Linux and the web;
macOS keeps "Reveal in Finder". The menu catalogue (docs/parity.md),
the engine command labels and the command ids stay unchanged.

The help search, command palette and keyboard shortcut list read the
relabelled menu item, so they follow. Every complete language gets both
new labels, with the localized Windows name for Explorer.

* scorecard: platform shortcut hints and Reveal label are done (UI-217-19)
2026-10-10 13:40:30 -04:00
reese e81d5fd4ec fix(ui): nudge number-field digits 1 pt up so they look centred (#1322) 2026-10-10 13:40:20 -04:00
Nigel Ihza Firdausy f8744c6b81 fix(ui): dim unchecked layer style effect labels even when selected (#2288) (#2321) 2026-10-10 13:40:10 -04:00
62aa421d75 Keep menu separators out of the command palette (#2479) (#2632)
The palette fuzzy-matched every menu item against its label and menu
path, separators included. A "---" row under File or Filter matched
queries like "f" on its path and filled the results with blank rows.
Skip separators the same way Help > Search already does.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:40:00 -04:00
Elvis33LE b75267899d DNG: lossy compression 34892 (baseline JPEG tiles) (#2021)
* DNG: lossy compression 34892 (baseline JPEG tiles)

Adobe's lossy DNG (compression 34892) decodes: each tile is a complete
baseline JPEG (8-bit luma at tile size), decoded by zune-jpeg into the
tile geometry (a mismatch is an error), widened 0xFF -> 0xFFFF like
Photoshop's read of 8-bit CFA data. Predictors and the rest of the
pipeline are unchanged.

testgen grows LossyJpegTiles (image-rs encodes the Q60 fixtures behind
the testgen feature), so CI runs a decode oracle: a smooth ramp stays
within a few quantisation steps of the 8-bit source, and a tile cut
mid-stream fails cleanly.

* Lossy DNG: check the tile JPEG header before decoding; zune deps go workspace

decode_headers() runs and the (width, height) == (s.w, rows) check fires
before decode(), so a hostile SOF cannot allocate the decoder's buffers
(up to 16384x16364) before the size mismatch is caught. The mismatch has
a regression test that swaps a 32x32 tile JPEG for a 16x16 one. zune-core
and zune-jpeg move to [workspace.dependencies] next to image and flate2.

* chore(ui): format prefs_ui (the workspace fmt gate is red on main until #2417 lands)

* Lossy DNG: 3-sample LinearRaw (YCbCr) decodes to RGB; tiles size-check

Real lossy DNGs are 3-sample YCbCr LinearRaw, not single-channel CFA:
the tile now decodes through zune-jpeg's YCbCr-to-RGB output when
SamplesPerPixel is 3 (gray stays for CFA), the decoded length is checked
against the tile's sample count, and other sample counts say unsupported.
The generator writes RGB tiles for 3-sample specs. A LinearizationTable
maps the decoded samples in the develop stage as before - nothing to add
in the sensor. Test: a 3-sample ramp with 64-step channel separation
(surviving Q60 chroma quantisation) decodes within the quality band.
2026-10-10 13:39:57 -04:00
Valentin KleinandClaude Opus 5.5 c908f76827 Dropdowns: open lists start at their widest option's width (#2607) (#2634)
egui takes a plain row's frame stroke off its padding but draws a hovered
row with the stroke, so a row grows by two stroke widths under the pointer.
The popup keeps the widest width it has seen, so scrolling the widest option
under the pointer widened the list by 2 pt. The shared dropdowns now size the
open list to the widest option as drawn hovered from the first frame.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:39:50 -04:00
fdf5cd668b Push neighbouring dock groups when dragging a splitter (#2573) (#2624)
Dragging a dock splitter only traded height with the next expanded group,
so it hard-stopped once that group hit its minimum. resize() now shrinks
the groups on the side the splitter moves into in turn, nearest first,
each down to its minimum (skipping collapsed groups, the filler taking its
share implicitly), and grows the group on the other side by what they
gave. Works both ways; the column height stays the same.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:39:36 -04:00
Jason 7e6fc93aa9 Close a document tab with a middle click (#2570) (#2637)
Middle-clicking a document tab closes that document, as in a browser. Both
tab strips share one rule (`tab_close_clicked`): the x, or a middle click
anywhere on the tab, including over the x. It routes through the same guarded
`file.close` as the x and the context menu, so a document with unsaved
changes still gets the Save / Don't Save / Cancel prompt.

Opening-file tabs are untouched: their x still cancels the job.
2026-10-10 13:39:27 -04:00
alexanderalber 1c4a0d12da Image Size and Canvas Size open on Width, selected (#2329) (#2357)
The filter dialogs open on their first number since #1757: typing replaces
it and Enter applies it. Image Size and Canvas Size draw their own bodies
and were left out; they now go through the same once-per-dialog focus,
moved into dialogs::first_field_focused.

generated with Claude Code
2026-10-10 13:39:17 -04:00
Roaldo Sulejmani 30bf920d75 Windows: keep the custom title bar's window borderless (#2246) (#2401)
winit 0.30 gives an undecorated window WS_CAPTION | WS_BORDER and hides the
non-client area by spreading the client rect over it (rust-windowing/winit#2419).
On some Windows systems the compositor still reserves that frame, so the content
is drawn offset by the caption and border while input stays at the client origin:
black bars at the window's top-left and a pointer that no longer matches what it
points at.

Strip WS_CAPTION | WS_BORDER from the window (keeping WS_THICKFRAME and the window
buttons, so edge resizing and Aero snap keep working) and recalculate the frame,
restoring winit 0.27's undecorated behaviour. The guard runs every frame from
raw_input_hook, so a style winit restores on a flag change (maximize, restore, …)
is taken off again. Decorated windows (the system title bar preference) are left
alone.
2026-10-10 13:39:07 -04:00
Jason 352e1cf168 Opening card: a long file name no longer pushes Cancel out of the card (#2423) (#2444)
The card painted a fixed 340×132 rect and laid its rows out with no height
constraint, so a title that wrapped (long names, long translations) pushed
the percentage and Cancel onto the backdrop. The title and message are now
single-line truncated labels (the full text on hover), and the card is
painted after its rows are laid out, growing from the 132 pt minimum to fit
them. It stays centred at the height it needed last frame, settling in one
repaint.

The regression test fails on the old layout (the title wrapped to three
lines) and asserts the title is one line and both the title and Cancel lie
inside the card.
2026-10-10 13:38:57 -04:00
Valentin KleinandClaude Opus 5.5 0f6d3dfea1 Paste: a web Ctrl/Cmd+V key press and its paste event are one paste (#2638) (#2643)
On the web eframe forwards the Ctrl/Cmd+V key-down and then the browser's
paste event (Event::Paste when the clipboard holds text) in the same frame.
clipboard_keys turned the event into a second press, so edit.paste ran twice.
A clipboard event right after its own command key press now counts as that
press; the same goes for Ctrl/Cmd+X with Cut and Ctrl/Cmd+C with Copy.
Desktop is unchanged: egui-winit never sends both.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:38:48 -04:00
David MannandClaude Opus 5.5 6f5e16a0c4 Filter Gallery: preview at the scale OK applies (#2502) (#2524)
Below 100 % the preview filtered every k-th source pixel with unscaled
params, so strokes, grain and textures showed several times too large.
It now runs the stack at full resolution on the visible region (the
filters read their reach around it, and noise and textures are seeded by
document position, so the pixels equal the same crop of the applied
result), then averages k x k blocks down to the zoom.

On the desktop the render runs on a worker thread with a progress bar in
the zoom bar; the last preview stays up and moves with the view, a stale
render is cancelled once the settings settle, and closing the dialog
cancels it. Web and inline sessions render synchronously.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-10 13:38:39 -04:00
0a18937573 Text fields: copy, cut and paste through the Mac menu's key equivalents (#2568)
A text field copies and pastes on egui's Copy / Cut / Paste events, which egui-winit makes from
the window's key. With the native menu bar, AppKit takes ⌘C / ⌘X / ⌘V as Edit › Copy, Cut or
Paste's key equivalent whenever that item is enabled, and the key reaches egui as a plain key
press, which a text field ignores. So pasting text into a field (a dialog's text input, a panel
search box) worked only while PhotoCraft's own clipboard was empty and Edit › Paste disabled.

While typing, ⌘C / ⌘X presses become Copy / Cut, and a ⌘V press asks the window for the
clipboard text, which arrives as a Paste event. egui-winit never sends these presses itself
(it sends the events instead), so this changes nothing without the native menu. It covers the
type tool's editor as well as egui text fields.

Co-authored-by: Trade-Mottoes <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:38:33 -04:00
0384b1af6d Warp Text: the dialog opens with the layer's warp and previews it live (#218) (#2539)
* Warp Text: the dialog opens with the type layer's current warp

Type > Warp Text... always started at Arc with Bend 50, whatever warp
the layer had, so OK without a change replaced a Flag warp with Arc.
The dialog is now the schema dialog of type.warpText: it starts from
the shown type layer's style, bend, distortions and orientation (None
for a layer without warp, as in Photoshop) and keeps the targets it
opened on (selected type layers or the inline edit). Remembered dialog
values never override the layer's warp.

* Warp Text: the dialog previews the warp live on the canvas

The Warp Text dialog showed its result only after OK. It now has the
schema dialogs' Preview checkbox and live canvas preview; Cancel leaves
the document as it was and OK stays one history step.

The preview of a large document runs on a reduced proxy, but Warp Text
renders the type again from the layer model, at full size: the preview
showed the text k times too large and out of place. Warp Text runs on
the full-size copy and its result is reduced instead.

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:38:17 -04:00
Erica FrancoandBrandon Thomas 1e2194a054 fix(ui-egui): ui.key with ctrl does not trigger shortcuts off the Mac (#2430)
* fix(ui-egui): ui.key with ctrl does not trigger shortcuts off the Mac

`ui.key` and `ui.pointer` built egui's modifiers with `command` and `ctrl` as
independent fields. Off the Mac they are the same physical key: egui asks for
both to carry the same value and matches shortcuts on `command`, so a request
with only `ctrl` set produced a state a real key press never produces and
matched nothing. `ui.key {"key":"N","ctrl":true}` replied ok and did nothing,
while `command: true` opened New Document.

One `modifiers_from` helper now serves both: off the Mac the two flags are
paired, on the Mac they stay apart as ⌘ and Control. Callers already sending
`command` are unaffected.

* contributors: add my own entry (GitHub profile name)

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 13:38:12 -04:00
c287ecabc5 Fixed a bug where if you select a mask and hit the delete key, it deletes the image (#2635)
* Fixed a bug where if you select a mask and hit the delete key, it deletes the image

* Delete on a targeted mask: fill the selection with the background colour; delete the mask only with no selection

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:33:53 -04:00
Nigel Ihza FirdausyandBrandon Thomas 8d13aff784 fix(layers): preserve Background behavior across merge, duplication and canvas resize (#2419)
* fix(layers): keep Background semantics across merge, duplication and canvas size

Preserve destination locks in Merge Down, share the normal Background-copy rule with multi-layer duplication, and convert a Background to a paintable layer when extending its canvas transparently.

Add depth-aware regression coverage and ordinary-layer controls for #2380, #2381 and #2384.

* refactor(layers): copy lower-layer locks without cloning Copy data

* Format background_layer_consistency test

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 13:26:11 -04:00
28ed1c1147 Handle allocation failures in large pixel operations (#2530)
* Make large pixel operations allocation-fallible

* Warp: drop the fixed 400 MP cap; fallible reservations already cover large transforms

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Adapt #2530 to main: fallible steep-Distort warp, Result from mask paste in float moves; regenerate scorecard

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:26:07 -04:00
David MannandClaude Opus 5.5 d456f6701e Filters: full-resolution preview for Add Noise, Wind, Extrude, Tree, the Filter Gallery and more (#2063) (#2494)
A sweep of every previewed command (default params plus small and large
pixel sizes, on smooth, sharp and noisy images) compared the 1/4 proxy
preview with what OK applies. Still mismatched after #2207:

- Fixed pixel features, now previewed at full resolution: Add Noise,
  Reduce Noise (fixed kernel radii), Custom (5x5 kernel), De-Interlace
  (scan lines), Trace Contour (1 px lines), Wind (fixed streaks), Extrude
  (depth in px), Tree (6 px branch segments), all 47 Filter Gallery
  filters, and Indexed Color / Bitmap when they dither.
- Lens Correction's perspective horizontal/vertical and Tree's and
  Picture Frame's size are relative, not pixels: no longer divided by k.
- Negative lengths (Offset left/up, Displace) were clamped to +0.1.
- Shadows/Highlights' radii were not scaled.
- Mosaic rounds its cells: k now divides the cell size evenly.

The new every_preview_shows_what_ok_applies test checks all previewed
commands (about 3 s); sweep_all_previews (ignored) prints the table.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-10 13:25:59 -04:00
743d81307b Fix/2361 scrub layer labels s20261010 t083444 z og3kyw (#2397)
* fix(layers): scrub opacity and fill by dragging labels (#2361)

* test(layers): compare translated scrub labels as text

* test(layers): query egui label roles for scrub gestures

* cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Layer label scrub test: find the text label by its value on the popup arrow's row

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:24:54 -04:00
401357306b Shift-click New Group groups the selected layers (#2561) (#2613)
The Layers panel New Group button always ran layer.new.group, so
Shift-click made an empty group too. Photoshop documents Shift-click on
that button as grouping the selected layers (same as Layer > Group
Layers). Shift-click now runs layer.groupLayers; a plain click still
adds an empty group, as in Photoshop.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 13:20:12 -04:00
Manuel MontotoandClaude Opus 5.5 0140ffdf9d fix(ui): keep menus responsive on documents with thousands of layers (#2454)
With a 3,593-layer PSD open, an open menu rebuilt its 809 items every
frame in about 700 ms. Each item's enabled/checked state looks up the
active layer several times, and Document::layer built the whole layer
list (one allocated path per layer) for every lookup.

- Document::layer and path_of search the tree directly: 265 us -> 23 us
  per lookup on that file, 700 ms -> 87 ms per menu build.
- An open menu reuses its items between frames, rebuilding when the
  native menu's state hash changes or on a click or key press. The hash
  now also covers a running background job.


Claude-Session: https://claude.ai/code/session_01TABvQWhsoDmc14uLCnkBJJ

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:17:38 -04:00
bfbc9903d5 cms: accept ICC DeviceLinks whose output isn't a 3-channel PCS (#2348)
A DeviceLink's header PCS field holds its output colour space
(ICC.1:2010 §7.2.7), so a CMYK→CMYK link has a 4→4 AToB0. The LUT
channel check hard-coded 3 outputs and rejected such files as invalid,
so users were told a well-formed profile was corrupt and never reached
the "DeviceLink profiles cannot be used" error.

Check DeviceLink LUTs against the header's output space instead, and
only let a Lab DeviceLink through link_stages when its tables end in
3 channels, so a Lab→CMYK link gets the unsupported error rather than
building a mismatched transform.

Fixes #2337


Claude-Session: https://claude.ai/code/session_01X5k8jSoLtGswanmHBipHER

Co-authored-by: Leel Wasanatha <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:16:32 -04:00
d166450c77 Hue/Saturation: Colorize at 0% saturation gives grey, not a 25% tint (#2343)
Colorize floored saturation at 25% on both the CPU (compose::adjust::hue_saturation) and the
GPU shader, so dragging Saturation to 0 with Colorize ticked still tinted the image. Photoshop
leaves only the lightness at 0%. The floor is gone from both paths, so 1-24% now tint
progressively too.

The floor also stood in for Photoshop's 25% starting saturation when Colorize is switched on.
The dialog's checkbox already sets that; the hueSaturation params now do the same when a call
turns Colorize on without giving a saturation, so {"colorize": true, "hue": 30} still tints.

Fixes #2326.

Co-authored-by: lloyd <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:16:26 -04:00
MrCloudy2andClaude Opus 5.5 4760f75b4d Blend modes: Fill below 100% works inside the blend for Photoshop's special eight (#2552)
* Blend modes: Fill below 100% works inside the blend for Photoshop's special eight

In Photoshop, Fill and Opacity are the same for most blend modes, but not
for eight: Color Burn, Linear Burn, Color Dodge, Linear Dodge (Add),
Vivid Light, Linear Light, Hard Mix and Difference. PhotoCraft treated
Fill as Opacity for all of them, so a Difference layer at 50% Fill gave
(150,90,110) where Photoshop gives (150,60,10).

Measured on Photoshop 27.11 (scripted, 24 cases at Fill 25/50/75% with
two colour pairs): below 100% Fill, Photoshop pulls the layer's colour
toward the mode's neutral colour (black for Color Dodge, Linear Dodge,
Difference; white for Color Burn, Linear Burn; 50% gray for Vivid and
Linear Light) and blends that at full strength; Hard Mix becomes
clamp((b - f(1 - t)) / (1 - f)). Opacity still mixes the result in.
That reproduces 31 of 32 values within 1 level (Hard Mix at 75%: 3).

CPU (psblend::composite_fill, the final blend of plain pixel, shape and
type layers) and GPU (Kernel::Blend takes Fill in the spare uniform slot)
agree; Dissolve keeps Fill as coverage. Layers with effects, adjustment
layers and groups keep the old behaviour for now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* GPU: composite_fill with a single blend_rgb call, so fs_blend stays small

The first version added a third inlined copy of blend_rgb (every blend
mode) to fs_blend: composite_g's two plus blend_rgb_fill's. Windows CI
(software WARP adapter) then timed out rendering the UI in
arbitrary_rotation_preview, which passes on main; a larger shader
compiles noticeably slower there.

composite_fill now handles every case itself with one blend_rgb call
(Fill as coverage for normal modes, the special-eight blend, Lab Normal
mixing, the text gamma space) and is fs_blend's only composite path,
leaving it with fewer inlined copies than on main. Same results: the 35
GPU parity tests pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:16:20 -04:00
43a2cfdf6d Bevel contour: drop the glow-style Range stretch (#2498)
The bevel Contour element mapped the height through contour(min(v / range, 1)),
the glow transfer. At the default 50 % range that flattened a Linear contour to
a bevel half as wide as Photoshop's: on a real 18 px smooth inner bevel at
136 % depth the top-edge highlight was gone 15 px in, where Photoshop's is
still 0.19 at 16 px. The contour alone matches that file (bad pixels 0.38 % ->
0.03 %, max error 63 -> 25 / 255) and lowers the bad pixels of every contour
oracle (bevel-inner-contour-ramp-peak 25.9 -> 21.8 %, -double-ring-aa-r70
25.2 -> 21.0 %, bevel-pillow-chisel-hard-gloss-and-contour 11.4 -> 7.2 %);
the other 23 bevel oracles are unchanged. What Range does instead is open.

CPU (compose) and GPU (fx) share the new bevel_contour_lut.

Co-authored-by: Justin Campos <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:16:14 -04:00
MrCloudy2andClaude Opus 5.5 2c163bf73d Legacy Brightness/Contrast: brightness first, then contrast around 128, as in Photoshop (#2615)
* Legacy Brightness/Contrast: brightness first, then contrast around 128, as in Photoshop

With Use Legacy on, PhotoCraft applied contrast first and then added
the brightness, so any setting that moves both sliders came out wrong:
brightness +40 with contrast +30 mapped mid-grey 128 to 168, where
Photoshop gives 185 (up to 17 levels darker across the midtones).

Measured on Photoshop 27.11 (scripted, a gray ramp through seven
settings): Photoshop adds the brightness, then scales contrast around
128/255. Contrast 80 keeps 128 at 128; the 0.5 pivot moved it to 130.
With both changes every measured value matches within 1 level, on the
CPU and in the GPU adjustment kernel.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Legacy B/C: brightness after contrast when contrast is lowered

The corpus caught it: psd-tools' brightnesscontrast_legacy_grayscale.psd
(brightness -23, contrast -26) matched Photoshop with the old order and
was 6 levels off with brightness first. Photoshop adds the brightness
before contrast when contrast is raised (measured: +40/+30 maps 128 to
185) and after it when contrast is lowered. The measured cases with
lowered contrast had brightness 0, so they could not tell.

CPU and GPU kernel (brightness after contrast goes in p0.w). The io
corpus oracle is back at its floor; the 34 GPU parity tests pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:15:36 -04:00
xsvm b077cc3a18 Extended filters: an unknown option is a bad-params error (#2228 follow-up) (#2548) 2026-10-10 13:15:30 -04:00
David MannandClaude Opus 5.5 c1eac9969b Render: Tree and Picture Frame accept whole numbers sent as floats (#2501) (#2521)
Filter > Render > Tree... and Picture Frame... failed from their dialogs
with "invalid type: floating point `1.0`, expected u32": the schema
dialog sends every range value as a JSON float, and TreeSpec/FrameSpec
deserialize baseTreeType, lightDirection, frame, lines and seed as u32
through serde. The render commands now round finite floats for those
integer fields (and Flame's seed) before deserializing, like the
engine's `int` helper does for other commands; negative or too-large
values are still refused as invalid parameters.

Tests: a render_cmds regression test (whole floats draw what integers
draw, fractions round, hostile values fail) and a filter_dialog sweep
that opens every schema dialog with its defaults and runs OK and the
preview, failing on any float type error. Only Tree and Picture Frame
failed it.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-10 13:15:24 -04:00
ericandhideoneric 5b051861bc fix(blend): keep 32-bit Hue/Saturation/Color/Luminosity above 1 (#1735)
- Hue, Saturation, Color and Luminosity no longer clip 32-bit documents to 0..1, so values above 1 survive in the CPU compositor (blend_rgb_hdr now uses blend_rgb_within at f32::MAX) and in the GPU shader (under the existing F_HDR flag). 8/16-bit results are unchanged apart from rounding at white.
- ClipColor returns the grey when the luminosity is outside the in-gamut range, instead of dividing by max − lum rounding noise. The old formula turned colours inside out (Luminosity of a grey of 2 over (0.5, 0.25, 0.125) gave (1.0, 2.32, 2.99)), and CPU and GPU disagreed (Hue over a grey of 2: CPU 1.0, GPU 2.82).
- Tests: 8/16-bit inputs match the ISO 32000 formula, HDR cases in compose, psblend::with_hdr nesting, and a CPU/GPU parity test across depths.

Co-authored-by: hideoneric <[email protected]>
2026-10-10 13:15:18 -04:00
B?! d1a062e044 AF.3: recognize current Affinity artboard properties (#2355) 2026-10-10 13:14:59 -04:00
Fabian GhenofandClaude Opus 5.5 141c80d3e8 Open file pickers for Replace Contents, Export Contents and Convert to Linked (#2438)
From the menu these Smart Object commands failed with "pass `path`": no file
dialog was wired to them. Replace Contents now asks for a file (by contents,
so it works on the web too) and updates every instance; Export Contents and
Convert to Linked ask where to save, suggesting the contents' own file name.

The engine gains replace_contents_bytes and contents_of for the UI to call.
Relink to File is left to #2416, which adds its picker.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:14:52 -04:00
Jason 3bc6860e72 Save and export dialogs remember where each document was last saved (#1826) (#2421)
`pick_save` now records the folder of every path the user chooses in a save
or export dialog, per document, and starts that document's next bare-name
dialog (exports, an untitled Save As) there. Precedence: a caller's explicit
directory, then the remembered folder, then beside the document (#1866),
then the shell's default. Save As of a saved document still suggests its own
path. The memory is session-only, keyed by DocId, pruned of closed documents
at the next dialog, and not fed by the web's download-name answers, which
carry no folder.
2026-10-10 13:14:46 -04:00
Harrison O'Connor-Hoover 7cd42907e5 Reject colliding data-set export filenames before writing (#2433) 2026-10-10 13:14:39 -04:00
2d6154a69b Keep Duotone ink colours when converting to RGB, CMYK or Lab (#2383) (#2614)
convert_document treated a Duotone document as plain gray: it converted
the stored gray pixels through the gray profile and dropped the inks, so
the result was neutral gray instead of the inked look the canvas shows.
Fill, text and effect colours stored in Duotone mode were not converted
at all.

Before converting to a colour space, a Duotone document is now inked
into sRGB (Duotone::render, the same model the display uses, with the
inks' sRGB colours), then converted through photocraft-cms to the
destination profile like any RGB document. Grayscale still keeps the
underlying gray. Works per layer at every depth; undo restores the
Duotone document.

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:13:52 -04:00
MrCloudy2andClaude Opus 5.5 76e3cbd010 TGA: a 32-bit Targa opens with its alpha as "Alpha 1", as in Photoshop (#2225) (#2482)
Opening a 32-bit Targa turned its alpha into layer transparency: the
colours of transparent pixels were hidden, and since #2157 only an alpha
channel becomes a Targa's alpha on save, a TGA opened and saved again
lost its alpha.

Measured on Photoshop 27.11 (scripted, files built byte by byte): a
32-bit Targa opens as an opaque Background plus an "Alpha 1" channel
holding the fourth byte, also when the descriptor declares 0 alpha bits;
the stored colours stay; a 24-bit Targa has no channel. PhotoCraft now
opens Targas the same way, so they round-trip with #2157's export.

Image sequences (video layers) still treat a TGA frame's alpha as
transparency, as footage does: load_frames moves the channel back.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:13:46 -04:00
F4LCONandBrandon Thomas ae03e7cd66 OpenEXR/HDR export: linearize grayscale documents too (#2386) (#2448)
* OpenEXR/HDR export: linearize grayscale documents too

Fixes #2386. The EXR/HDR branch of export_flat converted RGB images to
linear sRGB but left gray ones as stored, so an sGray #808080 was written
as 0.502 instead of 0.216. Gray images are now converted from their
profile (sGray when untagged) to linear gray. An untagged grayscale
OpenEXR opens tagged linear gray (an EXR Y channel is linear luminance),
and the open policy keeps that profile without a mismatch prompt, as it
already does for linear sRGB.

* contributors: add itsF4LCON

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 13:13:40 -04:00
f8efd089ad Keep the layered original when saving a flat copy (#2550, #2579) (#2611)
Save As to a flat format always made the written file the document's
file: a layered or PSD-backed document saved as JPEG was renamed to the
JPEG and marked saved, so Ctrl+S then opened Save As with JPEG chosen,
and closing no longer asked about the unsaved layers. app.save on the
desktop did the same for any format, unlike the headless server (#1547).

Save As now writes a copy when the flat file can't hold the document
(anything beyond one plain raster layer, or the document already lives in a layered
PSD/PSB/.pcraft/OpenRaster/TIFF file), as Photoshop does. A flat
document not in a layered file still becomes the flat file. app.save
only retargets for layered formats, through a helper shared with the
headless server (file_cmds::layered_extension).

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:12:41 -04:00
d4b9f06891 Quit and Close All: answering No closes that document (#2547) (#2610)
* Close each document as it is answered when closing several (#2547)

Quit, Close All and Close Others asked about each unsaved document but
only removed it from the prompt's list; nothing closed until every
document was answered. After "No" the answered tab stayed open (and
often active), so it looked like the same file was being asked about
again.

Now each answered document closes right away (after its save, for Yes)
and the next one asked about becomes the active tab, as Photoshop does.
The parked command still runs at the end: quitting is allowed and Close
All closes the clean rest even if its original target already closed.
Cancel stops there and keeps the unanswered documents open. Single-file
Close and Revert are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Show the first document asked about when closing several (#2547)

The first question of a Quit, Close All or Close Others prompt now
switches to the tab it asks about too, so every question shows its own
document. Before, the tab active when the command ran stayed up for the
first question, often a different file with the same name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Fabio Lussi <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:12:35 -04:00
MarekSpodBiedry 93629daedc Float the layer mask, not the layer, when the mask is targeted (#2468) (#2486) 2026-10-10 13:12:20 -04:00
Nigel Ihza Firdausy 24fbf4a84f fix(document): restore layer comps when duplicating documents (#2429)
* fix(document): keep layer comps valid across document duplication

Remap saved comp and Last Document State references when cloned layers receive new IDs, including historical states and nested groups. Drop obsolete comp metadata in merged-only copies instead of carrying references to removed layers.

Add focused engine regressions for #2382 and related copy workflows.

* style(test): apply rustfmt layout to layer-comp regression tests
2026-10-10 13:12:15 -04:00
MarekSpodBiedry 10571be5e2 Let Edit > Fill and the fill keys fill an adjustment layer's mask (#2456) (#2471) 2026-10-10 13:12:09 -04:00
Kaustubh TripathiandClaude Opus 5.5 099aa57db5 fix(vector): Fill Path stays inside the active selection (#2387) (#2410)
Fill Path painted the whole work path even when a selection excluded
part of it. The path's coverage (after anti-aliasing and feather) is now
multiplied by the selection mask, so rectangular, elliptical and
feathered selections all limit the fill. With no selection the whole
path fills, as before.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:12:04 -04:00
e667483820 fix(codecs): exports drop the source's EXIF thumbnail (#2147, #2373) (#2450)
Exports copied the source EXIF with only Orientation and resolution
patched, so a camera JPEG's embedded thumbnail (IFD1) came along. Finder,
Android and upload pickers show that thumbnail instead of decoding the
image, so an edited photo kept its original preview.

export_exif now clears IFD0's next-IFD pointer, unlinking IFD1. Nothing
else moves, so every other offset stays valid; JPEG, PNG, WebP and the PSD
EXIF resource all go through it.

Co-authored-by: vivekprojects-GIT <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:11:59 -04:00
Rene Leonhardt 5290930e4a fix: Preserve CMYK solid and gradient fills through PSD round trips (#2628)
* fix(compose): Preserve native CMYK fills through PSD round trips

Share depth-quantized ink samples between rendering and PSD caches.
Use the document profile for RGB fill colours and preserve valid imported
caches. Uncached CMYK fills use CPU rendering.

Cover all sample depths, gradient styles and tiled renders. Fix the real
16-bit gradient round trip and raise the psd-tools floor from 307 to 308.

* perf(raster): Reuse exact 8-bit CMYK conversions within rows

Cache the previous ink bytes and ICC result per row, with alpha decoded
independently. Keep the 16/32-bit conversion loops unchanged.

Matched 1 MP reads improve by 77% for smooth ramps, 33% with dithering
and 10% for random colours. Bitwise regression coverage includes all
depths, alpha and tile boundaries.
2026-10-10 13:11:54 -04:00
Kaustubh TripathiandClaude Opus 5.5 d9a9ce5f4d fix(vector): Stroke Path refuses pixel-locked and fully locked layers (#2388) (#2408)
Stroke Path only honoured the transparency lock, so Brush, Pencil and
Eraser painted on a layer whose pixels (or everything) were locked,
directly or through a parent group. It now rejects those destinations
with the same error as Fill Path and ordinary painting, leaving the
layer unchanged.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:11:51 -04:00
MarekSpodBiedry f96c0d1f13 Remove tool: an empty layer is a no-op instead of running the fill (#2435) (#2447)
* Remove tool: refuse an empty layer instead of running the fill (#2435)

* Remove tool: an empty layer is a no-op, as the other retouch tools (#2435)
2026-10-10 13:11:46 -04:00
8fd4aa4cc2 fix(psd): an unedited save writes Photoshop's Txt2 back unchanged (#2374) (#2427)
* fix(psd): an unedited save writes Photoshop's Txt2 back unchanged (#2374)

Since #1517 every PSD save with type layers rebuilt the document's Txt2
block: it replaced everything under /1 with the text-object list, emptied
objects no layer names, and cut each kept object's style runs down to the
auto-kern mode alone. Photoshop then refused to open an unedited re-save
("Could not complete your request because of a program error").

build_txt2 now starts from the file's own block: the other /1 keys and
unnamed objects are kept, a kept object's style runs keep every style key
and only get /11 set (split where a mode changes inside a run), and a block
whose content comes out unchanged is returned byte for byte.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(psd): Photoshop type files keep Txt2 byte-for-byte on an unedited save (#2374)

Corpus test over corpus/photoshop/text: import, export, re-import, and
compare the Txt2 global block. All 56 Photoshop-authored type files pass;
the previous build_txt2 fails on the first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: vivekprojects-GIT <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:11:42 -04:00
Kaustubh TripathiandClaude Opus 5.5 1a49942b63 fix(engine): list running jobs before ended ones in jobs.list (#2395) (#2411)
Session::jobs_with_recent is documented as "running jobs followed by the
last few that ended", but chained the ended jobs first, so jobs.list and
MCP jobs_list returned a finished job ahead of a running one. Running
jobs now come first, as documented.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:11:40 -04:00
MarekSpodBiedry 99570a7538 Layer commands accept an explicit layer with none selected; Deselect Layers is a no-op when nothing is selected (#2457) (#2481) 2026-10-10 13:11:35 -04:00
MarekSpodBiedry e80fe372b0 Keep surrounding spaces when renaming a layer (#2459) (#2472)
* Keep surrounding spaces when renaming a layer (#2459)

* rustfmt: keep rename_layer's name on one line (#2459)
2026-10-10 13:11:29 -04:00
MrCloudy2andClaude Opus 5.5 878c3eaf90 Select › Modify › Border: Photoshop's soft band, 2r wide, not a hard r-pixel ring (#2564)
Border built a hard band r pixels wide (expand r/2 minus contract r/2).
Photoshop's Border is soft and twice as wide: measured on Photoshop
27.11 (scripted), Border 4 on a 32 px square gives 63, 127, 191, 255 |
255, 191, 127, 63 across the edge, and the same along the inside of a
corner; PhotoCraft gave 0, 0, 255, 255 | 255, 255, 0, 0.

A pixel D away (centre to centre) from the nearest pixel on the other
side of the edge is now selected 1 - (D - 1) / r, using the existing
exact distance transform. That matches every sampled pixel within 1.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:09:21 -04:00
MrCloudy2andClaude Opus 5.5 96ee4f911b Select › Modify › Smooth: a hard threshold, as in Photoshop, not soft edges (#2557)
Smooth box-averaged the selection and then applied a contrast curve
((v - 1/2) * 4 + 1/2). That left a band of half-selected pixels along
every edge: a straight edge of a 32 px square came out 158 instead of
255 after Smooth 8, and a fill showed a soft grey border.

Measured on Photoshop 27.11 (scripted): Smooth 8 on the same square
gives only 0 and 255; straight edges stay exactly in place and the
corner is cut where the 17x17 box average crosses 1/2. Smooth now
thresholds the box average at 1/2, which reproduces every sampled
pixel.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:09:17 -04:00
MrCloudy2andClaude Opus 5.5 81ed59b0e0 Selection feather: the radius is the Gaussian's sigma, as in Photoshop (#2529)
Select › Modify › Feather (and the marquee, lasso and path feather
options) blurred with sigma = radius / 2, so a feather came out half as
wide as Photoshop's. Measured on Photoshop 27.11 (scripted): a 32×32
rectangle feathered 4 px matches sigma = radius within 2 levels along
the edge; sigma = radius / 2 was up to 71 levels off. The mask feather
(Properties › Feather) already uses sigma = feather, fitted on the
psd-tools corpus, so both feathers now agree.

The two margins sized for the old reach grow with it: Modify's
canvas-bounds padding (3 sigma = 3 r) and Fill Path's render area.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:09:13 -04:00
Harrison O'Connor-Hoover e11ffc0ae8 Preserve the Zoom drag anchor in rotated views (#2583) 2026-10-10 13:09:08 -04:00
Valentin KleinandClaude Opus 5.5 5bb768b8f1 Spot Healing: the drag trail shows the dabs the heal covers (#2364) (#2642)
The Spot Healing Brush's drag preview stamped a hard round footprint at the
base brush size, so a soft brush and pressure/shape dynamics did not show,
while the heal itself uses the brush engine's dab coverage. The trail now
renders the same coverage (`stroke_coverage`'s StrokeRenderer, brush built by
the new shared `retouch_cmds::stroke_brush`), including the press's lone
first dab via `tail_preview`.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:09:05 -04:00
Valentin KleinandClaude Opus 5.5 0426b1bb09 Canvas: right-click outside the image opens the pasteboard colour menu (#2462) (#2633)
Right-clicking the pasteboard (outside the document bounds) now opens
Photoshop's pasteboard menu: Default, Black, Dark Gray, Medium Gray,
Light Gray, Custom and Select Custom Color…. The rows set the existing
Preferences › Interface canvas colour through `prefs.set`; Select Custom
Color… opens the Color Picker and OK stores and uses the custom colour.

Painting tools keep their Brush Preset picker / right-button erase, the
Pen keeps its path menu, text editing and Free Transform keep theirs;
the Move tool falls back to the pasteboard menu where no layer is hit.
The control channel's `ui.pointer` secondary click opens it the same
way, `ui.context.choose` picks rows (authorised as `prefs.set`).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:09:01 -04:00
Valentin KleinandClaude Opus 5.5 28edd59339 Zoom tool: double-click zooms to 100% (#2508) (#2527)
* Zoom tool: double-click zooms to 100% (#2508)

Double-clicking the Zoom tool in the toolbar now selects it and runs
view.actualPixels, as in Photoshop, next to the existing Hand tool
double-click (fit on screen). With no document open it only picks the tool.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* contributors: add vangel76 (sync GitHub name)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:08:57 -04:00
Valentin KleinandClaude Opus 5.5 0c3c6cdd8d Tools: a tool key brings back its group's last-used tool (#2608) (#2625)
Pressing a tool shortcut from another group always picked the group's
first tool (L gave the Lasso even after the Polygonal Lasso was used).
The UI state now remembers the last tool used in each shortcut group,
and the key picks it, as in Photoshop. Applies to every group.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:08:53 -04:00
Valentin KleinandClaude Opus 5.5 fbb1316831 Move tool: Auto-Select picks a type layer inside its text bounds (#2370) (#2591)
layer.pickAt hit-tested every layer by the alpha of the pixel under the
pointer, so a click in the gap between a type layer's letters picked the
layer under it. Like Photoshop, Auto-Select (and Cmd-click) now hits a
type layer anywhere inside the bounds of its rendered text. The
right-click layer list still lists only layers with pixels there.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:08:49 -04:00
David MannandClaude Opus 5.5 e7576cd997 Move tool: Ctrl/Cmd+arrow nudges the layer from any tool (#2474) (#2556)
In Photoshop, holding Ctrl (Cmd on macOS) is the temporary Move tool for
most tools, so Ctrl/Cmd+arrow nudges the selected layer 1 px, with Shift
10 px, and with Alt duplicates first. PhotoCraft only nudged with the Move
tool itself, and egui's consume_key never ignores an extra Ctrl/Cmd, so
Ctrl/Cmd+arrow did nothing anywhere.

- hold_keys::cmd_nudges: Ctrl/Cmd+arrow nudges wherever Ctrl/Cmd is the
  temporary Move tool, with the Move tool, and with the selection tools
  (moves the selected pixels). Not during Free Transform, text editing, or
  an in-progress polygon or Magnetic Lasso border.
- move_mods::arrow_keys adds Command to its patterns in that case.
- nudge decides on floating the selected pixels as the Move tool.
- Direct Selection keeps Ctrl/Cmd for itself, like Path Selection.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-10 13:08:45 -04:00
Valentin KleinandClaude Opus 5.5 87068253c6 Move tool: outline follows the moved layer (#2413) (#2565)
View > Show > Layer Edges was painted before the frame's tool events
were read, from the session document. Two bugs came from that:

- The frame in which Auto-Select picks a layer on the press still
  outlined the previously selected layer, because the pick ran after
  the outline had been drawn.
- During a live Move drag the moving pixels come from the preview
  document at the drag offset, but the outline used the committed,
  unmoved bounds. It stayed where the layer started until the release,
  so it trailed behind and was visibly off on fast drags.

The canvas now reserves the outline's z-slot where it was drawn and
fills it after the tool events, so it outlines the newly picked layer.
The rect is offset by move_ui::shown_offset, which is the offset the
image was drawn with this frame. That keeps the outline in lockstep
with the pixels. The moving set (the move targets plus their
descendants) is computed once per preview revision, so there is no
per-frame scan.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:08:40 -04:00
Valentin KleinandClaude Opus 5.5 4d7e5c1ef0 Marquee: keep one-pixel rows and columns on release (#2391) (#2562)
The live preview (ants and W/H readout) showed the whole-pixel rectangle
from marquee_px, but finish_gesture deselected any rectangle narrower or
shorter than 2 px. That threshold stood in for "was this a click?" because
floor/ceil turns a click between pixel edges into a 1x1 rectangle, so a
deliberate one-pixel column or row, and a thin drag replacing an existing
selection, ended with no selection at all.

Release now commits exactly marquee_preview_px, which decides a click by
screen distance (shape_dialog::is_click at the view zoom) and drops only
zero-area rectangles; the preview draws no ants when the release would
deselect. A plain click still deselects, as in Photoshop.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:08:36 -04:00
Harrison O'Connor-Hoover ac90ca2b1a Capture marquee selection modifiers at mouse press (#2558) 2026-10-10 13:08:31 -04:00
Harrison O'Connor-Hoover f55bc2d697 Fix snapping when drawing a new crop inside the default frame (#2549) 2026-10-10 13:08:27 -04:00
Nigel Ihza Firdausy 13d89378d8 fix(properties): expose equal-gap layer distribution (#2349) (#2398) 2026-10-10 13:08:22 -04:00
41d54036fc fix(selection): constrain Polygonal Lasso segments with Shift (#2352) (#2396)
* fix(selection): constrain Polygonal Lasso segments with Shift (#2352)

* Polygonal Lasso: make the Shift constraint helper visible to its tests; cargo fmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 13:08:18 -04:00
MarekSpodBiedry 8c2e16fb4a GPU canvas: re-upload a layer or mask texture when its default pixel changes (#2422) (#2446) 2026-10-10 13:08:14 -04:00
MarekSpodBiedry 0158fa82e1 Clip warp tiles at the inverse horizon so steep Distort commits keep every pixel (#2271) (#2500) 2026-10-10 13:08:10 -04:00
Max Murphy 8587c55c78 Free Transform: the Hand tool no longer steals a resize drag (#2302) (#2327)
* Free Transform: the Hand tool no longer steals a resize drag (#2302)

* Free Transform + Hand: only the selected Hand yields, and only in the primary canvas (#2302)

* cargo fmt
2026-10-10 13:08:06 -04:00
Max Murphy 3e000bc1d5 Canvas: UI Scale must not magnify the image (#2121) (#2333)
Interface > UI Scale is egui's zoom_factor, folded into pixels_per_point
with the display scale. The canvas divides View::zoom by the full
pixels_per_point (PhotocraftApp::point_zoom) and the GPU shader
multiplies it back, so 100% is one document pixel per physical display
pixel at every UI scale -- fixed by #1978 (Canvas: zoom is physical at
any display scale), which the report predates (v0.5.0). No behaviour
change; the report is stale.

Lock it down with a rendered-output regression test
(tests/ui_scale_canvas.rs): a black document is drawn through the real
app on the GPU and CPU canvas at UI Scale 100/125/150/200% and zoom
100/200%, and its on-screen size is measured in the pixels. It stays
60x60/120x120 physical px at every UI scale, and fails when the canvas
stops using point_zoom (75x75 at 125%) or when the GPU shader stops
multiplying by pixels_per_point (48x48 at 125%). The comments on
View::zoom, PhotocraftApp::ppp and canvas_view now name UI Scale too.
2026-10-10 12:22:49 -04:00
Brandon ThomasandClaude Opus 5.5 2b79c7c25d automation: test that root look-alike siblings and sub/../.. climbs are refused (#2216 follow-up) (#2528)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 11:53:35 -04:00
7722172585 Add OpenRaster (.ora) import and export (#2257)
Open and save .ora with pixel layers (any offset), nested groups, pass-through
groups, names, visibility, opacity, edit/alpha locks and blend modes (svg:* plus
Krita's krita:* names), at 8 and 16 bit. Save applies pixel masks, renders
text/shape/fill/smart layers to pixels and reports what OpenRaster can't hold.
Wired into File > Open/Save, the CLI, automation/MCP, the web picker and the
desktop file associations. Checked against 34 Krita 5.2.9-authored files
(opt-in krita_corpus test) and Krita re-opening our exports.

Co-authored-by: Scott Campbell <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 08:40:35 -04:00
texjerandBrandon Thomas 05e0b1f8a5 kys import: first launch asks before importing; edit.keyboardShortcuts importKys (#1987 review) (#2251)
- The live set found beside Photoshop is offered, never applied unasked: an
  "Import keyboard shortcuts?" prompt names the set and how many keys it
  changes, with Import / Don't Import. Either answer is recorded in
  dialogs.photoshopShortcuts, so it is asked once; ui.inspect shows the
  pending offer as kysOffer.
- Parsing and label matching moved to the engine (photocraft_engine::kys), so
  edit.keyboardShortcuts {"importKys": <xml>} imports a set from agents, the
  CLI and MCP; the app's dialog uses the same plan with its menus' labels.
- "The keyboard shortcut set was not imported: {error}" is translated.
- .kys input over 4 MiB is refused before it is read as text.

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 07:12:24 -04:00
4e8aaec643 Addition : Brush popup better UI (#2217)
* Brush name/tip/stroke cards

+ locale

* brush popup scale ui

scale brushes

* align fix + tests

* test fix

* ci fix

* ci fix 2

* don't scale text

* smaller width for tip+name

* scale + spacing + better UX

* Regenerate docs/scorecard.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: JJ <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 07:04:52 -04:00
AyanandBrandon Thomas d99562f038 Compute exact octagonal mask shifts with bounded workspace (#2154)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 06:46:06 -04:00
ae96037672 Expose native shape stroke controls with staged previews (#2218)
* Expose native shape stroke controls with staged previews

* Document shape stroke defaults in MCP control schema

* Regenerate docs/scorecard.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: optimalbytee <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 06:42:52 -04:00
291f30da55 EXR: Cryptomatte layers list, decode and hash to the specification (#2180)
* EXR: Cryptomatte layers list, decode and hash to the specification

Cryptomatte (specification 1.2) carries per-pixel object and material
IDs with coverage in <layer>NN.red/.green channel pairs, announced by
cryptomatte/<key>/name|hash|conversion|manifest header attributes - the
ID channels Arnold, V-Ray, Redshift, Mantra/Karma and Cycles write next
to the beauty pass.

cryptomatte_layers lists every layer from the headers alone (name, key,
channels, the embedded manifest parsed and capped at 16 MiB, a sidecar
pointer); decode_cryptomatte returns the per-pixel (ID, coverage) pairs
above zero, sorted by descending coverage; cryptomatte_id hashes names
the reference way (MurmurHash3 x86-32, the exponent fixed away from
denormals/inf/NaN, read as f32 bits) - verified against the official
test vectors - and cryptomatte_key/cryptomatte_preview_color expose the
metadata key and preview colour. Files with deep parts are refused, like
the other flat part decoders.

* chore(ui): format prefs_ui (the workspace fmt gate is red on main until #2417 lands)

* codecs: Cryptomatte decode checks the layer size without truncating casts

Count each pixel's pair list in the allocation check too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 06:40:49 -04:00
Sir StarchandBrandon Thomas a737281fad Distance fields on threads: bevel size changes 2-3x cheaper (#2119) (#2162)
* Distance fields: the Euclidean passes run on threads, results unchanged (#2119)

The chiselled bevel fields (#2006) and the precise glow fields are built
from an exact Euclidean distance transform, a few sweeps over the whole
map that all ran on one thread. They now run on scoped OS threads, in
groups of rows or columns handed out from a queue: edt_nearest (the
column pass, then the row pass), sharp_edges (rows), refine_edge_normals
(one edge pixel each) and the final per-pixel maps of the bevel and plain
Euclidean fields. Not rayon, as for the blurs (rows_par): maps are built
from inside rayon tiles, where a waiting worker steals other tiles (#276).
Maps under 65536 pixels stay on the calling thread, wasm always does.

Every unit is computed from its own inputs, in the same arithmetic as
before, so the fields are bit for bit the old ones whatever the thread
count: 216 fingerprints (bevel in and out, plain in and out, bevel_maps on
bars at 0 to 150 degrees, thin bars, discs, rounded rectangles, soft,
patchy and half-opaque masks, 40 stars, tiny and 1 pixel maps) are equal
at 1, 7, 16 and the default threads, and equal to the code before.
edt_nearest returns the nearest pixel as u32 (it was usize), which takes its
working memory from 20 to 16 bytes per pixel; a map past 2^32 pixels or a slice that does
not match its size gets "far" distances instead of a panic.

CPU compositor, 12 MP, bevel size change (ms, bevel_bench), main -> this:
ellipse 474 -> 217 (size 8), 990 -> 318 (250); text 747 -> 214 (8),
1110 -> 267 (250). A distance_field call on a 256x256 map goes from 2.2 to
1.8 ms, on 512x512 from 8.0 to 2.8, on 2048x2048 from 99 to 15.

Tests: par_units hands every unit to the closure once with its own
slices (short last unit, no second slice, units of different sizes, 1 to
64 threads); the nearest-pixel transform equals itself on 1, 2, 3 and 8
threads on awkward sizes and returns a seed at the distance it reports;
degenerate sizes; sharp edges and the four Euclidean fields are bit-equal
on 1, 2, 5 and 16 threads on discs, rounded rectangles, bars at several
angles, patchy opacity and an edge on the border. The nested-rayon
deadlock test (#276) now has a chiselled bevel layer in its document.

* GPU effect maps: the Euclidean fields are one window, not bands (#2119)

A bevel size change rebuilds the distance fields over the whole effect
region (the region grows with the size). The GPU path cut that into bands
of max(128, halo) rows, each computed from a window grown by the halo,
which for the bevel fields is reach + 10: at size 250, 262-row bands from
windows of about 786 rows. Every pixel went through the transform and the
edge refinement about three times, a 12 MP region gave about 12 tasks for
32 threads, and the two bevel fields ran one after the other.

The Euclidean fields (chiselled bevels, precise glows) now come from one
window, and distance_field spreads its own passes over the threads. A
rebuild is the whole region, which is also what the CPU compositor
computes, so the GPU canvas gets exactly the CPU's field: bands resolved
ties between equidistant edge pixels per window, and on a rebuild they
differed from the whole region by up to 0.07 px (ellipse) and 1.3 px (600
discs) at size 250, on a few dozen pixels in 12 MP. A partial update (a
brush dab) still computes the damage grown by the halo, from one window.
The chamfer fields (shadows, strokes, spread) are a sequential sweep and
keep the bands, and so does wasm, where there are no threads to spread
over and bands keep the memory small.

RTX 4080 SUPER, release, 12 MP, ms per size change on the GPU canvas
(bevel_bench from #2118, p50, median of 3 runs, before #2006 / main /
this), ellipse: 90 / 103 / 98 (8), 162 / 188 / 119 (50), 286 / 446 / 219
(250); text: 83 / 139 / 113, 140 / 215 / 130, 222 / 489 / 165. Alone in the
process (--no-cpu) ellipse at 250 is 407 -> 157 and text 468 -> 169.
36 MP ellipse at 250: 779 -> 382. Peak RSS: 12 MP at 250 1604 -> 862 MiB,
36 MP at 250 2987 -> 1726 MiB; at size 8 on 36 MP it is 163 MiB more
(1380 -> 1543). Precise glow fields on 12 MP: 46-84 ms -> 26 ms at reach
52-252 (32 ms at 12).

The window test now checks that the whole region is bit for bit the CPU's
field, and that a too small halo is noticed on a part of the region.

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 06:38:33 -04:00
Harrison O'Connor-Hoover ec03c602b4 Apply Type formatting to selected text layers (#2266)
* Apply Type formatting to selected text layers

* Name the multi-layer formatting test case type
2026-10-10 06:09:54 -04:00
401abc48a9 Content-Aware tools: Photoshop's behaviour, measured (#2202)
* Content-Aware tools: Photoshop's behaviour, measured

Photoshop 25.4 was measured as a black box (synthetic and public-domain
images, results read back exactly) and the content-aware family follows it:

- Fill (inpaint): coarse to fine with the coarser level's matches scaled up
  and voted with the finer level's own pixels, the coarsest level filled
  from the hole's edge inwards, a shallower pyramid. The fill is pieces of
  the image copied pixel for pixel with narrow seams, as Photoshop's;
  before, it was visibly blurred. Pixels have roles (hole, context,
  source, void), so excluded areas stay context instead of being filled.
- Colour adaptation: Image Melding's per-patch gain and bias, limited per
  level, instead of a low-frequency membrane pull.
- Sampling window: Photoshop's square of side 4·√(max(w,50)·max(h,50))
  centred on the selection, slid inside the canvas; Edit › Fill,
  Rectangular, Auto, Delete and Fill and Spot Healing use it.
- Auto sampling area: what looks like the selection's surroundings (local
  colour and contrast, one min cut), fitted to Photoshop's overlay.
- Patch Tool: a Content-Aware mode (Structure, Color, Sample All Layers).
- Content-Aware Move: Structure 3..7 alike, a band about a patch wide;
  Color as a gain/bias limited to about 0.04 per step.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Remove tool: keep its own sampling margin (fill_cmds::sampling_margin is gone)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 06:08:47 -04:00
Harrison O'Connor-Hoover e7df11d770 Load Thai fallback fonts for native UI text (#2280) 2026-10-10 06:06:39 -04:00
37985c0c61 Filters: preview at the scale OK applies (#2063) (#2207)
The filter dialog previewed large documents on a 1/k proxy and divided
pixel-sized params by k. Filters whose features have a fixed size in
pixels (Ripple, Diffuse, Oil Paint, Flame, Fibers, Mezzotint) came out
k times larger in the preview than in the result, and params divided
below their minimum were clamped (Pointillize 5 px cells -> 12 px).

filter_dialog::preview_factor picks the proxy factor per command: 1 for
the fixed-size filters, otherwise the largest factor up to k at which no
pixel-sized param falls below its range minimum.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 06:05:15 -04:00
Books 7198a94164 automation: accept absolute paths beneath the automation roots (#2176) (#2216)
doc_open, doc_save and the other automation file paths only took
forward-slash relative paths, so an agent passing C:/Users/me/a.png with
a C:/ root was refused. An absolute path is now compared with the
root's absolute path as text: if it lies beneath the root, the root's
components are stripped and the rest goes through the same checks as a
relative path and is opened through the same directory capability.
Nothing is resolved on the filesystem, so traversal, prefixes, device
names and link escapes are refused as before; absolute paths outside
the root, or with no root granted, are still refused.

Fixes #2176.
2026-10-10 05:53:23 -04:00
Sean LaveryandBrandon Thomas 478acf70cc Expand arithmetic expressions across numeric inputs (#2252)
* Expand arithmetic expressions across numeric inputs

* Test arithmetic and scientific notation in indexed color counts

* Drop the numeric_fields example (it wrote PNGs to /tmp; the widget tests cover the behaviour)

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 05:50:58 -04:00
kubuntugamerandBrandon Thomas 4c06b9fe4d fix(engine): adjustments on a smart object record smart filters (FILE-215-4); strokes honour doc CMYK (#2229)
On a smart-object layer, Image > Adjustments now records an editable
smart filter instead of committing disaster.

  - new engine helpers:
    - adjust_cmds::has_adjustable / adjust_as_smart_filter route
      image.adjustments.<kind> onto the source, with the selection as the
      filter mask, through smart_cmds::add_smart_filter
    - brush/eraser/pencil/live preview strokes now render inside
      with_cmyk_space(doc_cmyk_space(session)), so painted colours follow the
      document profile the same way the compositor does
  - docs/scorecard.md: FILE-215-4 partial -> done
  - tests: adjust_cmds/tests + brush_cmds/tests, plus panic_hunt and
    the lib suite all green on the committed tree

Known follow-up, already filed:
  - FILE-215-5 rows: double-clicking an adjustment smart-filter row is still
    a no-op. smart_ui::open_editor only proceeds when
    filter_dialog::has_dialog returns true, and has_dialog accepts
    filter.*, a fixed non-adjustment set and PREVIEWED - but not
    image.adjustments.* (those open through adjust_dialog::open, which isn't
    wired into the smart-filter row).

This is one commit on top of the latest upstream/main (rebased to fix the
stale fork ancestry that was blocking PR creation).

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 05:49:07 -04:00
Brandon ThomasandClaude Opus 5.5 29d5f791d5 Regenerate docs/scorecard.md (TOOL-213-19 from #2193) (#2404)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 05:20:57 -04:00
JohnnYoruandBrandon Thomas 897f9f37ad Add the Remove tool with non-local patch completion (#2193)
* Add the Remove tool with non-local patch completion

Tool::Remove (J flyout) paints a hole that paint.remove fills from its
surroundings as a background job, in one undo step. A stroke around an
object also removes what it encloses; the selection limits the hole.

The fill (photocraft_algo::nonlocal) follows Newson, Almansa, Gousseau and
Pérez (IPOL 2017): texture features in the patch distance, onion-peel
initialisation, match fields upsampled between levels and a best-patch
final copy, plus gradient-domain hiding of edge and interior seams.
Sparse holes are filled in tiles. inpaint::complete (Content-Aware Fill,
Spot Healing, Content-Aware Move) is unchanged.

On 20 holes in public-domain photos (remove_quality) the fill keeps 0.89
of the texture it replaces, against 0.54 with the Wexler/PatchMatch
completion. 24 MP (remove_bench): 100 px ring 120 ms, 1000 px ring 2.5 s.

* Translate the Remove tool's label and tighten comments

Adds "Remove Tool" to every UI catalog, following each one's pattern for
tool names and its existing word for Remove. Corrects comments that no
longer matched the code: the benchmark's description, the tile and margin
minimums, and the reasons given for two parameters.

* Put the Remove tool first in the J group

The J flyout's slot now shows Remove until another J tool is picked, and
J from another group selects it; repeated J goes on to Spot Healing Brush,
Healing Brush, Patch, Content-Aware Move and Red Eye.

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 05:19:11 -04:00
414b7b9e4b fix(ui): complete system appearance selection and styling (#2168)
* feat(ui): follow system appearance with a System theme

Follow the OS appearance through the existing egui input while retaining System as the saved theme choice. Apply the resolved palette to both egui styles and custom surfaces, and keep document surround settings independent.

Cover launch and live transitions, persistence, manual themes, menu checks, the Interface picker and Home contrast. Validate engine/UI suites, adversarial commands, wasm, layering, parity and the AutoReview gate. Strict Clippy reports pre-existing findings documented in the PR.

Refs: storytold/photocraft#2074

* Keep the document surround on the displayed theme in Sync with system (drop the dark-surround pinning)

---------

Co-authored-by: coygeek <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 05:14:41 -04:00
Harrison O'Connor-HooverandBrandon Thomas 607a8542f5 Keep duplicated Smart Objects linked to shared contents (#2222)
* Keep duplicated Smart Objects linked to shared contents

* Share Smart Object source update code

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 05:05:56 -04:00
Jason XiangandBrandon Thomas e05deac124 fix(engine): reject invalid core-filter parameters (#2228)
* fix(engine): reject invalid core-filter parameters

* test: cover filter validation through CLI and automation

* fix(ui): preserve filter preview minima during downsampling

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 04:57:56 -04:00
b203e7c295 Window edges: easier to grab, theme-safe cursors, and no lost hover after a resize (#1581) (#2205)
With the custom title bar the app draws its own resize zones. On Linux
they were hard to use:

- Edges asked for `ew-resize` / `ns-resize`, which some cursor themes
  (capitaine-cursors) don't ship: X11 fell back to the core font's big
  arrow and KDE Wayland showed the plain arrow, so the edge was hard to
  find. Edges now use the one-sided cursors (`w-resize`, ...), as GTK
  and KDE window borders do; corners keep the diagonal ones, which those
  themes draw in the same style.
- The edge zone grows from 5 to 8 pt (about a native resize border).
- KDE Wayland keeps the button release of an OS resize, so egui kept the
  edge pressed: hover stopped until the next click, and egui-winit never
  re-sent the resize cursor the compositor had replaced. The cursor came
  back only on every other press. After the hand-off the press is now
  ended in raw_input_hook, and the first motion afterwards shows the
  default cursor for one frame so the resize cursor is sent again.

Tested live on KDE Plasma (Wayland and XWayland).

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 04:54:10 -04:00
Sir StarchandBrandon Thomas 7b3ded0f8b Layers menu and layer commands follow the selection, not the active layer (#2244) (#2254)
* Layer › Rasterize acts on every selected layer; the Layers menu offers Rasterize Layers (#2243)

Rasterize › Layer / Type / Shape / Fill Content / Smart Object took only the active
layer, so right-clicking inside a multi-layer selection converted one layer. Without a
`layer` param they now rasterize every selected layer they apply to, in one history step.
An explicit `layer` (the "Rasterize?" paint prompt, scripts) still targets exactly one.

Layers panel: a multi-layer selection gets one "Rasterize Layers" item (greyed only when
nothing selected can be rasterized, judged by the whole selection, not the clicked layer).
Edit Contents and Convert to Layers act on one layer, so they are not offered there.
Adobe's documentation: select "the layer or layers you'd like to rasterize".

Tests: engine integration (mixed type/shape/fill/smart selection, one undo step, per-kind
commands, explicit layer, nothing to rasterize, bad targets) and ui-egui (menu entries,
enablement, right-click → Rasterize Layers end to end). The new behaviour tests fail on
the old code.

* Layers menu and layer commands follow the selection, not the active layer (#2244)

Availability of Rasterize, Create/Release Clipping Mask, Add Layer Mask and Paste/Clear Layer
Style was decided by the active layer, so one selection was greyed or not depending on which of
its layers happened to be active (with the Background active, Create Clipping Mask and Add Layer
Mask were greyed although they would have run on the other layers), and Rasterize Layer was
enabled for layers it then refused ("nothing to rasterize"). Several of these commands also only
ever acted on the active layer, whichever layer the menu was opened on.

- Add Layer Mask (Reveal/Hide All, Reveal/Hide Selection), Paste Layer Style and Clear Layer Style
  run on every selected layer that can take them (not the Background, layers that already have a
  mask, layers without a style), in one history step. An explicit `layer`, or a single selected
  layer, behaves as before.
- `enable_rules::selection_targets`: availability of those commands, Create/Release Clipping Mask
  and Rasterize is judged by the selection.
- Rasterize Layer is enabled only for type, shape, fill and Smart Object layers, which is what the
  command converts.
- Items with no single target stay greyed for several layers: Blending Options, Copy Layer Style,
  Quick Export, Export As and the per-layer mask items. A multi-layer menu has one stable mask item.

Tests: engine integration (mask, paste and clear on a selection, errors, unchanged single-layer
paths) and a property test over 20 selections x clipboard state x 7 commands: an enabled item runs,
and for several layers a greyed one would have changed nothing. It fails on the old rules for
["R1", "BG"] with the Background active, the case from the bug report.

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 04:18:42 -04:00
dd2ce3da33 GPU startup: CPU mode on Linux falls back to Vulkan to present the window (#1337) (#2206)
CPU rendering mode limited the window's wgpu instance to GL on Linux.
With NVIDIA's EGL the GL adapter can't present to the window (wgpu:
"EGL says it can present to the window but not natively") and llvmpipe
isn't offered, so the adapter selector found nothing and every start
exited with "no graphics adapter found", on X11 and Wayland alike. The
user couldn't reach Preferences to undo it.

CPU mode now creates the instance with GL and Vulkan. GL adapters still
rank first (llvmpipe, then hardware GL), so nothing changes where GL can
present; Vulkan is used only to draw the window when no GL adapter can.
Image compositing stays on the CPU.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 04:12:17 -04:00
TropicalandBrandon Thomas d4ec2db0a7 feat(ui): allow toolbar to scroll (#2238)
* feat: allow toolbar to scroll

* fix: assign the toolbar ScrollArea "toolbar-columns"

* chore: remove unused slots variable

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 04:04:26 -04:00
8d23c62272 Pen pressure curve: Preferences › Tools shapes how pen pressure reaches every brush (#2195)
* Pen pressure curve: Preferences › Tools shapes how pen pressure reaches every brush

Brush phase 6a (TOOL-213-11, #610). Every pen paints its pressure straight through, so artists
with a heavy or a light hand, or a tablet whose response feels off, had no way to adjust it.

- `tools.pressureCurve`: [input, output] points, linear by default, settable with `prefs.set`
  (validated: 2..=16 pairs within 0..1).
- `prefs::PressureCurve` reads it as a monotone cubic (Fritsch–Carlson), so a firmer press never
  gives less pressure. It sanitises the points itself (finite, clamped, sorted, one per input,
  capped, outputs made non-decreasing; flat beyond the ends), because a whole-section update or a
  hand-edited file can store anything.
- The stylus maps every pen sample's pressure through it before any brush sees it, so the live
  stroke, the commit and the journal agree. A mouse stays at full pressure.
- Preferences › Tools draws a curve editor under Use Tablet Pressure: drag a point, click to add
  one, right-click to remove one, with Linear, Soft and Hard presets. Translated in all 16 catalogs.

* Regenerate docs/scorecard.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 04:00:10 -04:00
265f10b91d Fix SVG selection and import detection (#2224)
* Fix SVG import detection and configurable group depth

* Fix malformed SVG error routing and formatting

* Refresh scorecard for SVG depth preference

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 03:58:08 -04:00
Sir StarchandBrandon Thomas 1b6150e3fc Layer › Rasterize acts on every selected layer; the Layers menu offers Rasterize Layers (#2243) (#2253)
Rasterize › Layer / Type / Shape / Fill Content / Smart Object took only the active
layer, so right-clicking inside a multi-layer selection converted one layer. Without a
`layer` param they now rasterize every selected layer they apply to, in one history step.
An explicit `layer` (the "Rasterize?" paint prompt, scripts) still targets exactly one.

Layers panel: a multi-layer selection gets one "Rasterize Layers" item (greyed only when
nothing selected can be rasterized, judged by the whole selection, not the clicked layer).
Edit Contents and Convert to Layers act on one layer, so they are not offered there.
Adobe's documentation: select "the layer or layers you'd like to rasterize".

Tests: engine integration (mixed type/shape/fill/smart selection, one undo step, per-kind
commands, explicit layer, nothing to rasterize, bad targets) and ui-egui (menu entries,
enablement, right-click → Rasterize Layers end to end). The new behaviour tests fail on
the old code.

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 03:55:43 -04:00
TropicalandBrandon Thomas 071fe4590b fix(ui): mode buttons respect two-column toolbar (#2241)
* fix: mode buttons respect two-column toolbar

* fix: draw menu indicator on window mode button

* fix: syntax mistake in `paint_toolbar_menu_indicator`

* fix: pass tokens to paint_toolbar_menu_indicator

* refactor: rename paint_toolbar_menu_indicator to paint_toolbar_flyout_indicator

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 03:49:22 -04:00
Brandon ThomasandClaude Opus 5.5 fc42f81f42 Web: leave the JPEG XL DNG decoder out of the wasm (25.1 MB -> 24.3 MB) (#2233)
* Web: leave the JPEG XL DNG decoder out of the wasm (0.88 MB, 23.1 MiB now)

The 0.6.0 web build went over packaging/web/package.sh's 24 MiB gate (26,980,503 bytes on
782bcb67). Today's landings added 1.34 MB; the biggest single item was jxl-oxide (#2047, JPEG
XL-compressed DNG): ~0.6 MB of jxl_* code plus brotli-decompressor and tables, 0.88 MB after
wasm-opt. 0c72d954 brought the wasm back to 25,144,413 bytes (21 KB under the gate) by deflating
catalogs and fonts; this takes it to 24,262,088 bytes (23.14 MiB, 904 KB of headroom).

jxl-oxide is now a native-only dependency of photocraft-raw. On wasm32 a JPEG XL DNG segment
returns RawError::Unsupported ("can't be opened in the browser version of PhotoCraft; open it
in the desktop app"), like the other cfg-gated web features; every other DNG compression and
raw format still opens in the browser. Native builds are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* xtask i18n-coverage: read the deflated catalog! registry entries

0c72d954 changed the LANGUAGES registry from include_str!("xx.tsv") to catalog!("xx"), so
`cargo xtask i18n-coverage` failed with "language `ja` has no include_str! catalog". Parse the
new form (the macro argument is the catalog's file stem).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 03:40:35 -04:00
Nigel Ihza FirdausyandBrandon Thomas 91a2b58725 fix(ui): remove the gap beneath Spectrum document tabs (#2265)
* fix(ui): remove Spectrum document tab-to-canvas spacing (#2188)

* scrollbars test: compare the centred view within float error

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 03:40:16 -04:00
6a39da98c8 Move tool on a locked layer: Photoshop's message (#2249)
* Move tool on a locked layer: Photoshop's message

Dragging with the Move tool (or Cmd with another tool) on a layer it can't
move showed nothing: the Background or a position-locked layer with no
selection, or a locked layer whose selected pixels can't float. Photoshop
puts up "Could not use the move tool because the layer is locked." when
the drag starts (a plain click says nothing); move_lock.rs does the same
with the Error dialog, translated in every catalogue. The float lock rule
moves to float_cmds::locked_for_float so the UI can ask before the press
goes anywhere.

Also in Dutch and Ukrainian. The Cmd-with-a-painting-tool case lands with
the Cmd-as-Move change, whichever merges second.

* Fix merge: close the lock-message test

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 03:39:40 -04:00
Sir Starch 1f84f19caf Hand tool: an open hand and a fist as the pointer on Windows, and the fist while panning everywhere (#2196) (#2221)
* Hand tool: an open hand and a fist as the pointer on Windows, and the fist while panning everywhere (#2196)

Windows: winit maps CursorIcon::Grab and Grabbing to the four-arrow move cursor, so the Hand
tool never showed a hand. tool_cursor::hand now hands the OS an outlined bitmap hand (open) and
fist (dragging), drawn from signed distance fields like the brush tips, through the same
set_cursor_image path. macOS and the Linux themes keep their own grab cursors.

All platforms: the tool-cursor block of canvas_view is inside `else if primary`, which the Hand's
own drag branch skips, so Grabbing was dead code and the pointer was a plain arrow while panning
(Hand tool, Space and the middle button). The drag branch now sets the fist.

Also used by the Hand pointer under a dialog and the Camera Raw preview's pan.

* tool_cursor tests: the Hand's pointer on Windows is now a bitmap (#2196)

brush_hover_uses_an_os_bitmap_that_survives_motion_but_not_tool_or_panel_changes pinned the old
behaviour (no bitmap, CursorIcon::Grab once the Hand is selected), which is the four-arrow move
cursor on Windows. It now expects the open hand's bitmap.
2026-10-10 03:15:00 -04:00
texjerandBrandon Thomas b37bff987c Cmd held is the Move tool with the painting tools (Cmd+Alt duplicates) (#2248)
Photoshop switches to the Move tool while Cmd (Ctrl off the Mac) is held
with every tool but the Hand, Rotate View, Zoom, Crop, Slice, Path Selection,
shape, Pen and Type tools. #896 did this for the selection tools per press; this
does it for the rest (Brush, Eraser, Gradient, Clone Stamp, Eyedropper, ...).

hold_keys gains Temporary::Move (a modifier, not a rebindable key); the
canvas sets PhotocraftApp::tool_override for the frame and the tool state
machine, the Move tool's selection check (move_ui::moves_selected_pixels)
and the tool modules that gate on the tool read active_tool(). The held-tool
latch now lasts through the release frame, otherwise the Move's Up went to
the selected tool. So Cmd-drag with the Brush moves the layer, Cmd+Alt-drag
duplicates it first (move_mods), Cmd-drag with a selection floats the
selected pixels, and Cmd-click picks the layer under the pointer.

Off the Mac, Cmd+Alt is Ctrl+Alt, which the brush tools keep for the
on-canvas resize (brush_resize, also Alt+right-drag there): with a brush
tool Ctrl+Alt-drag resizes, with the other tools (Gradient, Eyedropper...) it
duplicates. Tests pin both layouts on any host. docs/control-protocol.md
describes `command` on ui.pointer events.

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 02:44:27 -04:00
Harrison O'Connor-Hoover 935c94b5d3 Add pixel mask density and feather controls to Properties (#2240) 2026-10-10 02:43:34 -04:00
Krzysztof CieślikandBrandon Thomas a0c18f5f75 Tools: double-clicking a layer mask launches Select and Mask with preference (#204) (#2161)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 02:35:51 -04:00
texjer 95006995f6 Selection cursors: Photoshop's badges for cutting, copying and dragging the selected pixels (#2250)
Over a selection the cursor now says what a press does, as in Photoshop:
the move cursor where a marquee press moves the outline (#1428, unchanged),
the arrow with scissors where Cmd (or the Move tool) cuts and moves the
selected pixels, the arrow with a second arrow where Alt lifts a copy, a
hollow arrowhead while they are dragged, and a plain arrow over the floating
piece. canvas::selection_cursor decides, drawn as icon badges beside the OS
arrow (icons::cursor_badge), white with a dark outline.
2026-10-10 02:24:22 -04:00
Harrison O'Connor-HooverandBrandon Thomas 97f37feaec Default layered flat-image saves to PSD (#2234)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 02:23:57 -04:00
eb20f83654 Masks: target a new layer mask and keep separate colour pairs for mask and pixels (#2166) (#2200)
* Masks: target a new layer mask and keep separate colour pairs for mask and pixels (#2166)

Photoshop keeps one foreground/background pair for layer masks and one for
layer pixels and swaps them when the edit target changes; adding a mask
targets it, with white/black. PhotoCraft never touched the colours when a
mask was targeted, and adding a mask left the pixels targeted.

- engine: ToolState::target_mask swaps in the other target's pair
  (mask pair starts at white/black, colours picked on either side are kept).
- ui-egui: sync_mask_targets applies the effective target (mask targeted,
  active layer has a mask, composite channel, no Quick Mask) after every
  command, every frame and every control request; the Layer Mask add
  commands target the new mask.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Fix merge: close mask colour-pair test before the deletion tests

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 02:20:48 -04:00
Nigel Ihza Firdausyandtiya nur alfiyanti 1e7c38b98f Expose Clone Stamp opacity and flow and apply them to strokes (#2256)
Co-authored-by: tiya nur alfiyanti <[email protected]>
2026-10-10 02:20:27 -04:00
Krzysztof CieślikandBrandon Thomas b4044a5c0c Workspace: wire open_documents_as_tabs preference (#204) (#2177)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 02:18:05 -04:00
Harrison O'Connor-Hoover 2db1b26d9d Preserve quoted multiline variable CSV records (#2242) 2026-10-10 02:17:09 -04:00
26d40dbd0f TGA: save the document's alpha channel as 32-bit alpha (#2124) (#2157)
Flat exports ignored the document's alpha channels, so a Targa saved
from a document with an "Alpha 1" channel had no alpha. Photoshop 25.1
(checked via scripting) writes a 32-bit Targa's alpha from the
document's alpha channel when there is exactly one (spot channels
skipped), composites layer transparency over white, writes an opaque
alpha when there are several channels, and never adds alpha to
grayscale Targas. TGA export now does the same; 16-bit documents are
written as 8-bit Targa with the channel's values.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 02:11:44 -04:00
Tanish Manku f2836b0475 Soft brushes paint soft strokes and thin lines stay even: a Gaussian-like tip and area coverage for tiny tips (#2167)
Brush phase 1 (owner-approved option A of the brush audit):

- Soft tips fall off as (1 - t²)⁴ from the hard core to the edge, a Gaussian-like curve that
  tracks exp(-4.6 t²) but is exact on every platform and reaches 0 at the edge with a flat tangent.
  The old smoothstep kept so much of the tip near full strength that overlapping dabs (Flow builds
  up, as in Photoshop) turned a soft stroke's edge to half the tip's width. It now keeps about two
  thirds of it, at the default 10 % spacing, with no ripple along the stroke.
- Computed tips under 3 px radius are rasterised by covered area (a 4×4 grid per pixel, each
  sample anti-aliased over its quarter pixel) instead of at pixel centres: a 1 px dab's total
  coverage no longer swings 1.00–1.17 with its sub-pixel position, so thin lines don't bead.
- The default spacing stays 10 %. Photoshop's documented 25 % beads soft strokes with either
  curve; it waits for Photoshop-authored reference strokes.
2026-10-10 02:10:39 -04:00
26cc6ed6bc Confirm layer deletion only from the Layers trash button (#2197)
* fix(ui): confirm deletion only from the Layers trash button

* Trash confirmation: Alt-click deletes without asking (Photoshop); drop docs page and screenshot

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: kotulsky <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 02:10:24 -04:00
2c15f13f02 scorecard: Marquee modifiers and brush resize drag are done (TOOL-214-2, TOOL-213-10) (#2261)
* scorecard: Marquee Shift, Alt and size readout are done (TOOL-214-2)

The row still said canvas.rs passes false for Shift (#208), but #208 is
fixed: marquee_corners applies Shift (square or circle) and Alt (from the
centre), the W x H readout follows the drag, and marquee_tests.rs covers
all three.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* scorecard: on-canvas brush resize drag is done (TOOL-213-10)

The row said only [ ] resize the brush, but brush_resize.rs (#297, #370)
implements Photoshop's drag: Alt+right-drag, or Control+Option-drag on
macOS, sets diameter and hardness with a circle and readout, and is
covered by nine tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 02:04:18 -04:00
LuniiyaandBrandon Thomas 9c79871c6b Preferences: the dialog grows with the window (#2155)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 02:03:37 -04:00
8b1bb0fd05 fix(engine): select neighbouring layer after deletion (#2189)
Co-authored-by: kotulsky <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 02:01:55 -04:00
8a80430c40 Layers panel: press-drag-release picks a fill or adjustment layer (#2071) (#2172)
Photoshop's "Create new fill or adjustment layer" footer button opens its
menu on the mouse press, so one gesture can press it, drag onto an item and
release to choose it. PhotoCraft used egui's Popup::menu, which only opens on
the release (click), so choosing needed two clicks.

A small reusable press_menu helper (the menu bar's press-drag gesture from
#669/#775, for a single popup button) now drives the adjustment button and the
identical fx (layer style) footer button: the press opens the menu, the release
that ends the opening click keeps it open, releasing on an item chooses it, a
release on nothing chooses nothing, and a secondary click still opens it. The
gesture belongs to the popup whose button started it, so several press menus in
one frame don't end each other's gestures. The items dispatch the same
commands as before.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 01:57:43 -04:00
TropicalandBrandon Thomas 4aa511bb05 fix(ui): avoid drawing panel borders twice (#2226)
* fix: don't draw panel borders twice

* fix: avoid drawing caption buttons over titlebar border

* fix: remove manually painted separator on statusbar

* titlebar test: caption buttons stop above the panel's separator line

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 01:57:01 -04:00
44636cb6f2 Canvas: clip the Free Transform preview to the canvas (#2027) (#2201)
The transform overlay drew the moving pixels as a textured mesh with the
canvas painter, whose clip is the whole viewport, so a box moved or
scaled past the canvas edge showed its pixels over the pasteboard.
Photoshop never shows pixels outside the canvas; only the box and its
handles reach over the pasteboard.

Build the preview mesh (Free Transform/perspective grid and Warp) in
document space and clip each triangle to [0, 0, width, height] before
mapping it to the screen. Clipping in document space stays exact under a
rotated or flipped view; a mesh fully on the canvas is drawn unchanged.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 01:51:47 -04:00
Harrison O'Connor-Hoover 34382a65ca Ignore hidden RGB when Magic Wand selects transparency (#2273) 2026-10-10 01:51:28 -04:00
bf1036a273 Layers panel: Opacity and Fill share one right-aligned column (#2085) (#2173)
In the pro theme the Fill row zeroed the horizontal item spacing for the
lock icons on the whole row, so the "Fill:" label touched its field while
"Opacity:" kept the normal gap and sat 8 pt further left. Scope the zero
spacing to the lock icons only, so both labels end the same gap before
fields that share one right edge, as in Photoshop. The narrow-panel check
that drops the "Lock:" text now counts the restored gap.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 01:51:26 -04:00
kmnkv1andBrandon Thomas effee8cdc3 i18n(ru): translate layer style effects (#2210)
Stroke was Мазок; effect names were untranslated. Names follow Photoshop's Russian UI.

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 01:43:46 -04:00
kmnkv1andBrandon Thomas f10c83425c fix(layer style): wrap Make/Reset Default buttons (#2209)
Translated labels (ru) are wider than the page column and overlapped the effect list.

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 01:43:42 -04:00
39c97c9be0 Keep the selection when smart selection finds nothing (#2235)
* Keep the selection when smart selection finds nothing

Select Subject and Object Selection run heuristics that often miss on busy
photos. In Replace mode an empty result cleared the selection, so the Select
Subject button looked dead and even destroyed existing work. apply() now
preserves the selection and reports changed:false in every mode.

The UI also answers visibly instead of staying silent: empty smart-selection
results set an info status suggesting what to try next, and a click with
Object Selection falls back to a Quick Selection dab at the brush size
instead of doing nothing.

* Translate the smart-selection status messages; drop needless borrows (clippy)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 01:42:28 -04:00
5e481cde02 Layers: mask thumbnails update after Invert and other whole-mask edits (#2117) (#2164)
Thumbnail and bounds caches key on surface_fingerprint, which hashed only
tile coordinates and Arc pointers. A fresh Reveal All mask has no tiles;
Image > Adjustments > Invert (and other whole-mask edits) only flips its
default pixel, so the fingerprint stayed the same and the Layers panel kept
the stale white thumbnail. The fingerprint now includes the default pixel.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 01:27:41 -04:00
Michał Kosior 183122f676 Fix hyperlink in credits panel to use crate::links::open instead of the unreliable ui.hyperlink_to (#2146) 2026-10-10 01:26:48 -04:00
a9267e199d Fix layer mask toggle action labels (#2156)
Co-authored-by: optimalbytee <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 01:13:06 -04:00
David MannandClaude Opus 5.5 9482e0c710 Smudge: use the Brush Settings spacing for retouch strokes (#2140) (#2171)
parse_brush, shared by Smudge, Blur, Sharpen, Dodge, Burn, Sponge, the
clone/healing tools and the History Brush, defaulted `spacing` to a fixed
25% instead of the session brush's spacing (Brush Settings > Brush Tip
Shape > Spacing). The UI never sends `spacing` for these tools, so the
Brush Settings value was ignored. Default to the session brush spacing,
as Photoshop does; an explicit `spacing` param still wins.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-10 01:10:12 -04:00
BenzizaandBrandon Thomas 634cfbf3c5 Preserve unchanged XMP translations in File Info (#2152)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-10 01:08:52 -04:00
Coy Geek f4bc463ee8 docs(adjust): correct Levels and Curves composition order (#2212)
Describe per-channel records before the master to match the compositor fixed in #1929. Clarify the CMYK black channel and the ignored Lab master.

Closes #975.
2026-10-10 00:59:39 -04:00
SawizzleandClaude Opus 5.5 6973fe4496 docs: register the MCP server from an installed release (#2185)
* docs: register the MCP server from an installed release

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: drop the third-party link; the Windows path is the default install folder

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 00:59:34 -04:00
Brandon ThomasandClaude Opus 5.5 0c72d95425 Web: store translation catalogs and bundled fonts deflated, unpacked on first use (wasm back under the 24 MiB gate)
The 0.6.0 web build was 26.9 MB, over packaging/web/package.sh's 24 MiB gate (Cloudflare's per-file
cap is 25 MiB, #198). The i18n .tsv catalogs (1.85 MB -> 0.64 MB) and the Inter/JetBrains Mono fonts
(1.52 MB -> 0.73 MB) are now deflated by build.rs and inflated on first use, so wasm is 25,141,080
bytes. No visible change. A catalog that fails to inflate falls back to English, a font that fails
falls back to egui's default font; neither panics. Headroom is only ~25 KB: the next size cut is
needed soon (fetching catalogs on demand would save another ~0.64 MB).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 22:11:13 -04:00
Shayan HorbankandBrandon Thomas e398cc80b8 Use shared Color Picker for Layer Style and text styles (#2015) (#2049)
* Use shared Color Picker for Layer Style colors (#2015)

* Use shared Color Picker for text style colors (#2015)

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 22:03:51 -04:00
texjerandBrandon Thomas a81eaa4187 Keyboard Shortcuts: import Photoshop .kys sets; first launch takes Photoshop's live set (#1163) (#1987)
* Edit › Keyboard Shortcuts: Import Photoshop Shortcuts… loads a .kys set (#1163)

Photoshop saves a shortcut set as .kys XML: <command name="Gaussian Blur...">
rows with one or more <shortcut>Control+Opt+Cmd+G</shortcut>, then the tool
keys. The dialog's new button (and File › Open or a drop of a .kys) parses it
with roxmltree, matches each row to our commands by menu label, and fills the
dialog's overrides, so OK applies the set the way hand-made changes are
(a key moved to a command is taken from its old owner) and Cancel discards it.

Rules, from Photoshop's own ambiguities: a label in several menus (Levels…
under Image › Adjustments and Layer › New Adjustment Layer; All under
Select, Edit › Purge and View › Show) goes to the command whose default is one
of the row's keys, else the one with a default, else the first in menu order.
A row's first key is kept unless one of its keys is already the command's
default (Zoom In is Cmd++ then Cmd+=). Scripts, Bridge, the frames commands
and the macOS application menu have no command here and are counted in the
message. Tool keys are not imported: the tool letters are fixed.

* First launch beside Photoshop imports its live shortcut set; the Open dialog lists .kys

Photoshop keeps the set in use as Keyboard Shortcuts.psp in its per-version
settings folder (macOS ~/Library/Preferences/Adobe Photoshop <v> Settings,
Windows %APPDATA%\Adobe\Adobe Photoshop <v>\Adobe Photoshop <v> Settings),
the same XML a saved .kys holds. The desktop app hands the newest version's
file to the UI (Services::photoshop_shortcuts); at the first launch that has
no shortcut overrides yet, kys_import::auto_import applies it through the
Keyboard Shortcuts dialog's own OK path and posts a notice naming the set and
the count. The preference dialogs.photoshopShortcuts records the source, so
the import happens once; someone who already changed a shortcut keeps theirs.
Reset All to Defaults undoes it.

The Open dialog's filter now lists .kys (it greyed them out), and dropping
Keyboard Shortcuts.psp imports it like a .kys.

* kys import: Ukrainian and Dutch strings; tests follow Cmd+K and Cmd+F as the defaults (#1900)

* kys import: user-facing strings name no other product (#1985)

The button is Import Shortcuts…, its tip names the .kys format, the notice
says "Keyboard shortcuts imported" and names the set, and a file that is not
a set is "not a keyboard shortcut set (.kys)". A set without a name is called
by its file name. Comments, identifiers and the XML root tag keep the format's
own name.

* rustfmt: format panels.rs and prefs_ui.rs

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 21:55:43 -04:00
5ed094a940 ui: Panels::rail and Panels::menu_bar let an embedding app hide the icon rail and the menu bar (#1960)
The right dock's icon rail and the title bar with the in-window menus were
always drawn. An app that embeds PhotoCraft's UI and offers a simpler view, or
draws its own bar, could hide every other panel through `ui.panels` but not
these two.

Two Panels flags, both on by default and with `#[serde(default = "yes")]`, so
saved settings and the current UI are unchanged. `ui.set` accepts them like
the other panel flags. The title bar's caption buttons, where PhotoCraft draws
its own, go with it.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 21:47:12 -04:00
16ad6e1079 Add font previews and keyboard cycling to font menus (#1746)
Co-authored-by: highperfocused <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 21:43:59 -04:00
Max MurphyandBrandon Thomas 995c895c33 Notices: auto-hide after a delay, with Interface preferences (#2022) (#2100)
* Notices: auto-hide after a delay, with Interface preferences (#2022)

Non-blocking notices no longer stay on screen until closed: each card
hides itself after Interface › Notification › Auto Hide Notifications'
delay (new, default 6 s), and the timer pauses while the pointer rests
on the stack until it moves away. Two new Interface preferences,
notificationAutoHide and notificationDurationSeconds, are read by
notices.rs; errors still land in the status bar.

The decision lives in the pure notices::expire helper, unit-tested
without an egui clock; Notice.shown_at round-trips through the control
channel with serde defaults. Labels translated across the complete
catalogues. Regenerated docs/scorecard.md.

* Notices: repaint on expiry, and a fresh delay when a long hover ends (#2022)

Addresses review of the auto-hide change:

- When the last notice expires, `show` had already painted it and, with
  nothing left, requested no further frame, so the card lingered until
  unrelated input. It now requests a repaint in the frame that drops
  anything, clearing the stack at once.
- A stationary hover over a settled UI refreshed `shown_at` only on
  frames, so hovering longer than the delay then leaving expired the
  notice instantly. `show` now tracks the pointer leaving the stack and
  restarts the timers on that frame, so hovering never counts as elapsed
  time.

Regression tests: expiring a notice requests a frame to clear it;
leaving a long hover gives a fresh delay.

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 21:38:03 -04:00
LuniiyaandBrandon Thomas 8c3b6f8e5f Appearance modes: sync with system, separate dark and light themes (#1981)
* Appearance modes: sync with system, separate dark and light themes

* Appearance button cycles Auto, Light, Dark

* Appearance: default stays Dark, follow the portal signal instead of polling, split out the Preferences resize

* Preferences: size both appearance cards for the five dark themes

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 21:34:49 -04:00
LuniiyaandBrandon Thomas 782bcb67fa Toolbar: Studio themes draw round colour chips with Switch Colors below (#2002)
* Toolbar: Studio themes draw large round colour chips with Switch Colors right below

* Toolbar: round chips keep Default Colors, follow Tokens::round_chips, lie side by side in two columns

* Theme: Solarized Dark and Adwaita use the Studio round colour chips

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 21:14:37 -04:00
cc584d9aff Add Adwaita and Adwaita Dark themes (+ brush chip fix on light themes) (#1823)
* Brush preset chip: draw the tip preview in the icon colour on light themes

The options-bar chip always painted the round tip white, which nearly vanished on Studio
Light's chrome (246 gray) and disappears entirely on a white header bar. Dark themes keep
Photoshop's white tip; light themes use their icon token.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add Adwaita and Adwaita Dark themes

Two opt-in themes that put the Studio layout in GNOME's libadwaita palette, so PhotoCraft
sits with the rest of a GNOME desktop: header bar, sidebar, card and view colours, the
GNOME blue accent (#3584e4), destructive and warning colours, 6 / 9 / 12 px radii, and a
neutral (not red) close button as in GNOME's title bars. The default theme is unchanged.

Wired through ThemeKind, the interface.theme preference (adwaita, adwaitaDark), Window ›
Theme and the control channel, with menu and preference labels in every complete-menus
language ("Adwaita" kept as the proper name). A test holds both themes to WCAG contrast:
7:1 for text and 4.5:1 for dim text on every surface that carries labels.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n: translate the Adwaita theme names in Dutch and Ukrainian

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 21:08:12 -04:00
SilentYetiandClaude Opus 5.5 db0fb07862 Add native layered Paint.NET (.pdn) import (#1998)
Squashed onto main, with the maintainer's asks applied:
- Photoshop's blend menus (layers, brush, pencil, gradient, layer style) stay as they are;
  the Layers panel and Blending Options list a Paint.NET mode only for a layer that uses one.
- The six Paint.NET mode labels are translated in every catalog, and the blend-mode i18n test
  iterates layer_modes().
- pdn::pixels rejects truncated uncompressed (version 1) data before allocating its buffer.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 21:05:00 -04:00
Brandon ThomasandClaude Opus 5.5 d3fa5e4c6f Bump version to 0.6.0 (from 0.5.0) for release; refresh contributors
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 21:02:23 -04:00
Max MurphyandBrandon Thomas 9c427a7a2c Themes: add Solarized Dark (#1136) (#2098)
* Themes: add Solarized Dark (#1136)

* Solarized Dark: ship the palette's MIT license notice (#1136)

---------

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 20:34:31 -04:00
Brandon ThomasandClaude Opus 5.5 69b1379781 prefs_ui: declare recovery_tests after the production code (fixes prefs_usage on main) (#2194)
#2115 put `#[cfg(test)] mod recovery_tests;` at the top of prefs_ui.rs, and the
prefs_usage test reads each file only up to its first test module, so every preference
read in prefs_ui.rs looked unread.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 20:16:52 -04:00
23fbfb9b3c Layers: delete targeted masks and edit Solid Color by thumbnail (#1997)
* Fix mask trash targeting and Solid Color Fill editing

* Fix Solid Color picker mode conversion and validate RGB ranges

* Apply rustfmt to Solid Color regression tests

* Fix Solid Color mode regression test using distinct RGB values

---------

Co-authored-by: abc2cb <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 20:15:29 -04:00
ZamandClaude Opus 5.5 6884809d02 Gradient Editor window: the Gradient tool's swatch opens a customizable gradient editor (#1983)
Rebased onto main as one commit (the PR's net diff); the preset-drop mapping now uses
ViewXform::active, which accounts for the display's pixels per point.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 20:05:26 -04:00
d502c5de27 ci(web): validate browser builds and wasm size on pull requests (#1689)
* ci(web): build browser release and enforce wasm gate on PRs

* docs(web): describe PR browser build and size checks

* CI web gate: run only when web-relevant files change (main always)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 20:05:15 -04:00
Ahmed Moussa 1cfc56db56 fix(Text): served fonts become script fallbacks on the web (#2109)
A host's font manifest can now list the scripts each font covers (`scripts` field). The first served family for a script the bundled fonts lack (Arabic, Hebrew, Devanagari, Thai, Japanese, Chinese, Korean) becomes that script's fallback. When a layout contains text in that script, it requests the family. The font database adds the family to the fallback stack once it arrives, and type layers drawn before then are re-rendered.

The web shell also fetches the fallbacks for the browser's languages (`navigator.languages`) at startup, so an Arabic reader gets the Arabic font before typing anything.

The manifest's SHA-256 is now turned into a Subresource Integrity value (`sha256-<base64>`) and passed with the font fetch, so the browser rejects any file whose bytes don't match.

Also adds a contributor entry for hamada147 to `contributors/people.toml`.

Signed-off-by: Ahmed Moussa <[email protected]>
2026-10-09 20:04:04 -04:00
1330899aca fix(web): persist imported brush libraries in IndexedDB (#479) (#2054)
* Persist browser brush presets through IndexedDB

* fix(web): clear resolved preset staging rejections

* web: translate the brush preset storage messages

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: zenjabba <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 19:58:25 -04:00
35f832f03a Brush panel: update-current-brush button, identity-based preset selection, tip-grid fixes (#2007)
* update brush button

* ui brush duplicated highlight fix

* formatting fix + locale

* i18n: translate "Update the current brush with these settings" in remaining complete catalogs

* Tip Shape picks the tip only; set_brush records the preset once accepted

- A click in the Brush Tip Shape grid copies the tip fields only (main's
  Photoshop behaviour: the dynamics sections stay); the picked preset is
  marked current with brush.presets.setCurrent instead of a whole-preset
  tools.setBrush, so identity-based selection still tracks it.
- tools.setBrush sets current_preset only after the brush merged and
  validated, so a failed call leaves no state behind; a reset still wins
  over a preset in the same call. Tested.
- brush.presets.save / brush.defineFromSelection append at the end again
  (insert-after-the-copied-brush had no Photoshop reference).

* Brush presets: forget the picked preset when the tool's brush swaps; no indexing in brush.presets.update

Each painting tool keeps its own brush (#218), so Update Brush could overwrite the
preset picked with one tool with another tool's brush.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: JJ <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 19:56:41 -04:00
Tanish Manku 917fbcb006 Pen pressure follows every sample: moves in one frame no longer share the frame's last pressure (#2112)
Brush phase 3b. The stylus feed was one latest-value slot, so every pointer move in a frame
painted with the frame's last pressure, tilt and rotation: fast pen strokes got stair-stepped line
weights (#2046, #2036, #1776, #610).

- `StylusFeed` keeps the latest sample (for proximity, the eraser end and tilt) and also queues
  every sample in order (bounded to 1024). `set()` is unchanged, so the macOS, X11 and web
  sources, and a WinTab source later, need no changes.
- Each frame takes its pen samples in order: the feed's queue, then the touch forces (Windows).
  Pointer move k of n takes the pressure, tilt and rotation interpolated at its share of the
  frame, from the previous frame's last sample. Rotation takes the short way round. A mouse
  still paints at 1.
- A new stroke starts from this frame's samples, never from a sample an earlier stroke left behind.
- The stylus updates once per egui frame: the canvas runs once per view, and egui can run a
  frame in several passes, so a second update drained an empty queue.
2026-10-09 16:55:18 -07:00
Harrison O'Connor-Hoover 269d8fedc7 Keep startup responsive while recovering autosaved documents (#2115) 2026-10-09 19:50:53 -04:00
David MannandClaude Opus 5.5 03bb64a681 Brushes: keep the folder hierarchy of imported .abr files (#1851) (#2001)
* Brushes: keep the folder hierarchy of imported .abr files (#1851)

Photoshop CC brush files keep their Brushes panel folders in a `phry`
(preset hierarchy) section; the importer skipped it, so every preset of an
.abr landed in one flat group named after the file.

- photocraft-psd: `abr::parse` reads `phry` (a token stream of `Grup`
  {Nm, zuid}, `preset` and `groupEnd` objects) into `AbrFile::folders`, one
  folder path per preset. A damaged hierarchy never fails the parse: a stray
  groupEnd, more or fewer preset tokens than presets, folders nested deeper
  than MAX_FOLDER_DEPTH (32) or an unreadable section become warnings and the
  affected presets land at the top level. `write_v6_folders` writes `phry`
  back (`write_v6` is unchanged).
- photocraft-paint: `BrushPreset::folder`, the nested folder path inside its
  group (serde default, so older JSON loads unchanged).
- photocraft-io: the file's folders nest inside the group named after the
  file, as Photoshop's Import Brushes does.
- Preset store: each stored preset records its `folder`; group files written
  before this change load with every preset directly in its group (no
  rewrite). Paths from disk and from imported .pcpresets files are bounded.
- Commands: brush.presets.move, moveGroup, renameGroup and deleteGroup take
  an optional `folder` path to move a preset into a folder, or to move a
  folder among its siblings, rename or delete it. importAbr reports the
  number of folders kept.
- Brushes panel and Brush Preset picker: nested folders are drawn indented
  under their group (list and grid), open and close like groups, take
  dropped presets, reorder among their siblings by drag and drop, and have
  Rename/Delete in their context menu.

Checked against the 4-folder ABR Photoshop 25.1 exports of its default
brushes (8/6/6/8 presets): all 28 land in their folders, and a write/parse
round trip keeps them.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Brushes: bound phry folder allocation; reword the move folder param

Review on #2001:
- read_phry now runs after every section is read, so it builds folder
  paths only for the presets in desc (a phry may precede desc), and the
  paths it holds are capped at 16 MB; presets past the cap import at the
  top level with a warning.
- brush.presets.move documents `folder` as folder names, so the
  automation filesystem-path classifier no longer flags it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 19:46:07 -04:00
Brennan StehlingandClaude Opus 5.5 85572c61c3 Save in the background so large saves don't freeze the window (#2017) (#2072)
* Save in the background so large saves don't freeze the window (#2017)

File › Save and Save As encoded and wrote the whole document on the UI thread,
so a multi-GB layered TIFF or PSB save left the window unresponsive for the
whole write, with no progress.

Saves now run as a background job: a new `Services::save_file` encodes and
writes atomically on a worker (the desktop app provides it), the document is
locked meanwhile, and the existing progress dialog shows the stage with Cancel.
Cancelling while encoding leaves the file untouched. The save is recorded when
the job ends, the unsaved-changes prompt waits for it, and a window close
during a save is held until it ends. Without the service (web, tests) saves
stay synchronous.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Background save: a save can't be cancelled once writing starts (#2072 review)

- `Services::save_file` now gets a `SaveCtl` and calls `commit()` right before
  replacing the file. Cancel and Esc are refused after that, so a "Cancelled"
  save can no longer replace the file while the document shows unsaved.
- A save's worker stays counted (`saving()`) until it returns, even when its job
  was cancelled: quitting waits for it, and another save to the same file is
  refused until it is gone.
- A failed or cancelled save no longer closes a window whose close was held.
- The pending reply carries the job id, and the job becomes `last_started`, so
  control and MCP clients can wait for the save.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 19:39:55 -04:00
Sir StarchandBrandon Thomas 819bd47bf1 perf: bevel_bench, the cost of changing a chisel bevel's size (#2006 follow-up) (#2118)
#2006 made a bevel size change dearer on purpose (+10-75% on the GPU canvas,
2x for CPU text bevels) and asked for a bench of it under perf/.

`bevel_bench` renders a 12 MP document with one Chisel Hard inner bevel on
an anti-aliased ellipse (a smooth outline) or on a text paragraph (many thin
edges). Each case warms the caches one pixel below the size, then times
refreshes with the size growing by one pixel each, so the GPU canvas
rebuilds its distance fields every time (it keeps them while the size
shrinks) and the CPU compositor misses its map cache. Sizes 8, 50 and 250,
GPU and CPU, with `--scene`, `--size`, `--reps`, `--no-cpu` and `--json`.

Registered in perf/budgets.toml as P52-P59 with no budgets (track only,
like P45 and P46): GPU for ellipse and text at 8, 50 and 250, CPU at 8.
docs/scorecard.md is regenerated; the rows read "not run" until the next
baseline.

RTX 4080 SUPER, release, 9 reps, p50 ms, before #2006 (3bc49f5e) -> after:
ellipse GPU 88 -> 105 (8), 169 -> 199 (50), 305 -> 460 (250); text GPU
119 -> 140, 141 -> 252, 238 -> 557; CPU text at 8 402 -> 797. Runs vary by
about 20% on this machine.

Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 19:39:45 -04:00
AyanandBrandon Thomas e93b30e60d Proximity Match: 1.5-3.8x faster stroke searches, smaller mask tables (#2101)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 19:34:26 -04:00
AyanandBrandon Thomas 3953d78378 Selection distance transforms: 7.6-10.6x faster and correct past 4K (#2093)
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 19:28:33 -04:00
590c1496b4 Affinity import: special shapes and sample corpus (#1606) (#2035)
* Import Affinity issue 1606 special shapes

* Affinity corpus: give the #1606 sample ceilings a margin for font differences between machines

The samples' labels render with whatever fonts are installed, so the measured
differences move by up to 0.8 between machines; each ceiling is now the higher
measurement plus about 1. Also use as_chunks in on_white (clippy with --features corpus).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 19:27:35 -04:00
0e011a69dc feat(canvas): Caps Lock forces the precise crosshair for painting tools (#1758) (#2111)
* feat(canvas): Caps Lock forces the precise crosshair for painting tools (#1758)

* Caps Lock poll: back off for 5 s after an X error instead of reconnecting and warning every frame

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 19:25:36 -04:00
5630e112b4 Layer style colours keep the document's mode (Gray, CMYK) (#2103)
In a Grayscale or CMYK document, effect colours (overlays, shadows, glows,
strokes, satin, bevel, gradient stops) were stored as RGB and drawn
unconverted: a red Color Overlay in a Gray document was red. Effect::in_mode
converts them where effects are written: the effect commands, the Layer
Style dialog (replace), Paste Layer Style and style presets.

Co-authored-by: Claude <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 19:20:10 -04:00
510636f461 DNG: JPEG XL compression 52546 (DNG 1.7, Samsung Expert RAW) (#2047)
* DNG: JPEG XL compression 52546 (DNG 1.7, Samsung Expert RAW)

Decode JPEG XL-compressed DNG strips and tiles with jxl-oxide (pinned
=0.12.6), with geometry and channel checks, Limits/AllocTracker budgets
and catch_unwind around the decoder. Warn when a DNG carries a
ProfileGainTableMap (tag 52525), which is not applied yet.

Tests encode fixtures in-process with zune-jpegxl (dev-dependency only).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* raw README: list Deflate DNG beside JPEG XL after rebasing onto #1971

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 19:17:46 -04:00
David MannandClaude Opus 5.5 c161a7a5c9 Shape tools: a click opens Create Rectangle / Create Ellipse (#1175) (#2031)
In Photoshop a single click (no drag) with a shape tool opens a creation
dialog to type the exact size. PhotoCraft ignored the click: the drag
geometry was below 1 px, so finish_shape returned without doing anything.

- New shape_dialog module: Create Rectangle (width, height, four corner
  radii with a link toggle, From Center), Create Ellipse, Create Triangle
  and Create Polygon (sides, star ratio). Width and height show in the
  ruler unit and are stored in document pixels; values are remembered per
  tool. OK runs the existing shape.create command at the clicked point
  (or centred on it) with the options bar's fill and stroke; invalid
  sizes/positions are rejected with an error, never a panic.
- canvas::finish_gesture opens the dialog when the gesture never left
  the press point by more than 3 screen px; drags draw exactly as before.
  Line and Custom Shape keep ignoring clicks.
- vector_ui::create_shape shares the fill/stroke params with the drag path.
- Catalog entries for the new labels and titles in every complete language.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 19:14:31 -04:00
72d78f3067 Patterns paint in the document's colour mode (Gray, CMYK) (#1950)
An RGB pattern (every built-in one) showed in colour as a pattern fill or
Pattern Overlay in a Grayscale or CMYK document, unlike Edit > Fill, the
export, and Photoshop, which fills in grey but keeps the pattern's colours
(a Grayscale round trip brings them back).

pattern::pattern_rgba projects a pattern's pixels through the document's
mode when painted; the CPU prepared tiles and the GPU pattern textures use
it. Patterns themselves are unchanged.

Co-authored-by: Claude <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-09 19:12:45 -04:00
David MannandClaude Opus 5.5 c7287703a3 Crop tool: Show Cropped Area (H) and Crop Shield colour/opacity options (#1919) (#2128)
The Crop options bar gets Photoshop's gear menu (Set additional Crop options): Show Cropped Area
(H toggles it while the Crop tool shows a box; off hides everything outside the box behind the
canvas colour) and Enable Crop Shield with Color (Match Canvas, the pasteboard colour, or Custom…,
which opens the Color Picker), Opacity (default 75 %) and Auto Adjust Opacity (half the opacity
while the box is dragged). The shield used to be a fixed black at about 51 %. The options persist in
ToolOptions.crop_shield (older settings get Photoshop's defaults; a stray opacity is clamped) and
ui.set takes cropShield. Classic Mode and Auto Center Preview are left out: PhotoCraft always crops
in Classic Mode.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 19:10:06 -04:00
David MannandClaude Opus 5.5 35010f5138 Crop tool: Straighten button and ⌘/Ctrl-drag level the frame (#1919) (#2127)
The Crop options bar gets Photoshop's Straighten button (one-shot), and holding ⌘/Ctrl with the
Crop tool is a temporary Straighten. The drawn line (with an angle readout) turns the frame so the
line ends up level, or plumb when it is nearer vertical (the Ruler's straighten_angle convention),
and fits the frame to the largest of its proportions inside the image (Classic Mode). It is a
pending frame edit: Enter commits, Esc cancels. New logic lives in crop_straighten.rs.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 18:56:11 -04:00
Ian Swope 2caa58884c Free Transform: the preview follows edits made while the box is open (#1384) (#2099)
Changing the moving layer's opacity, fill or visibility in the Layers panel
during Free Transform was applied and kept on commit, but the preview showed
the session's starting state until then: the moving pixels kept their first
opacity and the document under them was the copy taken when the box opened.

follow_edits rebuilds that copy from the current document whenever its
revision changes (keeping the lifted pixels out) and takes the tint from the
layer's opacity x fill, or 0 when hidden. canvas::display_doc calls it before
reading the preview, so the canvas never caches a new revision with the old
preview. Lone mask/channel transforms and Transform Selection are unchanged.

Blend modes are still not shown on the moving pixels (an egui mesh blends
normally); that needs the compositor and is left for discussion in #1384.
2026-10-09 18:51:55 -04:00
f9ea13a857 EXR: multi-part files open the colour part; exr_info lists them all (#2116)
* EXR: multi-part files open the colour part; exr_info lists them all

A Maya/Arnold render writes one part per AOV. The decoder took part 0
silently, so a depth-only part failed the whole file with "no R/G/B or
Y channels". Now the part that looks most like a colour image opens
(RGBA > RGB > YA > a single channel, earliest wins), with a
DecodeWarning::MoreParts naming how many parts exist.

exr_info lists every part (name, view, size, channels, deep/tiled) from
the headers alone, and decode_exr_part decodes a chosen part — F16 parts
stay F16. Deep parts stay with the deep decoder: a file that has any is
refused here with a pointer to decode_deep_exr, by design.

* EXR: cap the parts' sizes together, move the chosen part out instead of cloning it

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 18:51:33 -04:00
zenjabbaandzenjabba 9d1713cfb6 fix(ui): show brush strokes live in mask view (#2078) (#2108)
Co-authored-by: zenjabba <[email protected]>
2026-10-09 18:44:34 -04:00
David MannandClaude Opus 5.5 596842666f Masks: mask button adds a vector mask instead of replacing the layer mask (#2075) (#2114)
The Layers panel "Add a mask" button always dispatched
layer.layerMask.revealAll/hideAll/…Selection, which replace the layer's
mask unconditionally. A second click (Alt or not) silently discarded a
painted mask; Alt-click only looked like "invert" because hide-all
replaced reveal-all.

Like Photoshop, the button now adds a layer mask when the layer has
none, a vector mask (Alt: Hide All) when it already has a layer mask,
and is greyed when the layer has both (or is a shape layer with a layer
mask). Its tooltip becomes "Add vector mask" once a layer mask exists.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 18:33:14 -04:00
zenjabba 48fc0279e7 fix(ui): keep 32-bit Preview Options within the window (#2081) (#2105) 2026-10-09 18:29:57 -04:00
zenjabbaandzenjabba 9200786605 fix(linux): disable unsupported startup notification (#2089) (#2097)
Co-authored-by: zenjabba <[email protected]>
2026-10-09 18:18:54 -04:00
Tanish Manku a680ed22c9 Brush strokes carry their timing: the first moves count, smoothing feels the same on any device, a held airbrush builds up (#2110)
Brush phase 3a (owner-approved brush overhaul):

- Every stroke point now carries a time (`timeMs`). egui's pointer events have none, so a frame's
  samples are spread evenly between the previous point and the frame time. Speed spacing, airbrush
  Build-up and Stroke Catch-Up worked from scripts but never from the canvas, because every point
  had time 0. The live stroke and the commit get the same times.
- A stroke started on the press takes its moves from the press on. The moves before egui
  recognised a drag (its 6 pt click distance) were dropped, which gave every stroke a straight
  start and lost the pen's pressure ramp-in.
- Smoothing pulls by stroke time (16 ms steps, fractional below that), not once per input event,
  so a 1000 Hz mouse and a 60 Hz pen feel the same. Without Stroke Catch-Up a paused pointer stops
  the brush, as in Photoshop.
- A pointer held still keeps the stroke's clock running only while the stroke changes with time
  (airbrush Build-up, or smoothing still catching up): it repeats the held point every 16 ms and
  asks for repaints, then goes idle.
2026-10-09 15:08:25 -07:00
Sir Starch f4c1048ead Chisel bevel: facets are flat at any edge angle (#1926) (#2006)
* Layer styles: chiselled bevel facets are flat at any edge angle (#1926)

Chisel Hard and Soft shaded the facets of an edge at 30, 60, 120 or 150
degrees in regular cross-stripes (a comb along the edge), while 0, 45, 90
and 135 degree edges were clean. The height of a chisel is a linear ramp of
the distance to the edge, and that distance was measured to the nearest
pixel centre of a thresholded mask: an oblique edge is a pixel staircase,
so the distance ripples with its period (0.19 px at 60 degrees), and the
shading is a gradient of it, scaled by depth.

Chisel bevels now measure to the edge itself. A sharp anti-aliased edge
pixel (partly covered, touching an empty and a full pixel) places the edge
by its coverage along its own normal (edge_offset inverts the area a
straight edge cuts off a pixel), and a pixel measures to the line of the
edge pixels around the foot of its perpendicular, not to the centre of the
nearest one (edge_distance). The ripple drops to 0.01 px. Hard-edged masks
and soft ramps have no sharp edge pixel and give exactly the plain fields.

The GPU compositor takes the bevel distance fields from the CPU through
new FieldKind::BevelInside / BevelOutside (the glow fields are unchanged);
distance_field takes the reach so values past it are not refined, and the
band halo of the bevel fields grows to reach + 9.

* Chisel bevel: edge normals from a line fit, exact at hard stretches (#1926)

A follow-up to the previous commit, from measuring how far it was from the
best it can do. The 3x3 coverage gradient gives an edge's direction to 1-3
degrees, and the error is systematic, so every distance tilted the same way
and left a 0.010-0.017 px ripple. With the true normals the ripple is 0.002
to 0.004 px, so the normal was the limit.

refine_edge_normals fits a line through the edge points (pixel centre moved
to its edge) of the sharp pixels within 3 px that agree to 25 degrees, and
takes the line's normal where the points really are on a line (spread along
it at least 0.7 px, off it at most 0.1 px). Corners and tight curves keep the
gradient's normal. On straight edges it reaches the ideal-normal floor.

The inside field now seeds from the empty pixels, as the plain field does,
and measures to the sharp pixel next to the nearest empty one, capped by the
plain distance (which never falls short of the true one). A circle's pole,
or a rounded rectangle on whole pixels, has a stretch of edge exactly on a
pixel boundary with no sharp pixel; the distance to the sharp pixels alone
was up to 0.29 px too long there. A mask without sharp pixels still gives
exactly the plain field.

Measured on anti-aliased shapes: ripple on straight edges 0.0105 -> 0.0038
(0.0172 -> 0.0021 at 75 degrees); a disc of radius 70, inside, worst error
0.29 -> 0.02. The band halo of the bevel fields is reach + 9 and the banded
test now sees a halo that is too small (the old one passed at reach + 3).

* Chisel bevel: sparse sharp-edge storage, no full-map copies (#1926)

Measured before sending the fix: the new
bevel fields made a bevel size change in the GPU canvas about twice as slow
(12 MP: 84 -> 161 ms per step), and nearly all of a step is the CPU effect
maps. The cost of the normal refinement was memory, not arithmetic: a
Vec<Option<SharpEdge>> is 16 bytes for every pixel, refine_edge_normals
copied the whole map twice for a few thousand edge pixels, and
local_coverage cloned the whole map and read nine pixels for each.

SharpEdges keeps a 4 byte slot per pixel and a short list of the edge
pixels. The candidates are found by a row by row pass over which pixels are
covered (an edge pixel is covered and has an empty neighbour), and the
coverage is worked out where it is needed by the same formula as
local_coverage. The refinement works on the list. Nothing else changes:
the fields are bit-identical (FNV fingerprints of 27 maps at 5 reaches and
of whole bevel_maps at 3 sizes, 216 of 216 equal), and the rendered PNGs of
the issue scene and a realistic scene are byte-identical.

Release, 12 MP ellipse, size 8, one thread: new fields 408 -> 351 ms (old
fields 290); the sharp pass 48 -> 19 ms and the PCA step 32 -> 1 ms.
GPU canvas, ms per size change, main / before / after: 12 MP ellipse
84 / 161 / 96, 300 stars 122 / 246 / 166, text 91 / 184 / 139, 36 MP
ellipse 295 / 522 / 336. What is left on edge-heavy content is the
neighbour search and edge_distance, which this commit does not touch.
2026-10-09 14:22:21 -07:00
zenjabbaandzenjabba 3bc49f5e1a Fix Smart Object conversion of selected layers (#1079) (#2052)
Co-authored-by: zenjabba <[email protected]>
2026-10-09 14:03:16 -07:00
kayrockscreenprintingandClaude Opus 5.5 0493d06aaa Edit › Stroke: whole opaque pixels, Center like Photoshop, and strokes on the canvas edge (#2025)
* Edit > Stroke: whole opaque pixels; Center puts the odd pixel inside; canvas edge strokes

Center expanded and contracted the selection by w/2, so odd widths left
half-transparent pixels on both sides (a 1 px stroke was a 2 px band at
half opacity), and a selection edge on the canvas border got no stroke
(Select All, Stroke Inside drew nothing). As in Photoshop, widths round up,
Center puts ceil(w/2) inside and floor(w/2) outside, and the mask is padded
so the canvas border is a selection edge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Edit > Stroke: a hard-edged selection strokes hard, matching Photoshop's curves

Photoshop's 6 px Outside stroke of a 14 px circle selection made without
anti-aliasing is reproduced exactly when a pixel is stroked whenever its
centre is less than width + 1 from a selected pixel's (our expand gave the
6..7 px fringe partial alpha). For a hard selection the band is hardened;
soft selections keep their soft edges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Edit > Stroke: the inside of a hard stroke matches Photoshop on curves

Photoshop's 3 px and 5 px Inside strokes of a 14 px hard circle, and its 6 px
one filling the circle, fit one rule: inside, a pixel is stroked when its
centre is less than width + 1/2 from an unselected pixel's (the outside rule
is width + 1). Straight edges are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
2026-10-09 14:01:07 -07:00
kayrockscreenprintingandClaude Opus 5.5 1b8a68d45b Edit › Fill and Edit › Stroke: the colour opens the Color Picker (#2019)
* Edit > Fill: Color... and its swatch open the Color Picker

Choosing Contents: Color... opens PhotoCraft's Color Picker (as Photoshop's
Fill does), and the colour swatch opens it too instead of egui's compact
popup. OK sets the Fill colour, not the foreground; Cancel leaves it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Edit > Stroke: the colour swatch opens the Color Picker

A dialog body asks for the Color Picker on its colour field with
color_picker_ui::request; Fill and Stroke share it. OK sets the dialog's
colour, not the foreground.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
2026-10-09 14:00:31 -07:00
David MannandClaude Opus 5.5 51f9abaad7 Brushes: decode imported tips on demand, not at start (#1843) (#1949)
Opening the preset store decoded every imported tip at full resolution, and
each tip then lived twice: in the session's library and in the store's
snapshot of the last sync. A generated 600-brush library (16-bit tips,
800-2000 px, 2.27 GB decoded) cost about 4.5 GB after import and again after
every restart.

Library presets now hold their bitmaps as StoredTile references with a small
saved preview (at most 96 px): photocraft-paint gains TipShape::Stored and
Pattern::Stored (rendered with the full bitmap when loaded, else the preview),
and the store writes each tip's size and preview with its group. Opening the
store reads previews only; once a group is written its presets drop their full
bitmaps. A tip is decoded when its brush is used (picking a preset, a stroke
naming one, exporting) into a 256 MB least-recently-used cache. A loaded stored
tip serialises as `sampled`, so tool presets, actions and brush.get keep the
same JSON. Stores written before this change have no previews: their tips are
decoded once at the next start, eight at a time, and the groups rewritten. A
missing or corrupt tip file is now reported when the brush is used.

Measured with crates/engine/examples/abr_memory.rs on the 600-brush library
from crates/io/examples/gen_abr_library.rs (Windows, release):
after import 4565 -> 38 MB working set, after restart 4551 -> 20 MB,
after using 5 brushes 4560 -> 37 MB; store open 1.47 s -> 0.05 s.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 14:00:12 -07:00
zenjabbaandzenjabba 20a5f193f8 docs: describe actual raster format depths and decode limits (#520) (#2050)
Co-authored-by: zenjabba <[email protected]>
2026-10-09 13:59:13 -07:00
Roaldo Sulejmani 424a5d492f fix: remove Photoshop from user-facing strings (#1985) (#2008)
The app still showed the Adobe Photoshop name in several user-visible
strings. Per the product rule (user-facing text says PhotoCraft only),
none of these mention Photoshop now.

UI labels, tooltips and status messages:
- New Document preset "Default Photoshop Size" -> "Default PhotoCraft Size"
- "All shortcuts reset to Photoshop defaults." -> "All shortcuts reset to
  PhotoCraft defaults."
- "Import Photoshop brushes (.abr)" -> "Import brushes (.abr)"
- smart-filter fallback name "Photoshop filter" -> "Smart filter"
- File > Save As .psd/.psb filter "Photoshop" -> "PSD Document"

Errors and warnings:
- "this Photoshop filter isn't implemented in PhotoCraft" -> "this smart
  filter isn't implemented in PhotoCraft"
- smart_map: "has no PSD equivalent", "not a recognized filter", "its
  filter data is missing/unreadable", "this filter has no PSD equivalent"
- tiff_layers: "the PSD layer data...", "the PSD image resources..."
- multichannel: "32-bit Multichannel isn't supported"
- abr: "not a readable brush file (.abr)"
- gradient import: "not a readable gradient file (.grd)"

Translations: updated the changed tl! sources in all 16 catalogs and
dropped the stale "Load Photoshop brushes (.abr)" entries.

Installer / OS metadata: de-branded the nfpm description, the PSB MIME
comment, the AppStream summary/description, the macOS UTType
descriptions, the Windows ProgId Description and the desktop launcher's
Keywords. The Photocraft.PhotoshopDocument ProgId and the
image/vnd.adobe.photoshop MIME/UTType stay: machine identifiers,
changing them hurts file fidelity and Open-with registration.

Command params docs (agent-facing): dropped Photoshop from the
type_cmds kernPair text, the layer_menu_cmds Advanced Blending defaults
and the mask_view_cmds backslash-key text. The "photoshopManages" wire
value stays. Comments, format identifiers and the "photoshop" theme
alias are out of scope and unchanged.

The macOS native-menu shortcut resolution messages no longer say "as in
Photoshop" (Hide/Minimize).
2026-10-09 13:59:07 -07:00
David MannandClaude Opus 5.5 27906c05c1 Compose: bound effect memory on large documents (#1909) (#2076)
A layer with Transparency Shapes Layer off takes the whole canvas as its
effect region, so on a 1920 x 103675 page each such stroked layer built
~2.4 GB of effect maps, and a render held them for every layer at once.
Every edit's damage rect rebuilt them: 13 s and 11+ GB for three layers,
past 24 GB for ten.

When such a layer's effects are local (no gradient strokes, Precise
glows, chiselled bevels or noise) and it is composited within the
rectangle being rendered (each band of render_bands, or a damage rect),
build its maps over that rectangle padded by twice the effect reach, and
let them go when the next band starts. Composited over anything wider (a
group's effect shape renders its children over the group's whole region)
it keeps the whole region. The pixels are unchanged: a test renders every
local effect kind, masked and unmasked, inside a group with far-reaching
effects and clipped to a base with a wide glow, at 8/16/32 bits, in bands,
parts and tiles from a cold effect cache, and compares bit for bit with
the whole render.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 13:58:01 -07:00
zenjabbaandzenjabba 102e7ea891 fix(ui): apply distinct workspace preset layouts (#1120) (#2051)
Co-authored-by: zenjabba <[email protected]>
2026-10-09 13:57:56 -07:00
Alex 523d9257a8 Match New Document to clipboard in control API (#2045) 2026-10-09 13:56:24 -07:00
David MannandClaude Opus 5.5 6fba13cd1d History: Delete current state and New Document from the panel footer work (#1117) (#2039)
The History panel footer's trash and file-plus buttons discarded their
clicks. They now dispatch two new engine commands:

- history.deleteState {"state"?}: drops the state and every later one,
  as Photoshop's linear history does; the document returns to the state
  before and the deleted steps can't be redone. The oldest state can't
  be deleted (button disabled).
- history.newDocument {"state"?,"name"?}: a new document holding the
  document at that state, named after the state, with a fresh history.

Snapshots aren't implemented, so Create new snapshot is shown greyed.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 13:56:19 -07:00
David MannandClaude Opus 5.5 7567347b29 Dialogs: the first value is focused and selected; values persist (#1757) (#2040)
Like Photoshop, a schema value dialog (Select > Modify, Filter, Image >
Rotate Canvas > Arbitrary, ...) opens with its first number field focused
and its text selected, so typing replaces it and Enter applies it. It
also reopens with the values it was last applied with, kept across
restarts in prefs.dialogs and validated against the command's spec on
the way back in (ranges clamped, unknown choices dropped). Cancel and
failed runs remember nothing. Dialogs that show document state (Global
Light, Color Table, Proof Setup, Assign/Convert to Profile) and Define
Pattern keep their current behaviour.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 13:56:14 -07:00
David MannandClaude Opus 5.5 51598bb061 Text: fall back to Thai-capable fonts for missing glyphs (#1909) (#2030)
Thai typed in a font without Thai glyphs (any newly chosen font, which
drops the PSD PostScript name that found the original Thai face) fell
through the fallback stack to .notdef: none of the candidate families
cover Thai on Windows (Segoe UI), and Arial Unicode MS is rarely
installed. Add the platform Thai families (Leelawadee UI / Leelawadee /
Tahoma, Thonburi / Sukhumvit Set, Noto Sans Thai) to the candidates,
ahead of the CJK and last-resort fonts, as Photoshop's missing glyph
protection substitutes an installed font. parley picks the fallback per
cluster, so base consonants and their marks stay in one font.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 13:56:09 -07:00
Dan HiornsandClaude Opus 5.5 9966b534cd About window: fixed table headers, aligned columns, fitted tabs (#2000)
Help > About > Contributors and Models: the table header stays put while rows scroll, columns are measured once so sorting no longer shifts them, counts are right-aligned and every column fits the 700 pt window. The grab bag drops its stray separators and spaces rows evenly, and Models shows <1% for a model with commits and is as tall as its rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:36:44 -04:00
SimonandClaude Opus 5.5 72cabac616 Layers panel: the scroll wheel over the blend-mode menu steps through the modes (#1961)
The wheel over the Layers panel's blend-mode dropdown (closed or open) steps to the next or previous mode, one per notch and one undo step each, stopping at the ends, as in Photoshop. Fractional wheel deltas add up to whole notches, and the wheel there no longer scrolls the panel (#1747).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:34:01 -04:00
optimalbyteeandClaude Opus 5.5 cc0441f9ae Save As: the document takes the saved file's name (#2018)
A successful Save As (UI, automation or headless) renames the document to the written file, so its tab and title stop saying Untitled. The name is file identity, not a history step: undo and redo keep it. Failed writes, Save a Copy and exports leave the name, path and dirty state alone, and a deferred save no longer steals the selected tab.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:30:52 -04:00
RaghavandClaude Opus 5.5 45b22e7403 GPU: gradients with coincident stops fall back to the CPU compositor (#2005)
The 4096-entry ramp LUT interpolated across a hard stop, showing grey where the CPU export is
white. Gradient fills, Gradient Maps and gradient effects with coincident colour or opacity stops
now return Unsupported so the canvas uses the CPU oracle. Fixes #974.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:30:42 -04:00
Elvis33LEandClaude Opus 5.5 08ca445782 DNG: deflate compression 8 with the TIFF predictors (#1971)
Integer DNGs with zlib-compressed strips or tiles (compression 8) now decode, with TIFF predictor 1
and 2 (wrapping at the sample's container). Output is capped at the tile size; floating-point
predictor 3 and lossy DNG keep their unsupported errors. flate2 was already a workspace dependency.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:29:05 -04:00
shmuelbiller1andClaude Opus 5.5 f1413ea12e Outer Glow stays behind a see-through fill (#1964)
Outer Glow now gets the same fill-dependent knockout as Drop Shadow, on CPU and GPU, so a Fill 0%
shape with a glow no longer paints the glow across its interior. Fixes #1953.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:26:38 -04:00
Brandon ThomasandClaude Opus 5.5 11a2b72455 Prefs audit: Export Clipboard reads as wired again (#2069)
The prefs_usage scan treats everything after a file's first #[cfg(test)] as test code; the channel-tint tests from #1986 sat above export_os_clipboard and hid its read. The test module moves to the end of ui-egui's lib.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:23:11 -04:00
UnemarsandClaude Opus 5.5 9da40a1c7a Quick Selection: Photoshop's behaviour, measured and fitted (#1966)
Quick Selection is now one min cut around the brush footprint (Boykov & Jolly 2001; coarse to fine for
large windows, Lombaert et al. 2005), with costs fitted to Photoshop 25.4's masks measured as a black box
on 105 synthetic and public-domain cases (mean IoU 0.94 synthetic, 0.83 paintings), at Photoshop's
512x512 working-resolution rule. Replaces the colour-model flood, which selected far too much.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:21:27 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 bdbd43e63f Color Lookup: Load 3D LUT opens the native file picker (#1947)
The Color Lookup properties' Load 3D LUT… entry opens the platform file picker (filtered to .cube, .3dl and .look, on desktop and web) and embeds the chosen LUT into that adjustment layer, replacing the typed-path field. A cancelled or invalid pick leaves the layer unchanged (#1749).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:20:13 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 a4fbb1245d Levels applies each channel before the master, like Curves (#1929)
Levels and Curves composed their master and per-channel records in opposite orders (#975). The
Photoshop-authored corpus decides it: channel first, then master. Levels now does that, bringing
psd-tools levels_rgb.psd from 0.447 to 0.012 max error; Curves (curves_rgb.psd passes) is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:19:29 -04:00
Gert Pellin - GPEandClaude Opus 5.5 24435de7bb Canvas: say when the desktop takes an Alt-click (#2003)
Desktops that move windows with Alt+drag (Cinnamon, MATE, Xfce, older KDE) grab Alt+left presses, so
the Alt Eyedropper and Clone Stamp source never got the click. The canvas now spots the grab and says in
the status bar what happened and how to get Alt-click back. Fixes #1658, #1659.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:14:38 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 748821864e Panels: Close and Close Tab Group on a dock tab's context menu (#1924)
Right-clicking a dock tab offers Close (hides just that tab; the last one hides its group) and Close Tab Group, as in Photoshop. Hidden tabs are kept by name in the dock layout, so they survive theme switches and workspace saves, and the Window menu brings a tab back (#1753).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:14:10 -04:00
Max MurphyandClaude Opus 5.5 27263bb16d Canvas: zoom is physical at any display scale (#1978)
View zoom now means device pixels per document pixel, so 100% shows one image pixel per physical
display pixel on a scaled (125%, 200%) display, as in Photoshop. Fit, Actual Pixels, pan/zoom anchoring,
scrollbars, the navigator, the pixel grid and every hit tolerance go through canvas_ppp / point_zoom.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:10:49 -04:00
David MannandClaude Opus 5.5 32c918aaee Crop tool: overlay options (thirds, grid, diagonal, triangle, golden ratio/spiral), O / ⇧O (#2026)
The Crop options bar's overlay button opens Photoshop's overlay menu: six overlays, Auto/Always/Never
show modes, and O / Shift+O to cycle the overlay and its orientation. The default is Rule of Thirds with
Auto Show Overlay, as in Photoshop. ui.set takes cropOverlay, cropOverlayShow and cropOverlayOrientation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:06:27 -04:00
Krzysztof CieślikandClaude Opus 5.5 0bf7a1e15f Preferences: wire Large Tabs, Export Clipboard and Show Channels in Color (#1986)
Large Tabs makes the document tab strip taller (34 px) with larger type; turning off Export Clipboard stops copies being mirrored to the OS clipboard; Show Channels in Color tints the Channels panel thumbnails (RGB from black to the primary, CMYK from white to the ink). Settings that do nothing: 48 of 141 (#204).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 16:03:44 -04:00
Brandon ThomasandClaude Opus 5.5 9b0c6c4d74 PSD import: a pattern-filled shape opens as a pattern fill layer (#2059)
Since #1917 the exporter writes pattern fill pixels; a vector-masked pattern fill then reopened as a
shape layer covering the canvas, failing the corpus round-trip floor (adjustment-fillers.psd).
Pattern-filled plain shapes now import as pattern fill layers with their vector mask.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:59:48 -04:00
David MannandClaude Opus 5.5 b8fe7dd5ee Crop tool: arrow keys nudge, X swaps orientation, W × H readout (#1958)
With a pending crop frame, the arrows move it 1 px (Shift 10 px) instead of the selection or layer, X
swaps it between portrait and landscape about its centre (with the options-bar ratio), and the frame's
W x H shows beside the pointer while drawing or resizing it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:59:16 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 04b9db61e9 Filter dialogs remember their last applied settings (#1944)
A schema-built filter dialog reopens with the values it was last applied with, as in Photoshop. Only schema-valid numbers, choices and booleans are kept (no paths, document indices or free text), and a failed or cancelled dialog saves nothing (#1757).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:57:03 -04:00
David MannandClaude Opus 5.5 d0119dedbb Crop tool: a pending crop stays with its document (#1957)
A pending crop frame belongs to the document it was drawn on: New, Open, a tab switch or closing it
cancels the frame, so it never shows on or crops another document. While a crop is pending, the menus
Photoshop greys are greyed (checked item by item in Photoshop 27.11), and Image > Crop commits it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:54:01 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 a82408e3e2 Actions: Play runs the first action when none is selected (#1990)
The Actions panel's Play button falls back to the first action when no row (or a stale row) is selected, as Photoshop does, and a failed playback request now shows in the status bar instead of being dropped (#1951).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:53:33 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 25e349b048 Dialogs: the whole title band drags the window (#1945)
A dialog's drag handle spans the full title row plus a few pixels of padding around the title, so grabs slightly beside, above or below the title text move the window (#1921). The title keeps its height.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:50:27 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 765495e53b Free Transform: rotation cursor and live angle readout (#1948)
Just outside a corner the pointer becomes a curved rotate arrow, and while rotating the angle is shown
next to it. Distort and Warp keep their cursors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:50:07 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 c02ffa9755 Spot Healing: Proximity Match samples the original pixels (#1968)
Proximity Match copied its translated patch within the buffer it was writing, so overlapping offsets
re-copied fresh output and left streaks. It now reads from the pre-heal pixels, with checked bounds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:46:58 -04:00
Reynold HuandClaude Opus 5.5 60bce1894b File Handling: wire Lowercase Extension through Save As (#1941)
Preferences > File Handling > Lowercase Extension is live: with it on (the default) a save path's extension is lowercased (CAT.PSD saves as CAT.psd); off keeps the user's spelling. Settings that do nothing: 51 of 141 (#204).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:45:20 -04:00
LloydNicholsonandClaude Opus 5.5 be446f89d3 Transparent PNG, TIFF and other flat images open as Layer 0, not Background (#1913)
A flat image with transparency (alpha channel or tRNS) opens as a normal, unlocked Layer 0, as in
Photoshop; opaque images still open as the locked Background. A lone Layer 0 saves back to PNG natively.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:43:14 -04:00
Reynold HuandClaude Opus 5.5 429b9fc6a5 Type: wire the Use Escape to Commit preference (#1927)
Preferences > Type > Use Escape to Commit is live: on (the default) Escape commits the type session as before; off, Escape cancels it like the Cancel button, as in Photoshop. Settings that do nothing: 52 of 141 (#204).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:42:05 -04:00
Reynold HuandClaude Opus 5.5 23c56c659e Type: wire Fill New Type Layers with Placeholder Text (#1935)
Preferences > Type > Fill new type layers with placeholder text is live: with it off, a Type tool click starts an empty layer (removed again if committed without typing). Settings that do nothing: 53 of 141 (#204).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:38:38 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 3eef2c6bb4 Type: imported PSD tabs render as whitespace, not a box (#1942)
A literal tab in PSD text shaped as .notdef. Layout now shapes it as a space, keeping byte, style
and caret offsets intact. Tab stops are still to come. Part of #1881.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:34:38 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 cc4a13b58d Paint: keep stylus pressure on quick taps (#1967)
A release that egui reports as both a drag stop and a click no longer replays the click over a live
stroke (which painted a second full-pressure dab), and the click fallback now uses the pen's pressure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:34:21 -04:00
MarekSpodBiedryandClaude Opus 5.5 f885991184 Menus: a submenu with every item disabled is disabled too (#1984)
A submenu header is enabled only while some item under it can run, so File > Export, Automate, Scripts and Import grey out while a crop is pending, as in Photoshop (#1976).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:33:39 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 54d7b07acf Convert to Smart Object keeps a pattern fill's pattern (#1937)
The embedded document built by layer_to_smart now carries the document's patterns, so pattern fills
and pattern effects keep rendering inside the smart object and after Edit Contents. Fixes #1867.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:33:20 -04:00
Brandon ThomasandClaude Opus 5.5 ee3ebfa748 Smart contents test: match the refused path by file name (Windows CI red since #1882) (#2042)
The refusal message Debug-quotes the path, which doubles backslashes on Windows, so
contains(path) never matched there. Matching the unique file name keeps the check.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 15:32:39 -04:00
kayrockscreenprintingandClaude Opus 5.5 8b29d6c2cd PSD import: warn when an adjustment layer can't be read (#1925)
An adjustment layer kept verbatim as Unsupported rendered as nothing without telling anyone. Import
now warns, naming the layer, the adjustment and (for Color Lookup) the reason. Part of #1763.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:29:29 -04:00
Reynold HuandClaude Opus 5.5 b9f469546f Print Size honors the Screen Resolution preference (#1923)
View > Print Size divides the document's ppi into Preferences > Units & Rulers > Screen Resolution (72 ppi by default) instead of a hard-coded 72, and the setting is no longer hidden. Settings that do nothing: 54 of 141 (#204).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:29:25 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 d6802c62c0 Proximity Match: bound search radii to the image (#1969)
best_offset clamps the search radius and ring to the image extent and rejects zero or negative radii,
so hostile values no longer overflow i32 loops or search for billions of iterations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:29:16 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 3cae29abfa Grid: percentage spacing and snapping use each canvas axis (#1914)
A percentage grid now spaces vertical lines by the document width and horizontal lines by its height,
so rectangular canvases get proportional cells, and grid snapping uses the same per-axis steps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:27:30 -04:00
kayrockscreenprintingandClaude Opus 5.5 2819f37033 PSD export: pattern fill layers keep their pattern in CMYK and Lab (#1917)
The PSD (and layered TIFF) exporter rendered fill layers with no patterns, so pattern fills were
written as transparent pixels; in CMYK and Lab those tiles survive and the reopened layer drew empty.
Pattern fills now render from the document's patterns. Round-trip test over 4 modes x 3 depths.
Fixes #1907.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:26:56 -04:00
kayrockscreenprintingandClaude Opus 5.5 19256a29f5 Fill layers keep their colours in the document's mode (#1915)
New Fill Layer (Solid Color, Gradient), the Gradient tool's live fill layers, gradient fill edits and Gradients panel presets store their colours in the document's mode (Color::in_mode / Fill::in_mode), so a fill layer in a Grayscale, CMYK or Lab document composites like the same colour painted with Edit › Fill, as Image › Mode already converted them. Fixes #1905; tests at 8, 16 and 32 bits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:23:07 -04:00
khhjoeandClaude Opus 5.5 01bdf39f1b gpu: write F32_MAX exactly so the compositor shader builds on WebGPU (#1982)
The decimal 3.40282347e38 is just above f32::MAX; naga rounds it but browsers' Tint rejects it, so
the web app had no GPU compositor. Now a hex literal, with a test that every decimal float literal in
the shader fits f32.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:22:30 -04:00
3c5dc002d2 macOS: unsaved-changes prompt shows plain button labels (#1936)
On macOS the save prompt reads Save / Don't Save / Cancel without printed key letters, like the native alert; D, C, S, Return and Escape still answer it. Windows and Linux keep their mnemonics. Shortcut test from #1963 (arthurdeka).

Co-Authored-By: arthurdeka <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:22:26 -04:00
jason4shortandClaude Opus 5.5 b808780666 Paste: drop a stale image once the OS clipboard has moved on (#1912)
When the OS clipboard no longer holds the image we mirrored or imported (text or a file was copied
since), the session clipboard drops it, so Paste reports nothing to paste instead of a stale image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:20:38 -04:00
shmuelbiller1andClaude Opus 5.5 3e9359071c Native format: deflated ZIP entries read with an unbounded budget, no huge preallocation (#1956)
Reading a deflated .pcraft entry with max = usize::MAX no longer overflows the take() limit, and a
forged size in the ZIP header no longer reserves gigabytes up front (preallocation is now capped).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:19:43 -04:00
DmytroandClaude Opus 5.5 74eacf9860 i18n(uk): refine eyedropper and colour picker wording (#1974)
Ukrainian: clearer sampling terms (Sample, Sample Size), N × N averages, Color to Alpha and the web/print gamut warnings, plus the missing Transparency/Opacity Threshold rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:18:16 -04:00
ROSSA AIandClaude Opus 5.5 483712655f codecs: PNG export gives the same bytes on any core count (#1932)
The parallel PNG encoder now cuts deflate bands by a fixed byte budget instead of by thread count,
so the same image and options give identical files on any machine. Test covers 1, 2, 7 and 32 threads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:17:06 -04:00
shmuelbiller1andClaude Opus 5.5 decc7715b9 PSD: Optical kerning survives a round trip (#1517)
PSD export regenerates the document Txt2 block with one text object per TextIndex carrying each run's auto-kern mode (manual, metrics, optical), which EngineData's AutoKerning can't distinguish, so Optical no longer reopens as Metrics (#1348). A kept object with unchanged text keeps the file's extras (glyph pen positions); duplicate or out-of-range TextIndex values are renumbered and capped, so a crafted file can't size the save. io corpus tests stay at their floors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 15:09:10 -04:00
optimalbyteeandClaude Opus 5.5 6ae2a8498c Optimize Radial Blur sampling without changing output (#1499)
Radial Blur prepares its sample transforms once per filter (blur::radial::Plan) and shares them across output tiles, reading each bilinear tap once with channels kept together. Output is identical to the previous sampler at Draft, Good and Best, across colour models and depths (tests compare against the unchanged reference path); a failed table allocation falls back to that sampler. Measured on 24 MP RGBA8, Good, amount 1: Spin 66.1 -> 16.4 s, Zoom 19.2 -> 5.4 s (bench_radial example, docs/radial-blur-performance.md).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 14:41:52 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 d402631411 File > Export > Color Lookup Tables: export selected adjustment layers (#1493)
file.export.colorLookupTables takes scope all|selected or an explicit layers list and bakes only those top-level, visible adjustment layers, always in document stacking order; the dialog defaults to the selection when it is all exportable adjustments. Invalid selections and sizes are errors rather than silent fallbacks; LUT sizes outside 2-129 (the reader's limit) are now refused instead of clamped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 14:36:51 -04:00
optimalbyteeandClaude Opus 5.5 d651be1393 Speed up Mosaic with portable row reads (#1524)
Mosaic sums each four-channel cell by reading whole rows once with channel sums kept in registers, in the original addition order, so the output is bit-identical (including HDR values, -0.0, zero alpha and partial source bounds); 24-38% faster on three of the four measured cell sizes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 14:26:13 -04:00
Harrison O'Connor-HooverandClaude Opus 5.5 9e36825d2d Allow automation to edit embedded Smart Object contents (#1882)
Fixes #1833. Control and MCP may run Edit Contents, Convert to Layers and Save Contents on smart objects whose source is in memory (embedded, or a Photoshop UUID backed by embedded liFD data). Before any disk read the engine re-checks the source's stored path through the session's authorize gate, including nested sources re-rendered while unpacking, so external linked files stay refused; explicit layer targets work with another layer selected, and interactive linked-file access is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 14:24:58 -04:00
Minseo LeeandClaude Opus 5.5 9f23d65262 Type tool: list fonts' real style names, including numeric subfamilies (#1844)
The style menu now shows each face's actual OpenType subfamily (name 17, else 2) instead of a name guessed from its weight, so fonts whose faces share one weight (Yoon's numeric 20/30/40/50) list and render distinct faces: FontDb::select_named_face registers a runtime-only alias for the exact face, while the document keeps its public family and PostScript name. Variable faces still list the standard weights their wght axis covers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 14:12:49 -04:00
Harrison O'Connor-HooverandClaude Opus 5.5 cd559b387a Fix browser Save for Web downloads and stale export dimensions (#1857)
Save for Web gets a platform-writer entry point (web_cmds::save_for_web_with_writer) so the browser build downloads every image, spacer and HTML file side by side; the export is authorized before any picker opens, a failed write stops it, and only a complete export remembers its settings. Each document now opens the dialog at its own size instead of the last export's width, height and percent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 14:03:58 -04:00
Kostis PapadakisandClaude Opus 5.5 c0541baf6a Raw: decode uncompressed Fujifilm RAF, Bayer and X-Trans (#1872)
RAF's header, metadata records and Fuji IFD give size, packing (16-bit, 12-bit LSB-first,
14-bit in 32-bit words), layout, black, WB, crop and exposure bias; X-Trans and other
periodic non-Bayer CFAs go through a new edge-directed demosaic. Compressed and early
SuperCCD RAF stay unsupported (preview fallback). Tests use synthetic files only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:59:07 -04:00
kayrockscreenprintingandClaude Opus 5.5 82148e77f5 Filter previews compute off the UI thread; a stale one is cancelled once the slider settles (#1899)
In the desktop app every filter's live preview now runs on the preview worker (not just Indexed Color), so a slow one like Gaussian Blur at 1000 px no longer freezes the window. The worker hands the filter a JobCtx (Session::set_inline_job_ctx) and cancels a preview for older values once the dialog's values have been unchanged for 150 ms; during a drag the running preview is left to finish.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:52:24 -04:00
Gotya-OFFCIALandClaude Opus 5.5 4716d33372 Raw: cRAW black level without a tag; measured image areas (D800E, ILCE-7) (#1902)
Sony cRAW files with no BlackLevel tag take the 512 their tone curve gives the black
code instead of 0 (the ILCE-7 no longer develops washed out; the RX0 corpus oracle moves
to 512 too). cameras.rs gains measured image areas without a full profile: the Nikon
D800E and Sony ILCE-7 crop like the camera's JPEG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:51:43 -04:00
sunyd168andClaude Opus 5.5 0af072e82c SVG import: refuse deeply nested markup instead of overflowing the stack (#1901)
A pre-scan rejects element nesting past 512 levels before the XML parser recurses
(a 70 KB file of <g> aborted the process). .svgz is inflated by the importer with a
128 MB cap, so it can be scanned too and gzip bombs are refused; flate2 moves from a
dev-dependency to a dependency (already in the tree through usvg).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:47:17 -04:00
Shayan HorbankandClaude Opus 5.5 a342ab8820 Add centered and transformable painting symmetry axes (#1821)
Photoshop's Vertical, Horizontal, Dual Axis and Diagonal paint symmetry presets beside the
path-based symmetry: axes start at the document centre, Transform Symmetry moves and rotates
them (Shift snaps to 15°, Enter applies, Esc cancels), and all copies merge into one coverage
pass so overlaps don't build opacity. New paint.setSymmetry command and preset icons. Fixes #1648.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:44:24 -04:00
Reynold HuandClaude Opus 5.5 3ae44e3911 Document tabs: Reveal in Finder and drag to reorder (#1906)
The document tab's context menu gains Reveal in Finder (a new file.revealInFinder command that reuses the smart-object reveal helper and targets the clicked tab's document), and dragging a tab sideways reorders the open documents through document.move, with a drop line, in both tab strips. Flips UI-217-6 to done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:38:40 -04:00
kayrockscreenprintingandClaude Opus 5.5 0299162db2 MCP: tool schemas without $ref, $defs or boolean schemas (#1845)
Every tool's input schema is rewritten once at startup: $refs inlined (use-site
descriptions win), $defs dropped, boolean schemas turned into {}, with a depth cap
for recursive definitions. ui_pointer events get a concrete schema. Strict providers
no longer reject the whole tool list. Fixes #1782.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:29:50 -04:00
kayrockscreenprintingandClaude Opus 5.5 63f9ca9d74 Control: shell dialogs are listed and driven as "shell" (#1811)
ui.inspect lists the open shell dialog (Workspace, Pixel Aspect Ratio, Show Extras,
32-bit Preview) with the id "shell", and ui.dialog.set/confirm/cancel accept it;
confirm goes through the automation authorizer and the dialog's shared OK. Fixes #1004.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:27:46 -04:00
David MannandClaude Opus 5.5 147ee7efa0 Crop tool: rotate the crop frame by dragging outside it (#1879)
Outside the crop frame the pointer is Photoshop's curved turn cursor and a drag turns the frame
about its centre (Shift: 15 degree steps) with an angle readout; handles resize along the turned
axes and a double-click inside commits. image.crop takes an optional angle: Image Rotation >
Arbitrary so the frame is upright, then the crop, in one undo step. Fixes #1792.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:27:27 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 0f2900da34 Edit > Stroke: a full options dialog with Fill's blending controls (#1477)
Edit > Stroke… from the menus opens a Photoshop-style dialog (Width, Color, Location, Blending:
Mode, Opacity, Preserve Transparency) remembering its last values; called with params it runs
directly. edit.stroke gains mode and preserveTransparency, blending through Fill's compositing
(blend_color_mask), and validates them. The Blending section is shared with Fill
(dialog_blend_ui.rs). Fixes #1463.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:21:21 -04:00
Reynold HuandClaude Opus 5.5 4ed4faee51 Command palette: recently run commands on an empty query (#1824)
menus::invoke records each successfully run command (deduplicated, newest first, last 8) and the palette lists them when its query is empty, falling back to the full list in a fresh session. Flips UI-217-7 to done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:21:17 -04:00
Jason XiangandClaude Opus 5.5 5aaf0e4aae file.new rejects invalid parameters instead of falling back (#1878)
Unknown keys, wrong types, out-of-range sizes or resolution and unsupported
mode/depth/background now fail naming the parameter, before a floating selection is
committed or a document added; omitted fields keep their defaults. The renderer tests
now pass numeric depths (strings had silently fallen back to 8-bit). Part of #507.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:20:34 -04:00
Nigel Ihza FirdausyandClaude Opus 5.5 ffb62ec975 Pen: Ctrl/Cmd+Z undoes in-progress points (#1478)
While a Pen path is being drawn, Undo (its customisable shortcut or Edit > Undo) and Backspace/
Delete remove the last uncommitted anchor instead of undoing an earlier document step, as in
Photoshop; once the draft is empty, Undo works on the document again. Fixes #1466.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:18:00 -04:00
kayrockscreenprintingandClaude Opus 5.5 fdfa57f456 New Document starts from the last document's settings (#1869)
Fixes #1810. File > New remembers the size, resolution, mode, depth, background and display units its OK used (in the preferences' dialogs map, so they survive a restart) and starts from them next time, as Photoshop does; a clipboard image still sets the size, and corrupt remembered values are ignored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:15:35 -04:00
AntonandClaude Opus 5.5 66b022cddd Web: fonts served next to the app, loaded on demand (#1875)
A host lists fonts in fonts/manifest.txt beside index.html (craft-fonts' manifest format, paths
kept inside the site); the web shell lists those families in the font menus and fetches a family
when it is picked or a layout needs it, then re-renders the affected type layers without a history
step. No manifest changes nothing; package.sh copies one in with PHOTOCRAFT_WEB_FONTS_DIR. The
style menu also lists the weights of a variable font's wght axis.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:14:47 -04:00
kayrockscreenprintingandClaude Opus 5.5 54ff207004 Image › Adjustments: apply per tile in parallel (#1800)
adjust_surface now takes the layer's tiles and adjusts each one on its own rayon task, so a large layer needs one tile's buffers per thread instead of four full-layer copies. The result is bit-identical to the single pass for every adjustment kind, colour model and depth, with and without a soft selection (tiled_adjustment_matches_one_pass_over_the_content). Adds an invert scenario to large_image_bench.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:06:46 -04:00
JeremyandClaude Opus 5.5 7a5b0b5d45 Canvas: the CPU canvas pixel grid skips empty pixels, like the GPU canvas (#1891)
The CPU path drew the pixel grid over the whole view, including transparent areas, while the
GPU shader only lightens or darkens pixels with content. pixel_grid.rs applies the shader's
rule to the composite of the area in view, as merged segments cached per revision and padded
region (capped at 60k segments), sharing the zoom and strength constants with the shader.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:04:27 -04:00
David MannandClaude Opus 5.5 45c5001dfd GPU canvas: convert changed layer tiles once each, in parallel (#1847)
Changed tiles are grouped by shared Arc and converted once each in parallel batches; a tile
shared by several coordinates (a solid fill, a cleared area, a non-zero default) is uploaded
once to a scratch tile and copied on the GPU, and new pages take the same path. 16-bit RGB and
gray tiles convert to RGBA16F through a lookup table. Select All + Fill on a 50 MP 16-bit page
refreshes in 15-19 ms instead of about 1.4 s. Fixes #1774.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:04:21 -04:00
AntonandClaude Opus 5.5 96cdff7454 Free Transform: edge handles scale proportionally, Shift stretches one axis (#1873)
As in Photoshop CC 2019 and later, dragging an edge handle now scales both axes by the same
factor about the middle of the box (Alt: about the reference point), and Shift stretches the
one axis. Use Legacy Free Transform restores the old behaviour for edges as well as corners.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:04:14 -04:00
AlonandClaude Opus 5.5 9ba843290e Ctrl+T on a selected path transforms the path (#1871)
With Path Selection or Direct Selection and a path, Edit > Free Transform (and the Transform
items) frame the path's anchors and handles and commit one path.transform step instead of
moving pixels; it works on the Background too. Distort and Perspective, which an affine path
transform can't follow, report an error. Fixes #1770.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:04:08 -04:00
Jason XiangandClaude Opus 5.5 a4a2583280 Layer comps: an edited layout becomes the Last Document State (#1862)
Applying a comp after ordinary edits now backs up the edited layout instead of keeping
a stale one; cycling or reapplying unedited comps keeps the original backup. The check
runs only on comp application and respects each comp's capture flags. Fixes #919.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:04:07 -04:00
David MannandClaude Opus 5.5 7c2bd89e6a Canvas: edits that change no pixels (a lasso selection) don't recomposite (#1853)
Session::edit now reports empty damage when the step leaves every layer's pixels and the
document's compositing fields untouched (same_pixels: a bounded walk over the layer tree
comparing tiles by pointer), so a selection change no longer recomposites the whole canvas.
Adds a lasso_bench example. Fixes #1773.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:03:25 -04:00
rafi612andClaude Opus 5.5 f39abb70b9 System title bar: hide the in-app mark and title, show the file in the OS title (#1903)
With Preferences › Interface › System Title Bar (Windows/Linux) the OS draws its own icon and title,
so the in-app bar drops the brand mark and centred title; the OS window title follows the active
file ("name — PhotoCraft"), sent only when it changes. macOS and the web build are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 13:02:53 -04:00
kayrockscreenprintingandClaude Opus 5.5 83b0bcedbe Schema dialogs ignore notes after a spec; Selective Color's OK works again (#1886)
parse_spec reads only the spec's leading {…} object, so notes and → {…} results after
it no longer become junk fields. Selective Color's per-range arrays stop showing as a
number field, and its OK applies again (it failed since #1790 tightened the params).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:59:25 -04:00
David MannandClaude Opus 5.5 d7078f3623 Layers: a new empty layer no longer recomposites every layer (#1846)
step_damage pairs layers by id and steps over a layer only one side has when it draws nothing
(an empty pixel layer or group in Normal/Pass Through, no masks, effects or Advanced Blending,
not a clipping base), so New Layer, New Group and their undo/redo report no damage. Adds the
P51 perf scenario (new layer in the 150-layer document). Fixes #1771.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:59:12 -04:00
kayrockscreenprintingandClaude Opus 5.5 21649f6030 Filter dialogs: OK keeps the preview until the filter lands (#1825)
A filter that runs as a background job no longer flashes the unfiltered image after OK: the dialog's preview is marked committing and the canvas keeps showing it (canvas::committed_filter_preview) until the job lands, fails or is cancelled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:59:10 -04:00
Jason XiangandClaude Opus 5.5 175603a644 New adjustment and fill layers get a white mask (#1858)
As in Photoshop, a new adjustment or fill layer with no selection or active path gets
an enabled, linked reveal-all mask (sparse, no canvas-sized allocation), ready to paint,
in the layer's single undo step. Fixes #1768.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:48:26 -04:00
kayrockscreenprintingandClaude Opus 5.5 71e89906ee Dialogs: tall filter dialogs scroll; a moved dialog reopens in place (#1822)
Fixes #1829. A schema-built filter body sits in a scroll area capped to the window, so Flame's OK and Cancel stay on screen in a small window; a dialog the user drags is remembered per command (or per kind) in egui's persisted memory and reopens there, as Photoshop does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:48:07 -04:00
Neil VerschooreandClaude Opus 5.5 e7a83ca342 Add Dutch (nl) UI translation (#1877)
A complete Dutch catalog (nl.tsv) registered with the complete-menu languages (nl-NL and nl-BE
resolve to it) and in the coverage test, with the strings added on main since the PR opened and
Dutch bit-depth labels (8-bits, 16-bits).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:41:23 -04:00
kayrockscreenprintingandClaude Opus 5.5 99e8ac2d2a Fill: pick the Custom Pattern from its swatches (#1861)
Edit > Fill… with Contents: Pattern shows a swatch of the current pattern; a click opens a grid of every library pattern (current one outlined, names in tooltips and accessibility labels), as in Photoshop, instead of a dropdown of names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:31:53 -04:00
Dan HiornsandClaude Opus 5.5 13d50312bd Brush preset grid: centre the columns and indent every row (#1883)
The preset grid (Brush Preset picker and Brushes tab) wrapped with horizontal_wrapped, which
indented only the first row and left the spare width on the right. Rows are now laid out as
whole columns with the same centred margin (grid_columns, guarded against NaN/zero sizes).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:29:07 -04:00
David MannandClaude Opus 5.5 dee737313a Masks: \ toggles the layer mask's rubylith overlay (#1809)
New command layer.toggleMaskOverlay, bound to \ as in Photoshop: shows the active layer's
mask as a 50% red rubylith over the composite and hides it again (view state, not a history
step; the mask stays the paint target). Disabled without a layer mask; a focused text field
keeps the key. Fixes #1765.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:28:55 -04:00
Jason XiangandClaude Opus 5.5 c645f951b0 Panels: clicking a tab of a collapsed panel expands it (#1868)
A single click on a tab of a collapsed panel group (or a pick from its overflow menu) now
expands the group and shows that tab, as in Photoshop; double-click still collapses. The tab
strip reports clicks through StripOut/CardResponse. Tested in both themes, with the
workspace locked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:28:49 -04:00
Jason XiangandClaude Opus 5.5 941b84a748 Save As and export dialogs start beside the document (#1866)
Export dialogs suggested a bare file name, so the save dialog opened wherever the OS chose.
pick_save now joins a bare suggestion onto the active document's folder (an explicit directory
or an untitled document is left as is), and the desktop dialog starts in the suggestion's folder.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:28:42 -04:00
kayrockscreenprintingandClaude Opus 5.5 d4884d33fa Rasterize Vector Mask keeps a feathered edge (#1807)
Layer > Rasterize > Vector Mask multiplied the hard vector mask into the pixel mask, dropping
the vector mask's feather (and the pixel mask's feather or density). When any of those shape
the edge, the pixel mask now becomes exactly the combined mask the compositor showed, with
feather and density baked in. Tested at 8, 16 and 32 bits against the composite. Fixes #992.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:28:36 -04:00
AnandandClaude Opus 5.5 fb23c18581 Placed layer no longer disappears when editing Smart Object contents (#1831)
Opening a just-placed Smart Object's contents switched documents while the Place transform was
pending, and end_if_left cancelled it, deleting the placed layer from the parent. When the
active document is that layer's linked child, the transform session now just ends and the
layer stays. Fixes #1797.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:28:14 -04:00
Stevan MarjanovicandClaude Opus 5.5 b81808f6bc Double-click the Hand tool to fit on screen (#1796)
Double-clicking the Hand tool's toolbar button selects it and runs View > Fit on Screen, as in
Photoshop; a single click only picks the tool, and with no document open the double-click is
harmless. Also credits the author in contributors/people.toml.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:27:49 -04:00
David MannandClaude Opus 5.5 a42f7f0004 Crop tool: Enter crops to the selection's frame (#1806)
With a selection, the Crop tool's untouched default frame frames the selection's bounds, but
Enter on it did nothing (it was always treated as the no-op whole-canvas frame). It now only
skips the commit when the frame is the whole canvas. Tested at 8 and 16 bits. Fixes #1789.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:27:22 -04:00
Max MurphyandClaude Opus 5.5 dcf8ceef85 Rulers: the horizontal ruler keeps its ticks under View > Flip Horizontal (#1835)
With the view flipped, to_doc returns the ruler's ends reversed, so the tick loop ran zero
times. ruler_range normalises the visible range to (min, max) for both rulers. Fixes #1814.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:27:12 -04:00
MarekSpodBiedryandClaude Opus 5.5 d4634bb30f Layers panel: thumbnails of tall documents fill the thumbnail height (#1805)
The layer thumbnail drew the checkerboard over the whole square cell while the texture is the
document letterboxed into it, so tall (or wide) documents showed checker bars at the sides.
The checker and image are now drawn only over the document-shaped part (channels_panel::fit_thumb).
Fixes #1762.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:27:02 -04:00
Max MurphyandClaude Opus 5.5 1bccee1fda Desktop app: exit with status 2 when --control setup fails (#1834)
A bad control token, token plus token file, or a missing automation root printed an
error and exited 0, so a launcher believed the control server was up. Now exits 2,
like a bad --control port; subprocess tests cover the four paths. Fixes #1816.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:26:02 -04:00
kayrockscreenprintingandClaude Opus 5.5 749109e6fb Define Pattern asks for the pattern's name (#1850)
Edit > Define Pattern… now opens a Pattern Name dialog, prefilled with the name the pattern would get anyway (pattern_cmds::default_name, now shared with the command so the two can't drift), as Photoshop does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:22:50 -04:00
DmytroandClaude Opus 5.5 fee2240d59 Add Ukrainian UI translation (#1799)
A complete Ukrainian catalog (uk.tsv) registered with the complete-menu languages, with
one/few/many plurals (teens use many), uk-UA locale resolution, and the coverage test entry;
plus the strings added on main since the PR opened.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:18:31 -04:00
kayrockscreenprintingandClaude Opus 5.5 86a629939a RAW: check the orientation range before narrowing (#1839)
The five RAW readers cast the u32 Orientation to u16 before the 1..=8 check, so a LONG
65538 became 2 and rotated the image. A shared tiff::orientation checks the range on
the u32 first. Fixes #1817.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:14:28 -04:00
kayrockscreenprintingandClaude Opus 5.5 5012e4c32f Image Size reports the size it applied (#1836)
image.imageSize returns the document's size after the command instead of the requested
one, so Resample off (which changes the resolution only) no longer reports a size it
ignored. Tested at 8, 16 and 32 bits. Fixes #1815.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:13:12 -04:00
Max MurphyandClaude Opus 5.5 0050f29a85 Native format: reject a leading '+' in hex pairs (#1832)
u8::from_str_radix accepts a leading '+', so "+5" decoded as 0x05; unhex now requires
two ASCII hex digits per pair and fails as corrupt otherwise. Fixes #1818.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:03:52 -04:00
Reynold HuandClaude Opus 5.5 d4a5d974ac File > Open starts in the last-used folder (#1889)
Open dialogs (File > Open and the single-file pickers for Place, scripts, notes and presets) now carry the most recent file's folder as initial_dir, and the desktop shell hands it to rfd's set_directory. Flips UI-217-3 to done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:03:31 -04:00
texjerandClaude Opus 5.5 e8b992a6f0 Preferences on Cmd+K, Search on Cmd+F (Photoshop's defaults) (#1900)
Edit › Preferences › General takes ⌘K and Edit › Search moves to ⌘F, as in Photoshop. Nothing
else was bound to ⌘F (Filter › Last Filter stays ⌘⌥F); the shortcut-capture tests follow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:02:30 -04:00
xsvmandClaude Opus 5.5 9b69ba89aa image.mode.bitmap: an unknown halftone shape is a bad-params error (#1842)
HalftoneShape::from_id returns None for an unlisted id instead of silently falling
back to Round, and the command fails naming the valid shapes (part of #507).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 12:02:04 -04:00
Reynold HuandClaude Opus 5.5 a14e94617b Hue/Saturation: hue-following colour tracks on the Saturation and Lightness sliders (#1863)
The Saturation slider's track runs grey to the hue at full saturation and the Lightness track black, the hue, white; both recolour as the Hue slider moves, as in Photoshop. Flips UI-217-16 to done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 11:56:04 -04:00
Reynold HuandClaude Opus 5.5 d7d5c6069c Test the dispatch panic guard end to end; mark REL-3 done (#1803)
A cfg(test)-only test.panic command drives Session::execute into the catch_unwind
guard in jobs::dispatch; the test asserts an internal-error Err, an untouched document
and history, and a working session afterwards. REL-3 flips to done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 11:51:51 -04:00
Sir StarchandClaude Opus 5.5 d8d2df4fba camera_raw_scope: serialise the GPU tests with GPU_LOCK (#1856)
Concurrent wgpu instances segfault in libvulkan with NVIDIA and lavapipe both installed; the three
GPU-harness tests in camera_raw_scope now hold a GPU_LOCK, like canvas_16f. Fixes #1855.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 11:51:40 -04:00
Sir StarchandClaude Opus 5.5 9bd935498b GPU parity tests: give the one-step tolerance f32 slack (#1852)
Two results exactly one 8-bit step apart can land a few f32 ulps past 1/255 after premultiplying
and subtracting (NVIDIA, Hue/Saturation in adjustment_layers); allow 4 epsilon of slack. Fixes #1848.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 11:51:36 -04:00
Reynold HuandClaude Opus 5.5 ff1d933cb8 Scorecard: mark the BUG-205 and BUG-207 rows done; the fixes and their tests are on main (#1795)
BUG-205-1/2/3 (5a5facc, #242) and BUG-207-1/2/3 (e2444ce, #234) flip to done;
each row now names the test that covers it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 11:40:48 -04:00
Reynold HuandClaude Opus 5.5 7544bb1084 Scorecard: mark UI-217-2 done; the geometry round trip is tested (#1808)
UI-217-2 flips to done: b07a2e5b (#587) persists the window and dock width via eframe,
and window_and_panel_geometry_survive_a_restart asserts the round trip.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 11:39:33 -04:00
BFlat 9823f4ea08 Merge pull request #1898 from storytold/community/1734-fxdrag
Layers panel: drag layer effects onto another layer, Alt-drag copies (#1734 carry)
2026-10-09 22:09:00 +07:00
BFlat 46c9b83ce1 Merge pull request #1897 from storytold/community/1706-corpus
xtask: corpus --all --update-manifest refetches every manifest (#1706 carry)
2026-10-09 22:08:56 +07:00
BFlat bf1795e490 Merge pull request #1896 from storytold/community/1462-labmix
Compose: restore the blend-space flags instead of clearing them after a tile (#1462 carry)
2026-10-09 22:08:53 +07:00
BFlat e45c79df3d Merge pull request #1895 from storytold/community/1636-pixls
Raw corpus: real camera files from raw.pixls.us, oracle-tested (#1636 carry)
2026-10-09 22:08:50 +07:00
BFlat 9a71884244 Merge pull request #1894 from storytold/community/1745-eyedropper
Eyedropper: Sample Size, Sample layers and Show Sampling Ring (#1745 carry)
2026-10-09 22:08:46 +07:00
a01a3eb2de Canvas zoom: Photoshop's range, ladder and ⌥-wheel step; no slide at the limit (#1718)
* Canvas zoom: Photoshop's range, ladder and ⌥-wheel step; no slide at the limit

Measured on Photoshop 25.4 (exact zoom read by script, view position by screenshot
registration):
- ⌥ + wheel: ×1.1 a notch around the pointer (was ×1.05);
- the zoom runs up to 12800 % and down to where the document's shorter side is 2 px; a wheel
  notch past a limit lands on it exactly and further notches change nothing;
- Zoom In / Zoom Out and a Zoom tool click step along 0.1 … 66.67, 100, 200 … 800, 1200, 1600,
  3200, 6400, 12800 %, from any zoom to the next rung;
- with Overscroll off, an image smaller than the view stays where zooming put it, inside the
  view, instead of being re-centred.

PhotoCraft capped the zoom at 3200 % without meaning to: the status bar's zoom field (and the
Navigator's slider) clamped it and wrote it back every frame. Past 3200 % each ⌥-wheel notch
zoomed around the pointer and the field pulled the zoom back, so the image slid towards the
pointer. All zoom paths now share `zoom_levels` (range, ladder, clamp), and the fields always
include the current zoom.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Zoom: Print Size, 200 % and Fit Layers on Screen clamp through zoom_levels too

Review of #1718: `view.twoHundredPercent` / `view.printSize` and `view.fitLayersOnScreen` still
clamped to 1-6400 % on their own. They now use `zoom_levels::clamp` like every other zoom path:
Print Size at 1 ppi gives 7200 % (it was cut to 6400 %), and fitting a 1 px layer stops at
12800 %.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Wheel zoom: a notch applies on the frame it arrives (from #1490)

Folded in from @Jeremy8776's #1490, as agreed in review: zooming reads this frame's wheel
events (`Input::raw`) instead of egui's smoothed delta, so each notch is one ×1.1 step on the
frame it arrives, with no easing over the next frames (his frame-by-frame recordings of
Photoshop). The smoothed tail neither zooms nor turns into a pan when Alt is released; panning
still uses the smoothed delta. Zoom with Scroll Wheel uses the same ×1.1 notch (assumed, not
measured).

The Filter Gallery's and Liquify's own preview zooms keep their 3200 % caps, now with a comment
saying why: they aren't the canvas.

Co-authored-by: Jeremy <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Jeremy <[email protected]>
2026-10-09 22:08:18 +07:00
buivanvu94 69f307afbb fix(ui): autoscroll Layers panel when dragging past top or bottom edges (#1728) 2026-10-09 22:08:13 +07:00
MarekSpodBiedry 5538f3920d Patch Tool: say to drag the selection after the lasso and after a click that moves nothing (#1715) (#1720)
The Patch and Content-Aware Move tools work in two steps: lasso the
area, then drag the selection. The first step only leaves a selection,
and a press and release inside the selection returns early because the
offset is zero, so neither step said what to do next.

After a lasso made with either tool, and after a drag inside the
selection that moves nothing, the status bar now says "Now drag the
selection onto another area". The string is translated in all 14
catalogs.
2026-10-09 22:08:10 +07:00
2b139ebd5c inspect: report each smart object's source (#1785)
document.inspect (and photocraft-cli info) now gives every smart object a
smartSource: embedded with its file name, or linked with a file path or,
for a PSD placed layer, the Idnt uuid its duplicates share. A script can
then tell duplicates of one placed file from independent contents, e.g.
to check that every location in a mockup template has its own art.

Co-authored-by: Juan Manuel Verges Solanas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 22:08:07 +07:00
Gert Pellin - GPE 310e46e6a0 fix(ui): one Cmd+V pastes one layer (#1638) (#1743)
On macOS AppKit runs Edit > Paste's key equivalent and takes the
key-down, but winit still delivers the key-up (it forwards key-ups
while Cmd is held). The native menu fed egui a press plus a made-up
release, and clipboard_keys treats a Cmd+V release without a paste
event as an image paste (egui-winit drops Cmd+V when the clipboard
holds no text). So one Cmd+V pasted three times: the menu's press,
its synthetic release, and winit's real release.

- native_menu: a key equivalent adds only its press, inserted ahead of
  its key-up when that is already queued; winit delivers the release.
- clipboard_keys: a Cmd+V key press that reached egui marks the paste
  as seen, so its release doesn't paste again; any V/Insert release
  clears the mark (releasing Ctrl before V left it stale and swallowed
  the next image paste on Linux/Windows).
2026-10-09 22:08:03 +07:00
Gert Pellin - GPE 58289b2822 fix(codecs): read the resolution from EXIF, XMP and Photoshop APP13; write it consistently (#1691) (#1744)
A camera JPEG (e.g. Nikon D3200) records its resolution only in EXIF IFD0, so it
opened at 72 ppi instead of 300, and saving wrote JFIF 72 next to the source's
EXIF 300.

Reading: a JPEG takes the first usable of APP13 Photoshop ResolutionInfo
(0x03ED), XMP tiff:X/YResolution, EXIF IFD0 X/YResolution + ResolutionUnit
(2 inch, also when absent; 3 cm), and only then the JFIF density. That is the
order Photoshop resolves them in; JFIF comes last because cameras write EXIF
only while many tools write a default JFIF 72. Other formats (WebP, HEIF, PNG
without pHYs, ...) fall back to XMP then EXIF when they have no resolution of
their own. All parsing is bounds-checked; malformed data reads as no
resolution.

Writing: JPEG, PNG, WebP, TIFF (XMP), PSD and Save for Web JPEG rewrite the
EXIF/XMP resolution to the image's: RATIONAL values in place, ResolutionUnit 2,
and an entry that can't be rewritten safely is removed from IFD0 without moving
any other data.
2026-10-09 22:07:59 +07:00
BFlatandClaude e39cacd895 Packaging: Windows MSI setup wizard (folder choice, progress, version, launch on finish) (#1864)
Double-clicking the MSI now opens WixUI_InstallDir without the licence page:
Welcome, install folder (remembered for upgrades in
HKLM\Software\PhotoCraft\InstallDir), Ready, progress, and a Finish page with
a ticked "Launch PhotoCraft" box (WixShellExec, unelevated). The pages name
the full version, pre-release tag included (photocraft.en-us.wxl).
package.ps1 draws the banner and side bitmaps from the app icon, so no WiX
stock art ships. msiexec /qn still installs silently. The release and ARM64
workflows install the WiX UI and Util extensions; packaging-lint checks the
.wxl. Ported from VectorCraft (storytold/vectorcraft@aa548d2).


Claude-Session: https://claude.ai/code/session_01AP7ThRN3kpNmjsuJUerJui

Co-authored-by: Claude <[email protected]>
2026-10-09 21:33:38 +07:00
Elvis33LEandClaude Opus 5.5 adc1f76df4 Indexed Color: integer counts, palette stops and asynchronous previews (#1741)
Indexed Color accepted fractional colour counts and computed its live preview on the UI thread.
Counts are now whole numbers in 2-256 with a linear slider snapping at 8/16/32/64/128/256, and on
native builds the preview runs on one background worker that coalesces slider drags and rejects
stale results. Nearest-colour lookup uses an exact kd-tree above 64 entries (identical indices,
256 colours at 4.2 MP: 3018 -> 1061 ms). Web and inline sessions stay synchronous.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 10:33:13 -04:00
Gert Pellin - GPEandClaude Opus 5.5 15737e122b Filter > Other > Color to Alpha (#1683)
A new filter that removes a chosen colour by unmixing it into transparency, as GIMP's and
Krita's Color to Alpha do: per pixel the most transparent opacity that keeps the unmixed colour
in range, shaped by transparency and opacity thresholds. It runs through run_filter (selection,
smart filters, Last Filter, one history step), floats the Background first and refuses a
transparency-locked layer; the filter dialog gains a colour parameter. Fixes #1576.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 10:13:42 -04:00
Claude ac9c7b057b Merge main into #1745 (catalogs: keep both blocks)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UHgFEHEsefoQoBParH47JA
2026-10-09 14:08:06 +00:00
StreetblockandClaude Opus 5.5 e2bb2bd681 Share concurrent cold mask builds (#1653)
Concurrent requests for the same cold combined mask each rasterized and feathered the whole
image. A per-key OnceLock slot now lets one caller build while the others wait for the same
tiles; different keys build independently outside the cache mutex, and the result is admitted
through the byte-budgeted cache with the generation taken at lookup, so a purge mid-build still
wins. The vector mask renders sequentially inside the slot so a Rayon worker can't wait on itself.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 10:05:01 -04:00
UnemarsandClaude Opus 5.5 0d10f11733 Toolbar colour chips, Color Picker and panel footers, as in Photoshop (#1729)
The colour chips sit centred in the toolbar with Default Colors and Switch Colors above them. The Color Picker gains L/a/b radios and the out-of-gamut and web-colour warnings, each with a click to take the nearest colour. Panel footers are a full-width bar with their own mask and adjustment glyphs, keeping the right-click footer menus from #1680.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 10:03:37 -04:00
StreetblockandClaude Opus 5.5 68dab88f9b Bound mask-cache memory and include it in Purge All (#1650)
The combined-mask cache was capped only at 64 entries, so large feathered masks could retain a
lot of memory, and Edit > Purge > All left them allocated. The cache is now also bounded to
512 MiB of accounted pixel bytes (result plus the pinned input), Purge All clears it and reports
its bytes, and a purge generation stops a build that started earlier from refilling the cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 10:00:00 -04:00
Brandon ThomasandClaude Opus 5.5 9b1c916f42 Japanese: command names match the menu terms (#1860)
About 50 command names from #1669 now use the same word as their menu item (ゆがみ, 演算, ぼかし(ガウス) …).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 09:57:56 -04:00
Claude 42e60e3602 Merge #1636 into #1706: keep the pixls opt-in, fetch_all takes update
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UHgFEHEsefoQoBParH47JA
2026-10-09 13:56:23 +00:00
Claude beb80bc5dc Carry #1636: document test-corpus --pixls
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UHgFEHEsefoQoBParH47JA
2026-10-09 13:56:22 +00:00
Claude 819651f3c0 Merge commit 'refs/tmp/p1745' into community/1745-eyedropper
# Conflicts:
#	crates/ui-egui/src/i18n/de.tsv
2026-10-09 13:55:40 +00:00
Brandon Thomas 74112064cc Merge main; de: Photoshop's German eyedropper terms (Aufnahmebereich, 1 Pixel, 3 x 3 Pixel Durchschnitt) 2026-10-09 09:32:53 -04:00
Brandon ThomasandClaude Opus 5.5 2e41caf897 ATTRIBUTION: keep the PngSuite row and one pixls row
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 09:29:58 -04:00
Brandon Thomas 4b7db4088b Merge remote-tracking branch 'origin/main' into pr1636ff 2026-10-09 09:29:34 -04:00
Claude 0b958be52a Merge main into #1734 (effect-row eyes from #1664 kept beside the fx drag)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UHgFEHEsefoQoBParH47JA
2026-10-09 13:29:19 +00:00
Claude a94dd19d79 Merge main into #1745 (German catalog)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UHgFEHEsefoQoBParH47JA
2026-10-09 13:29:18 +00:00
Claude 8cdea53ced Carry #1745: Current & Below keeps an active group's own contents
Document::walk lists a group before its children, so hiding everything after
the active layer hid a group's own layers and sampled transparent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UHgFEHEsefoQoBParH47JA
2026-10-09 11:50:37 +00:00
Claude cc8d3c3f77 Merge main into #1462; in_blend_space restores LAB_MIX and HDR instead of clearing them
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UHgFEHEsefoQoBParH47JA
2026-10-09 11:49:32 +00:00
Elvis33LE 3bfaef668c pixls: usage and status text, per-file licence links, dedup, --changed for raw
The xtask usage line and the corpus status listing name --pixls and
corpus/pixls; the attribution row links each of the seven files' database
entries so the licence can be checked per file; -p raw no longer pushes
the crate into the list twice; and test-corpus --changed runs (and
fetches) the raw corpus when a file under crates/raw/ changed, matching
its CRITICAL entry.
2026-10-09 13:08:16 +02:00
Elvis33LE 5d0800df7a pixls corpus: in-house sha256 and pinned.rs, opt-in like the affinity corpus
The fetch lives in pinned.rs now, reusing its manifest discipline and the
xtask sha256 module (the sha2 dependency is gone). --pixls is opt-in: not
part of --all or the CI corpus job (CORPUS_CRATES no longer includes
photocraft-raw; test-corpus --pixls fetches and adds it), matching how the
Affinity corpus is handled. The usage line names the flag, and the
attribution row links each sample's folder in the database so its licence
can be checked per file.
2026-10-09 13:08:16 +02:00
Elvis33LE 6ce21609a2 raw corpus: real camera files from raw.pixls.us, oracle-tested
Seven public-domain files (raw.pixls.us), one per decode path: Canon
PowerShot SX50 HS as CR2 and as its DNG conversion, Nikon D3 uncompressed
NEF, Sony DSC-RX0 cRAW ARW, Panasonic DC-G9 high-res RW2 (10480x7794,
crop 10368x7776), Olympus E-1 with a GRBG CFA, and the Olympus E-5 as
the documented known-unsupported packed-ORF case (still previews).

xtask grows --pixls (single-file downloads, the server redirects
/data/ to /download/), a sha256-verified manifest and a --update-manifest
path; photocraft-raw gains the corpus feature and oracle tests: format,
make/model, sensor size, CFA, black/white levels and the crop are exact,
developing yields the crop in 16-bit RGB, deterministic, with sane
range coverage.

Two real findings already documented by the tests: the PowerShot CR2 and
the RX0 ARW carry no as-shot white balance we read, so the grey-world
estimate brightens those scenes (the same camera's DNG develops blacks
to ~0). Reading the Canon and Sony maker-note WB tags is the follow-up.
2026-10-09 13:06:05 +02:00
Claude Opus 5.5 acc27e0fd0 Merge remote-tracking branch 'origin/main' into fix/1112-lab-mix-restore
# Conflicts:
#	crates/compose/src/lib.rs
#	crates/compose/src/tests.rs
2026-10-09 06:57:07 -04:00
Gert Pellin 65f30dd9e3 feat(eyedropper): Sample Size, Sample layers and Show Sampling Ring (#1649)
The Eyedropper options bar now has Photoshop's Sample Size (Point Sample,
3 by 3 ... 101 by 101 Average), Sample (Current Layer, Current & Below,
All Layers, All Layers No Adjustments, Current & Below No Adjustments)
and Show Sampling Ring.

- engine: new `document.sampleColor {x, y, size, sampleLayer}`
  (sample_cmds.rs). Averages the square centred on the pixel, clipped to
  the canvas, alpha-weighted, in the document's colour model (Gray, Lab;
  CMYK documents use their composite RGB, since the profile round trip
  is not exact) and rounded to the document's bit depth.
- ui: eyedropper_ui.rs options bar; state.rs ToolOptions
  eyedropper_size / eyedropper_sample / eyedropper_ring (serde). The
  size is shared with the painting tools' Alt-click eyedropper, the
  Curves / Color Picker eyedroppers and the Info panel readout.
- control: ui.set eyedropperSampleSize / eyedropperSample /
  eyedropperRing; documented in control-protocol.md and the MCP schema.
- i18n: new strings in all 14 catalogs (plus the missing Russian hint
  the tl! scan had not reached).
- scorecard: TOOL-1649-1.
2026-10-09 12:28:14 +02:00
MarekSpodBiedry 6ba1419286 Layers panel fx drag test: measure the drop target before the mutable drag borrow (#1719) 2026-10-09 12:18:32 +02:00
MarekSpodBiedry b692ed451c Layers panel: drag layer effects onto another layer to move them, Alt-drag copies (#1719)
Effect rows only took clicks and the fx badge was part of the layer row, so
dragging an effect or the fx badge picked up nothing (or the whole layer).

As in Photoshop, dragging the fx badge or the "Effects" row onto another
layer moves all its effects there (replacing that layer's style, like Paste
Layer Style), dragging one effect row moves just that effect (replacing an
effect of the same kind), and holding Alt on release copies instead. The
badge takes the drag the way the eye does, so clicks still select the row.
The drop is one history step through a new engine command,
layer.layerStyle.transferEffects (no menu entry, like Show All Effects).

Tests: the engine command (copy, move one, move all, undo, bad params) and a
Layers panel test that Alt-drags an effect row and drags the fx badge.
2026-10-09 11:54:19 +02:00
MarekSpodBiedry fee28f3a1b xtask corpus: pass the pinned corpus without an explicit deref (clippy) (#948) 2026-10-09 11:34:11 +02:00
MarekSpodBiedry a5d92c231c fix(xtask): corpus --all --update-manifest refetches and rewrites every manifest (#948) 2026-10-09 10:42:10 +02:00
Claude Opus 5.5 f1433f4ab2 Compose: restore the Lab-mix flag instead of clearing it after a tile (#1112)
Rendering set the thread-local LAB_MIX to the document's value around each
tile, then set it to false. A nested rayon job (a gradient fill, say) can
let the same thread render another tile in the middle of an outer one;
clearing the flag there made the rest of the outer Lab tile mix in sRGB.
The issue's reproduction (a 4096 px Lab document with a gradient fill and
two 50 % fills, 60 renders, RAYON_NUM_THREADS=4) showed whole 256 px tiles
differing between identical renders.

psblend::with_lab_mix sets the flag, runs the closure, and restores the
previous value with a drop guard, as with_cmyk_space does for the CMYK
space. The three set/clear pairs in render_tiled_with use it.

The new test sets the flag, renders Lab and RGB documents on the single-
and multi-tile paths, and checks the flag is what it was. It failed before
the fix. The issue's reproduction, run twice each way on macOS with four
threads: before, 6 and 2 of 60 renders had one whole tile wrong (65536 px);
after, 0 of 60 both times.
2026-10-08 18:27:48 -04:00
940 changed files with 163955 additions and 11197 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
# cargo-nextest (https://nexte.st): runs every test in its own process, in parallel across test
# binaries. Optional for local runs; `cargo test` keeps working and stays what CI runs (#2204).
#
# cargo nextest run --workspace # all tests except doctests
# cargo test --doc --workspace # nextest does not run doctests
#
# GPU tests: each test is its own process here, so the in-process `gpu_lock()` mutexes no longer
# serialize them. Too many concurrent wgpu devices time out (`PollError: ... Wait timed out`), so
# this group caps them at 4.
[test-groups]
gpu = { max-threads = 4 }
[[profile.default.overrides]]
filter = 'package(photocraft-gpu) | (package(photocraft-ui-egui) & (kind(test) | test(/canvas|gpu|mip|type_tool/)))'
test-group = 'gpu'
+54
View File
@@ -39,6 +39,7 @@ jobs:
runs-on: ubuntu-latest
outputs:
os: ${{ steps.pick.outputs.os }}
web: ${{ steps.pick.outputs.web }}
steps:
- uses: actions/checkout@v4
with:
@@ -54,8 +55,17 @@ jobs:
all='["ubuntu-latest","windows-latest"]'
if [ "$EVENT" != pull_request ] || [ "$FULL" = true ]; then
echo "os=$all" >> "$GITHUB_OUTPUT"
echo "web=true" >> "$GITHUB_OUTPUT"
exit 0
fi
# The browser build (a fat-LTO wasm build) runs only when something it compiles or
# packages changed: the web app and its packaging, crate sources and manifests (the web
# build compiles nearly every crate), the workspace manifests and this workflow.
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/photocraft-web/|packaging/web/|packaging/env\.sh$|crates/[^/]+/(src/|Cargo\.toml$|build\.rs$)|Cargo\.(toml|lock)$|rust-toolchain(\.toml)?$|\.github/workflows/ci\.yml$)'; then
echo "web=true" >> "$GITHUB_OUTPUT"
else
echo "web=false" >> "$GITHUB_OUTPUT"
fi
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/|crates/(ui-egui|text|gpu|tablet|heif)/|Cargo\.lock$|(.*/)?build\.rs$|\.github/workflows/ci\.yml$)'; then
echo "os=$all" >> "$GITHUB_OUTPUT"
else
@@ -191,6 +201,50 @@ jobs:
- name: Check wasm-safe crates
run: cargo xtask wasm
web:
name: web build and wasm size gate
# PRs run it only when web-relevant files change (see `platforms`); main always does.
needs: platforms
if: needs.platforms.outputs.web == 'true'
runs-on: ubuntu-latest
env:
# Match release.yml so PR results reflect what would actually ship.
TRUNK_VERSION: 0.21.14
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@v2
with:
key: ci-web
save-if: ${{ github.ref == 'refs/heads/main' }}
cache-on-failure: true
- name: Install trunk
run: |
curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \
| tar -xz -C "$HOME/.cargo/bin" trunk
trunk --version
# package.sh runs Trunk's release build, validates relative URLs, checks the 24 MiB
# wasm limit and exercises the same packaging step used by release.yml.
- name: Build and verify browser release
run: packaging/web/package.sh
- name: Report wasm size
if: success()
run: |
{
echo "### Browser WebAssembly size"
echo
echo "| File | Bytes | MiB | Limit |"
echo "| --- | ---: | ---: | ---: |"
for wasm in dist/web/*.wasm; do
[ -f "$wasm" ] || continue
bytes=$(wc -c < "$wasm" | tr -d ' ')
mib=$(awk -v n="$bytes" 'BEGIN { printf "%.2f", n / 1048576 }')
echo "| $(basename "$wasm") | $bytes | $mib | 24 MiB |"
done
} >> "$GITHUB_STEP_SUMMARY"
fuzz:
name: fuzz (${{ matrix.target.crate }}/${{ matrix.target.name }})
# Placeholder: manual trigger only until a nightly schedule is enabled.
+7 -42
View File
@@ -19,47 +19,12 @@ concurrency:
jobs:
lint:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
verified-appimage-inputs:
name: Verified AppImage inputs
runs-on: ubuntu-latest
env:
ACTIONLINT_VERSION: 1.7.12
steps:
- uses: actions/checkout@v4
- name: Install tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends shellcheck desktop-file-utils appstream libxml2-utils python3-yaml
curl -fsSL "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" \
| tar -xz -C "$RUNNER_TEMP" actionlint
- name: actionlint
run: |
"$RUNNER_TEMP/actionlint" -color
- name: shellcheck
run: shellcheck packaging/*.sh packaging/*/*.sh packaging/linux/AppRun
- name: AppImage AppRun desktop integration
run: bash packaging/linux/apprun-test.sh
- name: PowerShell
shell: pwsh
run: |
foreach ($f in Get-ChildItem packaging/windows/*.ps1) {
$errors = $null
[System.Management.Automation.Language.Parser]::ParseFile($f.FullName, [ref]$null, [ref]$errors) | Out-Null
if ($errors) { $errors | ForEach-Object { Write-Output "::error file=$($f.Name)::$_" }; exit 1 }
Write-Output "ok $($f.Name)"
}
./packaging/windows/check-icons.ps1
- name: XML, desktop entry, AppStream, Flatpak manifest
run: |
xmllint --noout packaging/windows/photocraft.wxs packaging/macos/*.plist* packaging/linux/*.xml*
desktop-file-validate packaging/linux/ai.storyteller.photocraft.desktop
sed -e 's/@VERSION@/0.0.0/' -e 's/@DATE@/2026-01-01/' packaging/linux/ai.storyteller.photocraft.metainfo.xml.in >"$RUNNER_TEMP/ai.storyteller.photocraft.metainfo.xml"
appstreamcli validate --no-net --explain "$RUNNER_TEMP/ai.storyteller.photocraft.metainfo.xml"
python3 - <<'EOF'
import yaml
src = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.photocraft.yml"))
bundle = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml"))
for m in (src, bundle):
assert m["id"] == "ai.storyteller.photocraft" and m["command"] == "photocraft", m["id"]
for key in ("runtime", "runtime-version", "sdk", "finish-args"):
assert src[key] == bundle[key], f"Flatpak manifests disagree on {key}: {src[key]} vs {bundle[key]}"
print("Flatpak manifests ok")
EOF
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- run: bash packaging/linux/verified-download-test.sh
+17 -401
View File
@@ -1,9 +1,3 @@
# Release pipeline: every push to `release` builds signed installers for every platform and
# creates or updates the draft GitHub Release "PhotoCraft v<version>". See docs/releasing.md.
#
# All jobs run in the `release` environment (restricted to the `release` branch), which holds
# the signing secrets. Every secret is optional: missing ones produce unsigned artifacts and a
# warning, never a failed build.
name: Release
on:
@@ -17,405 +11,27 @@ on:
default: ""
permissions:
contents: read
contents: write
concurrency:
group: release-${{ github.ref }}
# Never cancel a run mid-notarization or mid-upload; a newer push waits its turn.
cancel-in-progress: false
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
PHOTOCRAFT_BUILD_SHA: ${{ github.sha }}
INPUT_VERSION: ${{ inputs.version }}
# craft-fonts (https://github.com/storytold/craft-fonts): shared font assets every release
# embeds (today the Japanese fonts). An optional build input for everyone else; see
# docs/development.md › Fonts. Bump deliberately; every desktop build job checks out this commit (not web).
CRAFT_FONTS_REF: abb83316d96aa59c1cf64784289e378fe9fa5695
jobs:
version:
name: version
runs-on: ubuntu-latest
# No `environment: release`: this job reads no secrets, so a branch dry run can run it.
outputs:
version: ${{ steps.v.outputs.version }}
date: ${{ steps.v.outputs.date }}
prerelease: ${{ steps.v.outputs.prerelease }}
steps:
- uses: actions/checkout@v4
- id: v
name: Resolve version
run: |
. packaging/env.sh
v="${INPUT_VERSION#v}"
v="${v:-$VERSION}"
if ! printf '%s' "$v" | grep -Eq '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'; then
echo "::error::'$v' is not a version like 1.2.3 or 1.2.3-rc.1"
exit 1
fi
case "$v" in *-*) pre=true ;; *) pre=false ;; esac
{
echo "version=$v"
echo "date=$(date -u +%Y-%m-%d)"
echo "prerelease=$pre"
} >>"$GITHUB_OUTPUT"
echo "### PhotoCraft v$v (\`${GITHUB_SHA::9}\`)" >>"$GITHUB_STEP_SUMMARY"
macos:
name: macOS universal
needs: version
runs-on: macos-15-xlarge # M2 Pro larger runner; use only in release.yml (actions_macos_xl budget caps spend)
environment: release
env:
PHOTOCRAFT_VERSION: ${{ needs.version.outputs.version }}
PHOTOCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- name: Check out craft-fonts (embedded fonts)
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
repository: storytold/craft-fonts
ref: ${{ env.CRAFT_FONTS_REF }}
path: craft-fonts
- uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-apple-darwin, x86_64-apple-darwin
- uses: Swatinem/rust-cache@v2
with:
key: release-macos-universal
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$PHOTOCRAFT_VERSION"
- name: Import signing certificate
env:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: packaging/macos/import-cert.sh
- name: Build, sign, notarize
env:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: packaging/macos/package.sh --arch universal
# Unpacks the CLI zip and checks the binary users get: Developer ID, hardened runtime,
# timestamp, and Gatekeeper's notarization lookup (codesign --verify, spctl). Also the DMG's
# stapled ticket. Strict when the signing secrets are present, warnings otherwise.
- name: Verify signatures and notarization
env:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: packaging/macos/verify.sh --arch universal
- uses: actions/upload-artifact@v4
with:
name: release-macos
path: dist/release/*
if-no-files-found: error
- name: Remove temporary keychain
if: always()
run: |
if [ -n "${MACOS_KEYCHAIN:-}" ]; then security delete-keychain "$MACOS_KEYCHAIN" || true; fi
windows:
name: Windows ${{ matrix.arch }}
needs: version
runs-on: windows-latest
environment: release
strategy:
fail-fast: false
matrix:
include:
- { arch: x64, target: x86_64-pc-windows-msvc }
- { arch: x86, target: i686-pc-windows-msvc }
# Windows on ARM: cross-compiled on the x64 runner, so signing and WiX run as above.
# .github/workflows/windows-arm64.yml installs and runs it on ARM64 hardware.
- { arch: arm64, target: aarch64-pc-windows-msvc }
env:
PHOTOCRAFT_VERSION: ${{ needs.version.outputs.version }}
PHOTOCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- name: Check out craft-fonts (embedded fonts)
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
repository: storytold/craft-fonts
ref: ${{ env.CRAFT_FONTS_REF }}
path: craft-fonts
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- uses: Swatinem/rust-cache@v2
with:
key: release-windows-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
shell: bash
run: cargo xtask version set "$PHOTOCRAFT_VERSION"
- name: Install WiX
shell: pwsh
run: dotnet tool install --global wix --version 5.0.2
- name: Build, sign, package
shell: pwsh
env:
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: ./packaging/windows/package.ps1 -Arch ${{ matrix.arch }}
- uses: actions/upload-artifact@v4
with:
name: release-windows-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
linux:
name: Linux ${{ matrix.arch }}
needs: version
# The oldest GitHub-hosted image, so the binaries only need glibc >= 2.35 (Ubuntu 22.04+,
# Debian 12+, Fedora 36+, RHEL 10). See docs/releasing.md.
runs-on: ${{ matrix.runner }}
# No `environment: release`: this job reads no secrets, so a branch dry run can run it.
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-22.04, deb: amd64 }
- { arch: aarch64, runner: ubuntu-22.04-arm, deb: arm64 }
env:
PHOTOCRAFT_VERSION: ${{ needs.version.outputs.version }}
PHOTOCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
NFPM_VERSION: 2.47.0
steps:
- uses: actions/checkout@v4
- name: Check out craft-fonts (embedded fonts)
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
repository: storytold/craft-fonts
ref: ${{ env.CRAFT_FONTS_REF }}
path: craft-fonts
- name: Install build and packaging tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev \
desktop-file-utils appstream python3-yaml zsync
curl -fsSL -o "$RUNNER_TEMP/nfpm.deb" \
"https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_${{ matrix.deb }}.deb"
sudo dpkg -i "$RUNNER_TEMP/nfpm.deb"
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
key: release-linux-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$PHOTOCRAFT_VERSION"
- name: Build and package (AppImage, deb, rpm, tar.gz)
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: packaging/linux/package.sh
- name: Check the packages
run: |
dpkg-deb --info dist/release/*.deb
dpkg-deb --contents dist/release/*.deb | grep -E 'usr/bin/photocraft$|metainfo|applications'
ldd target/release/photocraft
python3 -c "import yaml; m = yaml.safe_load(open('packaging/linux/flatpak/ai.storyteller.photocraft.yml')); assert m['id'] == 'ai.storyteller.photocraft'"
for appimage in dist/release/*.AppImage; do
chmod +x "$appimage"
APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --version
# Update information (#349) is embedded, and the .zsync for delta updates sits beside it.
"$appimage" --appimage-updateinformation | grep -F 'gh-releases-zsync|'
test -s "$appimage.zsync"
done
- uses: actions/upload-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
flatpak:
name: Flatpak ${{ matrix.arch }}
needs: [version, linux]
# Repackages the Linux job's tarball (the same binaries as the AppImage/deb/rpm); no Rust
# build here. 24.04 for a newer flatpak-builder (1.4) than 22.04 ships.
runs-on: ${{ matrix.runner }}
# No `environment: release`: this job signs nothing, so it gets no release secrets.
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-24.04 }
- { arch: aarch64, runner: ubuntu-24.04-arm }
env:
PHOTOCRAFT_VERSION: ${{ needs.version.outputs.version }}
PHOTOCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/linux
- name: Install flatpak-builder
run: |
sudo apt-get update
# librsvg2-common: the SVG pixbuf loader. flatpak-builder runs the host's
# `appstreamcli compose`, which renders the scalable icon and fails without it.
sudo apt-get install -y --no-install-recommends flatpak flatpak-builder librsvg2-common
# Ubuntu 24.04's AppArmor blocks the unprivileged user namespaces bubblewrap needs.
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
- name: Build the Flatpak bundle
run: packaging/linux/flatpak-bundle.sh "dist/linux/photocraft-$PHOTOCRAFT_VERSION-linux-${{ matrix.arch }}.tar.gz"
- uses: actions/upload-artifact@v4
with:
name: release-flatpak-${{ matrix.arch }}
path: dist/release/*.flatpak
if-no-files-found: error
freebsd:
name: FreeBSD x86_64
needs: version
# GitHub has no FreeBSD runners: build in a FreeBSD 14.3 VM, the same image and packages as
# .github/workflows/freebsd.yml.
runs-on: ubuntu-latest
timeout-minutes: 180
# No `environment: release`: this job signs nothing, so it gets no release secrets.
env:
PHOTOCRAFT_VERSION: ${{ needs.version.outputs.version }}
PHOTOCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- name: Check out craft-fonts (embedded fonts)
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
repository: storytold/craft-fonts
ref: ${{ env.CRAFT_FONTS_REF }}
path: craft-fonts
- name: Build and package in a FreeBSD VM (tar.gz)
# vmactions/freebsd-vm v1.5.9, pinned by commit (it runs our build).
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc
with:
release: "14.3"
usesh: true
cpu: 4
mem: 12288
# Passed into the VM by name; never templated into the script below.
envs: "PHOTOCRAFT_VERSION PHOTOCRAFT_BUILD_DATE PHOTOCRAFT_BUILD_SHA INPUT_VERSION"
# The FreeBSD CI packages, plus bash for the packaging script.
prepare: |
pkg install -y bash git curl pkgconf cmake python3 libxkbcommon wayland libX11 libXcursor libXrandr libXi libxcb mesa-libs vulkan-loader gtk3 fontconfig freetype2 alsa-lib
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
run: |
set -e
. "$HOME/.cargo/env"
git config --global --add safe.directory "$PWD"
# Build outside the checkout so only dist/ is copied back out of the VM (copying the
# target dir back fails on large builds). 4 jobs: more runs the VM out of memory.
export CARGO_TARGET_DIR=/var/tmp/photocraft-target CARGO_BUILD_JOBS=4
if [ -n "$INPUT_VERSION" ]; then cargo xtask version set "$PHOTOCRAFT_VERSION"; fi
# craft-fonts was checked out next to the sources and synced into the VM with them.
export CRAFT_FONTS_DIR="$PWD/craft-fonts" CRAFT_FONTS_REQUIRED=1
bash packaging/freebsd/package.sh
tar -tzf dist/release/photocraft-*-freebsd-x86_64.tar.gz \
| grep -E '/bin/photocraft$|/bin/photocraft-cli$|/share/applications/ai\.storyteller\.photocraft\.desktop$|/share/doc/photocraft/LICENSE-MIT$'
- uses: actions/upload-artifact@v4
with:
name: release-freebsd-x86_64
path: dist/release/*
if-no-files-found: error
web:
name: Web (wasm)
needs: version
runs-on: ubuntu-latest
# No `environment: release`: this job reads no secrets, so a branch dry run can run it.
env:
PHOTOCRAFT_VERSION: ${{ needs.version.outputs.version }}
PHOTOCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
TRUNK_VERSION: 0.21.14
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@v2
with:
key: release-web
- name: Install trunk
run: |
curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \
| tar -xz -C "$HOME/.cargo/bin" trunk
trunk --version
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$PHOTOCRAFT_VERSION"
# No craft-fonts here: the wasm32 build never embeds it (crates/text/build.rs), since even
# one Japanese font takes the wasm over packaging/web/package.sh's 24 MiB gate.
- name: Build and zip
run: packaging/web/package.sh
- uses: actions/upload-artifact@v4
with:
name: release-web
path: dist/release/*
if-no-files-found: error
release:
name: Draft GitHub Release
needs: [version, macos, windows, linux, flatpak, freebsd, web]
runs-on: ubuntu-latest
environment: release
permissions:
contents: write
env:
VERSION: ${{ needs.version.outputs.version }}
PRERELEASE: ${{ needs.version.outputs.prerelease }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
steps:
- uses: actions/download-artifact@v4
with:
pattern: release-*
path: artifacts
merge-multiple: true
- name: Checksums
working-directory: artifacts
run: |
sha256sum -- * | tee SHA256SUMS.txt
- name: Create or update the draft release
working-directory: artifacts
run: |
tag="v$VERSION"
title="PhotoCraft v$VERSION"
pre=()
if [ "$PRERELEASE" = true ]; then pre=(--prerelease); fi
if draft="$(gh release view "$tag" --json isDraft --jq .isDraft 2>/dev/null)"; then
if [ "$draft" != "true" ]; then
echo "::error::Release $tag is already published. Bump the version (cargo xtask version set) before pushing to release."
exit 1
fi
echo "Updating draft $tag: replacing its assets"
gh release view "$tag" --json assets --jq '.assets[].name' | while read -r asset; do
gh release delete-asset "$tag" "$asset" --yes
done
gh release edit "$tag" --draft --title "$title" --target "$GITHUB_SHA" --prerelease="$PRERELEASE"
gh release upload "$tag" --clobber -- *
else
echo "Creating draft $tag"
gh release create "$tag" --draft --title "$title" --target "$GITHUB_SHA" --generate-notes "${pre[@]}" -- *
fi
{
echo "Draft release **$title** at \`${GITHUB_SHA::9}\`:"
echo
sed 's/^/ /' SHA256SUMS.txt
} >>"$GITHUB_STEP_SUMMARY"
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
app-name: photocraft
app-title: PhotoCraft
craft-fonts-ref: abb83316d96aa59c1cf64784289e378fe9fa5695
version: ${{ inputs.version }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
+6 -66
View File
@@ -22,70 +22,10 @@ concurrency:
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
jobs:
package:
name: package (cross-compiled on x64)
runs-on: windows-latest
timeout-minutes: 90
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@89b12181fb390509a0842a86cc55eeb8eb928c1d # stable
with:
targets: aarch64-pc-windows-msvc
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
key: windows-arm64-package
- name: Install WiX
shell: pwsh
run: dotnet tool install --global wix --version 5.0.2
- name: Build and package (unsigned)
shell: pwsh
env:
DIST: ${{ github.workspace }}\dist\arm64
run: ./packaging/windows/package.ps1 -Arch arm64
- uses: actions/upload-artifact@v4
with:
name: photocraft-windows-arm64
path: dist/arm64/*
if-no-files-found: error
retention-days: 7
install:
name: install and run on ARM64
needs: package
runs-on: windows-11-arm
timeout-minutes: 30
steps:
- uses: actions/download-artifact@v4
with:
name: photocraft-windows-arm64
path: dist
- name: Install the MSI, check it, run it, uninstall it
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$msi = (Get-ChildItem dist/*.msi | Select-Object -First 1).FullName
$p = Start-Process msiexec.exe -ArgumentList '/i', "`"$msi`"", '/qn', '/l*v', 'install.log' -Wait -PassThru
if ($p.ExitCode -ne 0) { Get-Content install.log -Tail 60; throw "msiexec /i exited $($p.ExitCode)" }
$dir = Join-Path $env:ProgramFiles 'PhotoCraft'
foreach ($exe in 'photocraft.exe', 'photocraft-cli.exe') {
$path = Join-Path $dir $exe
if (-not (Test-Path $path)) { throw "$exe not installed in $dir" }
$bytes = [System.IO.File]::ReadAllBytes($path)
$machine = [BitConverter]::ToUInt16($bytes, [BitConverter]::ToInt32($bytes, 0x3C) + 4)
if ($machine -ne 0xAA64) { throw "$exe is for machine 0x$('{0:X}' -f $machine), not ARM64" }
Write-Output "ok $path (ARM64)"
}
# The installed CLI runs natively on ARM64.
$cli = Join-Path $dir 'photocraft-cli.exe'
$out = & $cli --version 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) { Write-Output $out; throw "photocraft-cli --version exited $LASTEXITCODE" }
Write-Output "ok photocraft-cli --version: $($out.Trim())"
$p = Start-Process msiexec.exe -ArgumentList '/x', "`"$msi`"", '/qn' -Wait -PassThru
if ($p.ExitCode -ne 0) { throw "msiexec /x exited $($p.ExitCode)" }
if (Test-Path (Join-Path $dir 'photocraft.exe')) { throw 'uninstall left photocraft.exe behind' }
Write-Output 'ok uninstalled'
windows-arm64:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main
with:
app-name: photocraft
app-dir: PhotoCraft
+18 -10
View File
@@ -1,6 +1,6 @@
# AGENTS.md: guide for AI agents and contributors
PhotoCraft is an open-source, native, Photoshop-comparable image editor written in **Rust only** (no JavaScript or TypeScript). **No Tauri, Electron or webview shells:** the desktop app is native egui/eframe on wgpu, and the web build is the same Rust compiled to WebAssembly (trunk + wasm-bindgen). Never add Tauri (or any webview/JS UI framework) as a dependency, build step or packaging target. The product name is always written **PhotoCraft** (`{Function}Craft` in PascalCase, like its siblings ArtCraft, ArtCraftX, DesignCraft, VectorCraft, EffectCraft, FilmCraft, LightCraft, PdfCraft) in user-facing text: UI, window titles, About, installers, release names, docs prose. Machine names stay lowercase: crates (`photocraft-*`), binaries, file names, ids (`ai.storyteller.photocraft`). Standards and learnings shared across the crafting apps live in `../craftrules` (read its `README.md`; the repository is not public — outside contributors should ask a maintainer for the standards relevant to their change). Contribute reusable learnings there, never code; repos don't share code. The goal is 1:1 Photoshop parity (same menus, shortcuts, behaviour and file fidelity) with better performance, and every feature drivable by agents. Read this file first, then `docs/`.
PhotoCraft is an open-source, native, Photoshop-comparable image editor written in **Rust only** (no JavaScript or TypeScript). **No Tauri, Electron or webview shells:** the desktop app is native egui/eframe on wgpu, and the web build is the same Rust compiled to WebAssembly (trunk + wasm-bindgen). Never add Tauri (or any webview/JS UI framework) as a dependency, build step or packaging target. The product name is always written **PhotoCraft** (`{Function}Craft` in PascalCase, like its siblings ArtCraft, ArtCraftX, DesignCraft, VectorCraft, EffectCraft, FilmCraft, LightCraft, PdfCraft) in user-facing text: UI, window titles, About, installers, release names, docs prose. Machine names stay lowercase: crates (`photocraft-*`), binaries, file names, ids (`ai.storyteller.photocraft`). Standards and learnings shared across the crafting apps live in `../craftrules` (read its `README.md`; the repository is not public — outside contributors should ask a maintainer for the standards relevant to their change). Contribute reusable learnings there; shared Rust components live in [storytold/craft-libs](https://github.com/storytold/craft-libs) and are pinned by immutable git revision. UI libraries stay at L6. The goal is 1:1 Photoshop parity (same menus, shortcuts, behaviour and file fidelity) with better performance, and every feature drivable by agents. Read this file first, then `docs/`.
## 1. Orientation (5 minutes)
@@ -11,8 +11,12 @@ PhotoCraft is an open-source, native, Photoshop-comparable image editor written
| `docs/contributing.md` | Rules: clean-room, tests, layering, style, commits; the "add a command" checklist |
| `docs/control-protocol.md` | JSON control channel: how agents drive and screenshot the running app |
| `docs/ui-design.md` | Design tokens, themes, widgets, and how to match Photoshop's look |
| `docs/roadmap.md` | Honest parity assessment (where we're lacking, where we're going), milestones, **current focus** |
| `docs/parity.md` | Generated list of every Photoshop menu item, live or missing |
| `ROADMAP.md` | One-page summary: stage, the two parity numbers, every dimension, languages, what's next |
| `docs/target-app-parity.md` | The authoritative parity assessment against Photoshop 2026: numbers, weights, evidence, hours |
| `docs/gaps.md` | Every known shortfall, ranked: the work list to pick from |
| `docs/roadmap.md` | Milestones, **current focus**, what's next with estimates |
| `docs/ui-parity.md`, `docs/brush-parity.md`, `docs/context-menu-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md` | Per-dimension parity checklists |
| `docs/parity-checklist.md` | Generated list of every Photoshop menu item, live or missing |
| `docs/scorecard.md` | Generated scorecard: performance budgets and numbers, corpus floors, per-area checklists (tools, files, UI, type, automation, reliability, distribution), settings that do nothing |
| `crates/<name>/README.md` (where present) | Public API of that crate |
| [photocraft-corpus](https://github.com/storytold/photocraft-corpus) + `docs/development.md` › Test corpora | Real-file test oracles (our Photoshop-authored PSDs); with psd-tools, ag-psd and PngSuite fetched into `corpus/` by `cargo xtask corpus --all` at the pins in `xtask/src/corpus_pins.rs` |
@@ -70,15 +74,16 @@ People trust PhotoCraft with their work, and a crash loses it. A malformed file,
Priorities: important infrastructure first, then low-hanging parity, then the long tail.
0. **Read `docs/roadmap.md` → "Honest parity assessment" first.** It says, dimension by dimension,
where PhotoCraft is lacking and the priority order of where we're going. `docs/parity.md`
(menu wiring) is not a measure of behaviour. When your work moves a measured number (PSD oracle,
round trips, workflow tests, performance), update that section with the dated figure.
0. **Read `ROADMAP.md`, then `docs/gaps.md`.** `docs/target-app-parity.md` says, dimension by
dimension, where PhotoCraft is lacking; `docs/gaps.md` ranks the work. `docs/parity-checklist.md`
(menu wiring) is not a measure of behaviour. When your work moves a number or closes a gap,
update the parity doc and gap entry it belongs to, with the date, and bump their status line
and revision history (craftrules `standards/progress-docs.md`).
1. **Check `docs/scorecard.md`** before picking work: each area's `missing` and `partial` rows,
the performance scenarios that are over budget or not measurable yet, and the count of
settings that do nothing. Its numbers are measured; prefer them to estimates.
2. `docs/roadmap.md` → **Current focus**.
3. `cargo xtask parity` → `docs/parity.md` lists every missing menu item, grouped by menu. Low-hanging fruit is usually a missing command whose algorithm already exists in `algo`, `paint`, `vector` or `text`.
3. `cargo xtask parity` → `docs/parity-checklist.md` lists every missing menu item, grouped by menu. Low-hanging fruit is usually a missing command whose algorithm already exists in `algo`, `paint`, `vector` or `text`.
4. `log/devlog.md` → the "Still open" bullets of recent entries.
When parity rises, raise `FLOOR` in `crates/ui-egui/src/parity.rs` (never lower it).
@@ -90,7 +95,7 @@ cargo test -p <crates you touched>
cargo clippy -p <crates> --all-targets -- -D warnings
cargo xtask layers
cargo xtask wasm # if you touched L0–L6
cargo xtask parity # if you added commands; commit the regenerated docs/parity.md
cargo xtask parity # if you added commands; commit the regenerated docs/parity-checklist.md
cargo test -p photocraft-engine --test panic_hunt -- --ignored # if you added/changed commands: no panic on adversarial input (Rule 9)
cargo xtask scorecard # if you moved a number: flip the checklist row in scorecard/*.toml, raise a
# corpus floor, fix a dead preference, or meet a budget (then set enforce = true
@@ -99,6 +104,8 @@ cargo xtask perf --quick # if you touched a hot path; `cargo xtask perf --upd
cargo xtask test-corpus # if you touched psd, io, codecs, compose, gpu, text or format (or: --changed decides)
```
While iterating, run less and keep the full commands above as the final gate: `cargo test -p <crate> --lib --tests` skips the examples and doctests plain `cargo test` builds every time (ui-egui has 11 examples), and `cargo test -p <crate> --test <file>` runs one integration-test file. `cargo nextest run` runs tests in parallel across binaries; see `docs/development.md` › Faster test loops.
**Test corpora.** Real-file corpora live in `corpus/` (gitignored, never committed), fetched at pinned commits and sha256-verified by `cargo xtask corpus --all`: our Photoshop-authored oracles from https://github.com/storytold/photocraft-corpus plus psd-tools, ag-psd and PngSuite from their upstreams. Pins: `xtask/src/corpus_pins.rs`. The corpus tests are opt-in (cargo feature `corpus`): plain `cargo test` skips them, and with the feature on a missing corpus fails ("run `cargo xtask corpus --all`"). `cargo xtask test-corpus` fetches and runs them all. CI always runs them (the `corpus` job, cached by pin). Never commit corpus files; new oracles go to photocraft-corpus (its `AGENTS.md`), then a pin bump here. Details: `docs/development.md` › Test corpora.
Commands must **never panic** on bad input (Rule 9): every `run` closure and the code it calls returns `Err`, not a panic, for any params or document state. New commands come with a graceful-failure test (empty/out-of-range/wrong-type params → `Err`, not a crash).
@@ -117,7 +124,8 @@ Then append a terse entry to `log/devlog.md` (what landed, numbers, what's still
- `docs/roadmap.md`: milestones M0–M12, status and the current focus.
- `docs/parity.md`: generated Photoshop menu coverage.
- `ROADMAP.md`, `docs/target-app-parity.md`, `docs/gaps.md` and the `docs/*-parity.md` checklists: where we stand against Photoshop.
- `docs/parity-checklist.md`: generated Photoshop menu coverage.
- `docs/scorecard.md`: generated scorecard (sources: `scorecard/*.toml`, `perf/budgets.toml`, `perf/baseline.json`, corpus floors, prefs audit).
- `docs/releasing.md`: cutting a release (`cargo xtask version`, the `release` branch), signing secrets, packaging scripts in `packaging/`.
- `../craftrules/release/playbook.md`: how every storytold app builds signed release binaries (the canonical recipe; `docs/release-playbook.md` just points there); `docs/releasing.md` is PhotoCraft's specifics.
+23 -3
View File
@@ -14,21 +14,40 @@ next to them.
| `crates/ui-egui/src/i18n/de.tsv` | German UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/it.tsv` | Italian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/ko.tsv` | Korean UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/nl.tsv` | Dutch UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/pl.tsv` | Polish UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/pt-br.tsv` | Brazilian Portuguese UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/cs.tsv` | Czech UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
| `assets/icons/*.svg` except `slice-knife.svg`, `clip-below.svg`, `clip-release.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg` and `direct-select.svg` (109 files) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/{check,chevron-down,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,lock,minus,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/*.svg` except `slice-knife.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg` (113 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/sampler.svg` | Color Sampler tool glyph: a target reticle marking a sampled pixel | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/convert-point.svg` | Convert Point tool glyph: an angle with a square anchor on its apex, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/artboard.svg` | Artboard tool glyph: a board with a tick at each end of its edges | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/perspective-crop.svg` | Perspective Crop tool glyph: a crop frame in perspective with its grid and crop-mark ticks | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/type-mask.svg`, `assets/icons/type-mask-vertical.svg` | Horizontal and Vertical Type Mask tool glyphs: a T drawn as marching ants (the vertical one beside a downward arrow), on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/marquee-row.svg`, `assets/icons/marquee-column.svg` | Single Row and Single Column Marquee tool glyphs: a dashed row (column) between two edge bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/clip-below.svg`, `assets/icons/clip-release.svg` | Clipping-mask cursors (⌥ over the line between two layers): a hooked arrow onto the layer below; the same with a small "no" badge to release | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/layer-mask.svg`, `assets/icons/adjustment-layer.svg` | Layers panel footer glyphs: Add a mask (a frame around a solid disc) and New Fill or Adjustment Layer (a circle, one half solid), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/frame-placeholder.svg` | Frame tool glyph: an empty placeholder frame, crossed corner to corner | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/eraser-background.svg`, `assets/icons/eraser-magic.svg` | Background Eraser and Magic Eraser tool glyphs: Lucide `eraser` plus added marks | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/eraser.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/brush-replace.svg` | Color Replacement tool glyph: Lucide `brush` plus two swap arrows | Lucide Icons and Contributors; arrows by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/bandage-sparkle.svg` | Remove tool glyph: Lucide `bandage` moved down, plus a sparkle mark | Lucide Icons and Contributors; mark by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/bandage.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/direct-select.svg` | Direct Selection tool glyph: Lucide `mouse-pointer-2` plus an anchor square | Lucide Icons and Contributors; square by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/mouse-pointer-2.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/pen-freeform.svg`, `assets/icons/pen-curvature.svg` | Freeform Pen and Curvature Pen tool glyphs: Lucide `pen-tool` scaled down, plus a freehand squiggle or a curve through two points | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/pen-tool.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/pen-add-anchor.svg`, `assets/icons/pen-delete-anchor.svg` | Add Anchor Point and Delete Anchor Point tool glyphs: Lucide `pen-tool` plus a + or − mark | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/pen-tool.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/painting-symmetry.svg` | Painting symmetry glyph: Lucide `heart` with a central axis | Lucide Icons and Contributors; adapted by @shorbank | Derived from <https://github.com/lucide-icons/lucide> `icons/heart.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/symmetry-{vertical,horizontal,dual,diagonal}.svg` | Painting symmetry axis glyphs | @shorbank | Original work; supplied SVG line geometry centred on a common square canvas, stroke adjusted to match the painting-symmetry glyph | MIT OR Apache-2.0, [`assets/icons/LICENSE-symmetry-axes.txt`](assets/icons/LICENSE-symmetry-axes.txt) |
| `assets/icons/lasso-magnetic.svg` | Magnetic Lasso tool glyph, adapted from "Magnetic Lasso Tool" (redrawn on the 24 px toolbar grid) | Lil' Seal (Noun Project); adapted by PhotoCraft contributors | <https://thenounproject.com/icon/magnetic-lasso-tool-177513/> | CC BY 3.0, [`assets/icons/LICENSE-noun-magnetic-lasso.txt`](assets/icons/LICENSE-noun-magnetic-lasso.txt) |
| `assets/dict/en_US-scowl-50.txt.gz` | English word list for Check Spelling (SCOWL 2020.12.07, size 50, en_US; 72,403 words) | Kevin Atkinson and the SCOWL contributors | <http://wordlist.aspell.net/> | SCOWL license (permissive, keep the notice), [`assets/dict/LICENSE-SCOWL.txt`](assets/dict/LICENSE-SCOWL.txt), which also has the build recipe |
| `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft Coated CMYK (synthetic) ICC profile | PhotoCraft contributors (generated by `photocraft-cms`, `src/synth.rs`) | Original work, see [`crates/cms/README.md`](crates/cms/README.md) | CC0-1.0 |
| `assets/app-icon/` (all files) | PhotoCraft app icon (nine-tailed kitsune) | The project owner (drawn in ArtCraft, vectorised) | Original work, see [`assets/app-icon/README.md`](assets/app-icon/README.md) | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) |
| `packaging/macos/dmg/` (all files) | PhotoCraft DMG window background and layout | @XusBadia, from the PhotoCraft app icon | Original work, see [`packaging/macos/dmg/README.md`](packaging/macos/dmg/README.md) | MIT OR Apache-2.0, like the code |
| `crates/ui-egui/src/theme.rs` (Solarized Dark palette) | Solarized colour scheme used by the Solarized Dark theme | Ethan Schoonover | <https://ethanschoonover.com/solarized/> | MIT, [`LICENSE-solarized.txt`](crates/ui-egui/src/LICENSE-solarized.txt) |
| `crates/ui-egui/src/theme.rs` (Breeze Light and Breeze Dark themes) | The Breeze Light and Breeze Dark themes are original colour values on PhotoCraft's Studio layout, chosen to look close to KDE Plasma's Breeze (cool blue-greys, blue accent, 5 px frame radius) so the app blends into a Plasma desktop. None of Breeze's colour values, files or code are copied; the values are a few levels away from its schemes and tuned for text contrast | PhotoCraft contributors | Inspired by the look of KDE Breeze, <https://invent.kde.org/plasma/breeze> (its colour schemes are LGPL-2.0-or-later) | Original work |
### Optional build input: craft-fonts (not files in this repo)
@@ -84,7 +103,8 @@ next to the files:
| `corpus/psd/` (170 files) | Small selection of the psd-tools and ag-psd test files | Kota Yamaguchi; Agamnentzar | psd-tools (above) and [ag-psd `test/`](https://github.com/Agamnentzar/ag-psd/tree/master/test) | MIT (both) |
| `corpus/heif/` (9 files, 0.1 MB) | HEIC/HEIF test files: `heic-rs/` checkerboards, RGB strips and a grid-tiled photo with EXIF and XMP (synthetic pixels encoded by macOS `sips`, each `.ref.png` Apple's decode); `pillow-heif/` the 10-bit RGBA `RGBA_10__29x100.heif` and its source `RGBA_16__29x100.png` | Thomas Braun (heic-rs); Pillow-Heif contributors | [heic-rs `tests/fixtures`](https://github.com/tbraun96/heic-rs/tree/main/tests/fixtures), [pillow-heif `tests/images`](https://github.com/bigcat88/pillow_heif/tree/master/tests/images) | MIT OR Apache-2.0 (heic-rs); BSD-3-Clause (pillow-heif) |
| `corpus/exr/` (5 files, 2.3 MB) | The deep OpenEXR test images `11`, `42`, `64`, `multivariate` and `objectid.deep.exr` | Contributors to the OpenEXR Project | [openexr `src/test/bin/test_images`](https://github.com/AcademySoftwareFoundation/openexr/tree/main/src/test/bin/test_images) | BSD-3-Clause |
| `corpus/affinity/` (21 files, 2.4 MB) | Public Affinity documents, unmodified: `vector-art/` (9), `afdesignload/` (9), `jac21/` (2) and `asset-store-template/` (1), each with its upstream licence next to it | samuel-etver; Nick Beeuwsaert; Jeremy Cantu; DAIKI (eviltwo) | [vector-art `simple/`](https://github.com/samuel-etver/vector-art/tree/255f8add3c8f0740196e22bd59502b811b532f0b/simple), [AFDesignLoad `testDesigns/`](https://github.com/NickBeeuwsaert/AFDesignLoad/tree/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns), [Jac21/Branding `Logos/JC/DesignerFiles/Affinity`](https://github.com/Jac21/Branding/tree/57ae3f45bf4637f6927c0b07de25b922c55f944f/Logos/JC/DesignerFiles/Affinity), [AssetStoreTemplate `AssetStoreTemplate/`](https://github.com/eviltwo/AssetStoreTemplate/tree/f671981ee89d15526285b3cc87b4393d3defe644/AssetStoreTemplate) | CC0-1.0 (vector-art); MIT, Copyright (c) 2015 Nick Beeuwsaert; MIT, Copyright (c) 2018 Jeremy Cantu; MIT, Copyright (c) 2024 DAIKI |
| `corpus/affinity/` (60 files) | Public Affinity documents and PNG references: `vector-art/` (9 documents), `afdesignload/` (9), `jac21/` (2), `asset-store-template/` (1), and `affinity-samples/` (18 CC0 documents plus exported references) | samuel-etver; Nick Beeuwsaert; Jeremy Cantu; DAIKI (eviltwo); satoshoe-dev | [vector-art `simple/`](https://github.com/samuel-etver/vector-art/tree/255f8add3c8f0740196e22bd59502b811b532f0b/simple), [AFDesignLoad `testDesigns/`](https://github.com/NickBeeuwsaert/AFDesignLoad/tree/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns), [Jac21/Branding `Logos/JC/DesignerFiles/Affinity`](https://github.com/Jac21/Branding/tree/57ae3f45bf4637f6927c0b07de25b922c55f944f/Logos/JC/DesignerFiles/Affinity), [AssetStoreTemplate `AssetStoreTemplate/`](https://github.com/eviltwo/AssetStoreTemplate/tree/f671981ee89d15526285b3cc87b4393d3defe644/AssetStoreTemplate), [affinity-samples](https://github.com/satoshoe-dev/affinity-samples/tree/96aca6bd86bbe7a677f1cf0630bd832d23943be8) | CC0-1.0 (vector-art and affinity-samples); MIT, Copyright (c) 2015 Nick Beeuwsaert; MIT, Copyright (c) 2018 Jeremy Cantu; MIT, Copyright (c) 2024 DAIKI |
| `corpus/pngsuite/` | PngSuite | Willem van Schaik | <http://www.schaik.com/pngsuite/> | Public domain |
| `corpus/pixls/` (7 files, 226 MB) | Real camera raws, one per decode path: Canon PowerShot SX50 HS (CR2 and its DNG conversion), Nikon D3 uncompressed NEF, Sony DSC-RX0 cRAW ARW, Panasonic DC-G9 high-res RW2, Olympus E-1 GRBG ORF, plus the E-5 packed ORF as the documented known-unsupported case. Per file (each CC0, per its database entry): [IMG_4059.CR2](https://raw.pixls.us/data/Canon/PowerShot%20SX50%20HS/IMG_4059.CR2), [CRW_4061.DNG](https://raw.pixls.us/data/Canon/PowerShot%20SX50%20HS/CRW_4061.DNG), [JD1_8203.NEF](https://raw.pixls.us/data/Nikon/D3/JD1_8203.NEF), [DSC00009.ARW](https://raw.pixls.us/data/Sony/DSC-RX0/DSC00009.ARW), [P1000475.RW2](https://raw.pixls.us/data/Panasonic/DC-G9/P1000475.RW2), [E_1__C106743_gredos.ORF](https://raw.pixls.us/data/Olympus/E-1/E_1__C106743_gredos.ORF), [_7061961_copy.ORF](https://raw.pixls.us/data/Olympus/E-5/_7061961_copy.ORF) | The photographers of the pixls.us raw samples database | [raw.pixls.us](https://raw.pixls.us) `data/`, fetched per [xtask/src/corpus_pins.rs](xtask/src/corpus_pins.rs) | CC0 / public domain, per file as linked |
Files copied into `corpus/` by hand (tiff, exr, raw) must be MIT, BSD or CC0.
Generated
+268 -29
View File
@@ -164,6 +164,21 @@ dependencies = [
"equator",
]
[[package]]
name = "alloc-no-stdlib"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
[[package]]
name = "alloc-stdlib"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
dependencies = [
"alloc-no-stdlib",
]
[[package]]
name = "allocator-api2"
version = "0.2.21"
@@ -670,6 +685,16 @@ dependencies = [
"piper",
]
[[package]]
name = "brotli-decompressor"
version = "5.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
]
[[package]]
name = "built"
version = "0.8.1"
@@ -1096,6 +1121,15 @@ dependencies = [
"libc",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5c874d51eeb3de70e735c8ce87a59a7dedd47675#5c874d51eeb3de70e735c8ce87a59a7dedd47675"
dependencies = [
"egui",
"serde",
]
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -2737,6 +2771,184 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "jxl-bitstream"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe"
dependencies = [
"tracing",
]
[[package]]
name = "jxl-coding"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c"
dependencies = [
"jxl-bitstream",
"tracing",
]
[[package]]
name = "jxl-color"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-image",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-frame"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-grid"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb"
dependencies = [
"tracing",
]
[[package]]
name = "jxl-image"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565"
dependencies = [
"jxl-bitstream",
"jxl-grid",
"jxl-oxide-common",
"tracing",
]
[[package]]
name = "jxl-jbr"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46"
dependencies = [
"brotli-decompressor",
"jxl-bitstream",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-modular"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-oxide"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3"
dependencies = [
"brotli-decompressor",
"jxl-bitstream",
"jxl-color",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-jbr",
"jxl-oxide-common",
"jxl-render",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-oxide-common"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b"
dependencies = [
"jxl-bitstream",
]
[[package]]
name = "jxl-render"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19"
dependencies = [
"bytemuck",
"jxl-bitstream",
"jxl-coding",
"jxl-color",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-threadpool"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3"
dependencies = [
"rayon",
"rayon-core",
"tracing",
]
[[package]]
name = "jxl-vardct"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "keyboard-types"
version = "0.8.3"
@@ -3970,7 +4182,7 @@ dependencies = [
[[package]]
name = "photocraft"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"arboard",
"async-io",
@@ -3987,6 +4199,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"open",
"photocraft-automation",
"photocraft-cms",
"photocraft-codecs",
"photocraft-color",
"photocraft-compose",
@@ -4011,7 +4224,7 @@ dependencies = [
[[package]]
name = "photocraft-affinity"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"crc32fast",
"flate2",
@@ -4021,7 +4234,7 @@ dependencies = [
[[package]]
name = "photocraft-algo"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4034,7 +4247,7 @@ dependencies = [
[[package]]
name = "photocraft-automation"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"base64",
"cap-std",
@@ -4056,7 +4269,7 @@ dependencies = [
[[package]]
name = "photocraft-cli"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"photocraft-automation",
"photocraft-codecs",
@@ -4070,7 +4283,7 @@ dependencies = [
[[package]]
name = "photocraft-cms"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"moxcms",
"rayon",
@@ -4078,7 +4291,7 @@ dependencies = [
[[package]]
name = "photocraft-codecs"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"exr",
"flate2",
@@ -4090,6 +4303,7 @@ dependencies = [
"png 0.18.1",
"proptest",
"rayon",
"serde_json",
"thiserror 2.0.21",
"tiff",
"zune-core 0.5.3",
@@ -4098,7 +4312,7 @@ dependencies = [
[[package]]
name = "photocraft-color"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"photocraft-cms",
"serde",
@@ -4106,7 +4320,7 @@ dependencies = [
[[package]]
name = "photocraft-compose"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"criterion",
"photocraft-color",
@@ -4121,7 +4335,7 @@ dependencies = [
[[package]]
name = "photocraft-doc"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4132,9 +4346,10 @@ dependencies = [
[[package]]
name = "photocraft-engine"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"blake3",
"exr",
"flate2",
"photocraft-affinity",
"photocraft-algo",
@@ -4155,15 +4370,17 @@ dependencies = [
"photocraft-text",
"photocraft-vector",
"rayon",
"roxmltree",
"serde",
"serde_json",
"tempfile",
"thiserror 2.0.21",
"wat",
]
[[package]]
name = "photocraft-format"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"blake3",
"flate2",
@@ -4182,14 +4399,14 @@ dependencies = [
[[package]]
name = "photocraft-geom"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"serde",
]
[[package]]
name = "photocraft-gpu"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"half",
"log",
@@ -4206,14 +4423,14 @@ dependencies = [
[[package]]
name = "photocraft-heif"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"heic-rs",
]
[[package]]
name = "photocraft-io"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"blake3",
"crc32fast",
@@ -4235,20 +4452,21 @@ dependencies = [
"photocraft-vector",
"proptest",
"resvg",
"roxmltree",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "photocraft-ops"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"photocraft-doc",
]
[[package]]
name = "photocraft-paint"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4259,7 +4477,7 @@ dependencies = [
[[package]]
name = "photocraft-plugins"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4274,7 +4492,7 @@ dependencies = [
[[package]]
name = "photocraft-psd"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"flate2",
"photocraft-psd",
@@ -4285,7 +4503,7 @@ dependencies = [
[[package]]
name = "photocraft-raster"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4295,16 +4513,22 @@ dependencies = [
[[package]]
name = "photocraft-raw"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"flate2",
"image",
"jxl-oxide",
"photocraft-raw",
"png 0.18.1",
"rayon",
"zune-core 0.5.3",
"zune-jpeg 0.5.15",
"zune-jpegxl",
]
[[package]]
name = "photocraft-tablet"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"block2 0.6.2",
"objc2 0.6.4",
@@ -4316,7 +4540,7 @@ dependencies = [
[[package]]
name = "photocraft-testkit"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"memory-stats",
"photocraft-color",
@@ -4327,7 +4551,7 @@ dependencies = [
[[package]]
name = "photocraft-text"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"flate2",
"parley",
@@ -4341,13 +4565,15 @@ dependencies = [
[[package]]
name = "photocraft-ui-egui"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"base64",
"craft-ui",
"eframe",
"egui",
"egui_extras",
"egui_kittest",
"flate2",
"log",
"photocraft-algo",
"photocraft-cms",
@@ -4373,11 +4599,12 @@ dependencies = [
"serde_json",
"sys-locale",
"toml",
"winsafe",
]
[[package]]
name = "photocraft-vector"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"photocraft-color",
"photocraft-doc",
@@ -4388,7 +4615,7 @@ dependencies = [
[[package]]
name = "photocraft-web"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"eframe",
"egui",
@@ -4398,8 +4625,11 @@ dependencies = [
"photocraft-doc",
"photocraft-engine",
"photocraft-io",
"photocraft-paint",
"photocraft-psd",
"photocraft-ui-egui",
"rfd",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
@@ -7218,7 +7448,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xtask"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"serde",
"serde_json",
@@ -7487,6 +7717,15 @@ dependencies = [
"zune-core 0.5.3",
]
[[package]]
name = "zune-jpegxl"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
dependencies = [
"zune-core 0.5.3",
]
[[package]]
name = "zvariant"
version = "5.15.0"
+26 -5
View File
@@ -4,12 +4,13 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"]
[workspace.package]
version = "0.5.0"
version = "0.7.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
[workspace.dependencies]
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }
# internal
photocraft-geom = { path = "crates/geom" }
photocraft-color = { path = "crates/color" }
@@ -44,6 +45,9 @@ arc-swap = "1"
bytemuck = { version = "1", features = ["derive"] }
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
image = { version = "0.25", default-features = false }
# Baseline-JPEG decode of lossy DNG tiles (compression 34892), shared with zune-jpeg.
zune-core = "0.5"
zune-jpeg = "0.5"
proptest = "1"
eframe = { version = "0.36", default-features = false }
egui = "0.36"
@@ -66,6 +70,10 @@ opt-level = 2
[profile.dev]
opt-level = 1
# Line tables keep file:line in panic backtraces but drop variable info, which roughly halves link
# time and PDB size for the ~260 test binaries (#2204). CI sets the same through
# CARGO_PROFILE_DEV_DEBUG. To inspect locals in a debugger, build with CARGO_PROFILE_DEV_DEBUG=true.
debug = "line-tables-only"
[profile.release]
lto = "thin"
@@ -73,11 +81,10 @@ codegen-units = 1
# The browser build (apps/photocraft-web, `data-cargo-profile` in its index.html). Hosts cap the
# size of a single file (Cloudflare Pages/Workers: 25 MiB), and the wasm is downloaded on every
# visit, so this profile optimizes for size: fat LTO, and opt-level "s" for everything except the
# pixel-processing crates, which keep opt-level 3 so filters and compositing stay fast. panic
# visit, so this profile optimizes for size: fat LTO, opt-level "z" for the UI, command, and I/O
# shells, and "s" for other crates except pixel processing, which keeps opt-level 3. panic
# stays the target default (wasm32-unknown-unknown aborts; AGENTS.md's `panic = "unwind"` is for
# the native app shell). packaging/web/package.sh fails the build above 24 MiB. Issue #198:
# this took the wasm from 26.3 MiB (release profile) to 18.8 MiB.
# the native app shell). packaging/web/package.sh fails the build above 24 MiB.
[profile.wasm-release]
inherits = "release"
opt-level = "s"
@@ -88,6 +95,20 @@ strip = "debuginfo"
[profile.wasm-release.package."*"]
opt-level = "s"
# Keep the browser shell compact as shared panel controls grow. Pixel-processing crates below
# retain their speed-oriented optimization level.
[profile.wasm-release.package.photocraft-ui-egui]
opt-level = "z"
# Keep browser command dispatch, import/export glue, and the entry point compact. Native
# builds and the speed-oriented pixel-processing overrides below retain their settings.
[profile.wasm-release.package.photocraft-engine]
opt-level = "z"
[profile.wasm-release.package.photocraft-io]
opt-level = "z"
[profile.wasm-release.package.photocraft-web]
opt-level = "z"
[profile.wasm-release.package.photocraft-raster]
opt-level = 3
[profile.wasm-release.package.photocraft-color]
+9 -7
View File
@@ -133,7 +133,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off
<br>
<sub>A badge made of shape layers: a gradient-filled lotus, a star and a dotted ring.<br><i>Water Lilies</i>, Claude Monet, 1906</sub>
<h3>Pixel-perfect vectors</h3>
Rectangle, Ellipse, Triangle, Polygon, Line and the Pen tool, with resolution-independent shape layers, gradient fills, and dashed, aligned strokes.
Rectangle, Ellipse, Triangle, Polygon, Line and the Pen, Freeform Pen and Curvature Pen tools, with resolution-independent shape layers, gradient fills, and dashed, aligned strokes.
<br><br>
Combine shapes (unite, subtract, intersect, exclude), keep paths in the Paths panel, use them as vector masks, or stroke and fill them. 116 of 116 shape layers in our PSD corpus match Photoshop's pixels.
</td>
@@ -178,8 +178,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
<table>
<tr>
<td width="33%" valign="top">
<h4>🧰 52 tools</h4>
Move · Rectangular and Elliptical Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Slice · Slice Select · Eyedropper · Ruler · Note · Count · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Clone Stamp · Pattern Stamp · History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Horizontal and Vertical Type · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom
<h4>🧰 67 tools</h4>
Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom
</td>
<td width="33%" valign="top">
<h4>🖌️ A real brush engine</h4>
@@ -187,7 +187,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off
</td>
<td width="33%" valign="top">
<h4>🗃️ Layers, done properly</h4>
Groups, clipping masks, pixel and vector masks, fill layers (solid, gradient and pattern), adjustment layers, live smart objects with smart filters and lossless transforms and warps, multi-layer selection with align, distribute and link, alpha channels and Quick Mask, 27 blend modes, opacity and fill, locks, colour labels, layer filters, merge, flatten, rasterize, Layer via Copy/Cut, Paste Into.
Groups, clipping masks, pixel and vector masks, fill layers (solid, gradient and pattern), adjustment layers, live smart objects with smart filters and lossless transforms and warps, multi-layer selection with align, distribute and link, alpha channels and Quick Mask, 27 Photoshop blend modes plus six Paint.NET variants, opacity and fill, locks, colour labels, layer filters, merge, flatten, rasterize, Layer via Copy/Cut, Paste Into.
</td>
</tr>
<tr>
@@ -199,11 +199,11 @@ Every screenshot here is the real app at work on public-domain art, rendered off
</td>
<td width="33%" valign="top">
<h4>🗂️ Formats</h4>
PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and AVIF, with symmetric read and write at 8, 16 and 32 bits, HEIC photos from iPhone and Mac (read; in official builds, an optional <code>--features heif</code> build feature), and the native <code>.pcraft</code> format. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.
PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), <a href="docs/pdn.md">Paint.NET PDN3 (read, with editable layers and all 14 blend modes)</a>, <a href="docs/ora.md">OpenRaster (read and write, with layers, groups and blend modes, for Krita, MyPaint and GIMP)</a>, SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and FITS (astronomy images: 8/16-bit and 32-bit float, gray or RGB, header kept), and the native <code>.pcraft</code> format. Flat formats retain the depths they support: PNG keeps 8/16-bit samples, TIFF keeps 8/16-bit and 32-bit float samples, and OpenEXR keeps half/float samples; JPEG, WebP and the other 8-bit formats reduce higher-depth samples with an export warning. See the <a href="crates/codecs/README.md#capability-matrix-default-build">codec capability matrix</a> for each format. HEIC photos from iPhone and Mac are read-only (included in official builds; optional <code>--features heif</code> for source builds). AVIF is write-only with the optional <code>avif</code> build feature; AVIF decoding and JPEG XL are unavailable. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.
</td>
<td width="33%" valign="top">
<h4>🪄 The everyday essentials</h4>
Auto Tone, Contrast and Color · Equalize · Image and Canvas Size · Crop and Trim · Reveal All · Edit › Fill and Stroke · Copy Merged · Paste in Place · guides, rulers, grid and snapping · Actions record and replay · a command palette (⌘K).
Auto Tone, Contrast and Color · Equalize · Image and Canvas Size · Crop and Trim · Reveal All · Edit › Fill and Stroke · Copy Merged · Paste in Place · guides, rulers, grid and snapping · Actions record and replay · a command palette (⌘F).
</td>
</tr>
</table>
@@ -298,7 +298,7 @@ photocraft
Maintainers: [`docs/releasing.md`](docs/releasing.md) explains how releases are built, signed and published.
> [!IMPORTANT]
> **Status:** PhotoCraft is in early alpha, and we want to be straight about where it stands: much of Photoshop's feature surface exists in some form, but **it is not yet a Photoshop replacement for daily professional work**. The biggest gaps are AI/generative features, about twenty missing tools, depth in typography and pro workflows, and plug-in compatibility. Every Photoshop menu item is wired to a command ([`docs/parity.md`](docs/parity.md)), but that measures wiring, not behaviour. The honest, dimension-by-dimension picture and where we're going next are in the [roadmap's parity assessment](docs/roadmap.md#honest-parity-assessment-2026-10-05). Expect rough edges, and please file issues (include your OS, document size, layer count and a screenshot). You can also tell us what broke on [Discord](https://discord.gg/artcraft).
> **Status:** PhotoCraft is in early alpha, and we want to be straight about where it stands: much of Photoshop's feature surface exists in some form, but **it is not yet a Photoshop replacement for daily professional work**. The biggest gaps are AI/generative features, 15 missing tools, depth in typography and pro workflows, and plug-in compatibility. Every Photoshop menu item is wired to a command ([`docs/parity-checklist.md`](docs/parity-checklist.md)), but that measures wiring, not behaviour. The honest, dimension-by-dimension picture and where we're going next are in the [roadmap](ROADMAP.md) and [parity assessment](docs/target-app-parity.md). Expect rough edges, and please file issues (include your OS, document size, layer count and a screenshot). You can also tell us what broke on [Discord](https://discord.gg/artcraft).
## Documentation
@@ -350,6 +350,8 @@ Installers and executables are code-signed.
| Fedora/RHEL/openSUSE | `photocraft-<ver>-linux-x86_64.rpm` | `photocraft-<ver>-linux-aarch64.rpm` | |
| Tarball | `photocraft-<ver>-linux-x86_64.tar.gz` | `photocraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
RISC-V (riscv64): `photocraft-<ver>-linux-riscv64.tar.gz` only, built against Ubuntu 24.04 (needs glibc 2.39+).
### FreeBSD
| Build | File |
+142
View File
@@ -0,0 +1,142 @@
# PhotoCraft roadmap
**Stage: alpha** · next: beta, ~30 points (ready for real work ~45% → ~75%, with reliable PSD) and ~1,100–1,800 h away
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-11 · **Change:** minor (toolbox count 56 of 68, 12 missing) · **Target:** Adobe Photoshop 2026
PhotoCraft's one-page summary of how close it is to Adobe Photoshop 2026 (27.11.0, measured from
the installed app on 2026-10-10) at version 0.6.0. Detail: [target-app parity](docs/target-app-parity.md)
(methodology, weights, evidence), [gaps](docs/gaps.md) (the ranked work list),
[roadmap](docs/roadmap.md) (milestones, current focus), [scorecard](docs/scorecard.md) and
[menu checklist](docs/parity-checklist.md) (both generated and measured),
[architecture](docs/architecture.md).
Hours are Opus 5.5 agent wall-clock hours for one agent working sequentially, calibrated from this
repository's 1,004 merged PRs (see [calibration](docs/target-app-parity.md#remaining-effort-and-calibration)).
About 80% of the work parallelizes.
## Headline numbers
| | Value | Kind |
|---|---|---|
| **Feature breadth** | **~76%** | partly measured: menus 628/628, tools 56/68, panels 30/35, formats 13+4 of 31 |
| **Ready for real work** | **~45%** (40–50%) | estimated: weighted by dimension below |
| Mainstream practitioner | ~43% (38–48%) | estimated: weekly areas of a typical pro, with discounts ([method](docs/target-app-parity.md#mainstream-practitioner-43)) |
| Essentials user | ~61% (55–67%) | estimated: core features only ([method](docs/target-app-parity.md#essentials-user-61)) |
| Remaining to **beta** | **~1,100–1,800 h** | estimated |
| Remaining to **full parity** | **~2,300–4,100 h** | estimated; AI and plug-ins need owner decisions |
### Readiness by audience
| Audience | Ready % | Opus 5.5 agent-hours to ~95% | Work that dominates |
|---|---:|---:|---|
| Full target (ready for real work) | ~45% (additive weighted sum: 46%) | 2,300–4,100 | Everything below, plus AI tier, plug-in/scripting ecosystem, video, localization, hardware |
| Mainstream practitioner | ~43% | 1,700–2,800 | Depth in the 11 weekly areas (1,180–2,000), performance budgets, stability on real machines, PSD exchange with Photoshop |
| Essentials user | ~61% | 400–700 | Startup and GPU robustness, brush and transform responsiveness, Type tool, discoverability (flyouts, commit buttons), AVIF/PDF open |
Hours calibrated as in [Remaining effort](docs/target-app-parity.md#remaining-effort-and-calibration) (2–9 h per checklist
item, 8–20 h per format or subsystem, from the repo's 1,004 merged PRs); each tier is a subset of
the one above. About 80% parallelizes (independent crates and command modules); performance
architecture and the PSD writer are the serial parts.
**Why alpha.** Core workflows (open, layer, select, paint, adjust, filter, type, save) work end to
end, and breadth is high, but users of 0.5/0.6 have 579 open issues, 22 of 25 performance budgets
are missed, and PSDs we write are not yet reliably accepted by Photoshop (#1281, #2469). Beta
needs ~75% ready and no blocking PSD gap. The [alpha gate](docs/roadmap.md#alpha-gate) passes: all six core workflows
(retouch, composite, cut-out, design, paint, PSD exchange) complete end to end and save and reopen;
four are partial in depth, none blocked.
## By dimension
| Dimension | % ready | Hours to full | Doc |
|---|---:|---:|---|
| Features (depth) | 55% (breadth 76%) | 600–1,000 | [target-app-parity](docs/target-app-parity.md#feature-areas) |
| UI/UX fidelity (tools, handles, modifiers, brush feel, panels) | 40% | 350–600 | [ui-parity](docs/ui-parity.md), [brush-parity](docs/brush-parity.md), [context-menu-parity](docs/context-menu-parity.md) |
| File formats | 60% (presence ~80%) | 300–500 | [file-format-parity](docs/file-format-parity.md) |
| Hardware (GPU, pen, displays) | 50% | 80–150 | [hardware-parity](docs/hardware-parity.md) |
| Localization | 55% | 80–140 | [localization-parity](docs/localization-parity.md) |
| Performance | 25% (3/25 budgets met, measured) | 200–350 | [scorecard](docs/scorecard.md#performance) |
| Stability | 45% | 150–250 | [gaps](docs/gaps.md#g3-user-reported-bug-backlog) |
| Platforms | 80% | 30–60 | [scorecard](docs/scorecard.md#distribution) |
| Ecosystem / plug-ins / scripting | 15% | 250–450 | [gaps](docs/gaps.md#g16-plug-in-compatibility) |
| AI features | 10% | 300–600 | [gaps](docs/gaps.md#g15-ai-and-generative-features) |
## Features
| Area | % ready | Hours |
|---|---:|---:|
| Layers, masks, blend modes, smart objects, styles | 65% | 150–250 |
| Selections, Select and Mask, channels | 55% | 120–200 |
| Painting and brush engine | 55% | 150–250 |
| Retouching (healing, clone, patch, remove, content-aware) | 50% | 100–180 |
| Transform, warp, puppet, liquify | 55% | 100–180 |
| Adjustments and filters | 70% | 120–200 |
| Type | 40% | 120–200 |
| Vector shapes and paths | 55% | 80–140 |
| Colour management and modes | 70% | 60–100 |
| Camera Raw and computational photo | 45% | 120–200 |
| Automation, actions, scripting | 45% | 120–200 |
| File I/O | 60% | 300–500 |
| Print, export, Save for Web | 50% | 60–100 |
| Video / timeline, data-driven graphics | 30% | 100–200 |
| Workspace, panels, preferences | 40% | 150–250 |
| AI / generative | 10% | 300–600 |
Rows and evidence: [target-app-parity › Feature areas](docs/target-app-parity.md#feature-areas).
## Languages
Measured with the `cargo xtask i18n-coverage` key universe (1,608 keys). `partial` everywhere
because engine messages are still English. Detail: [localization-parity](docs/localization-parity.md).
| Language | Code | UI strings | Status |
|---|---|---:|---|
| English | `en` | 100% | full |
| Simplified Chinese | `zh-hans` | 100% | partial |
| Spanish | `es` | 100% | partial |
| Hindi | `hi` | 0% | none |
| Arabic | `ar` | 0% (RTL shell only) | none |
| French | `fr` | 100% | partial |
| Portuguese (Brazil) | `pt-br` | 100% | partial |
| Indonesian | `id` | 100% | partial |
| Japanese | `ja` | 100% | partial |
| German | `de` | 100% | partial |
| Korean | `ko` | 100% | partial |
| Vietnamese | `vi` | 0% | none |
Also shipped: Traditional Chinese, Russian, Ukrainian, Czech, Polish, Greek, Dutch, Italian (8).
## Upcoming
| Rank | Milestone | Estimate |
|---|---|---:|
| 1 | PSD that Photoshop trusts: Save As corruption, Photoshop re-open check, Photoshop-oracle floor 133 → 200+ of 256 | 150–250 h |
| 2 | Performance budgets: the 22 over-budget scenarios and the 150-layer GPU crash | 200–350 h |
| 3 | User bug backlog to under 100 open | 250–400 h |
| 4 | Brush and transform feel (brush-parity, ui-parity rows) | 160–290 h |
| 5 | The 12 missing tools | 60–100 h |
Detail and the next releases: [docs/roadmap.md](docs/roadmap.md).
## Progress log
| Date | Entry |
|---|---|
| 2026-10-10 | Full re-measure against Photoshop 2026 27.11.0 (installed bundle inspected): breadth ~76%, ready ~45%, alpha. Progress docs reorganized to the craftrules standard (`parity.md` → `parity-checklist.md`, `parity-estimate.md` merged into `target-app-parity.md`). 0.6.0 released. |
| 2026-10-09 | Remove tool, Rotate View, crop rotation; OpenRaster and Paint.NET; 39 Affinity documents in the corpus |
| 2026-10-08 | 0.5.0. Affinity import; Magnetic Lasso, Pattern Stamp, Mixer Brush, Pencil, Patch, Vertical Type on the toolbar |
| 2026-10-07 | 0.3.0. 10 UI languages; shortcut audit 214 → 0 failures; TIFF decode 10× faster |
| 2026-10-05 | 0.2.0, first signed and notarized release. Honest assessment: ready for real work 25–35% |
| 2026-10-03 | Menu breadth 625/625 |
| 2026-10-01 | Menu breadth 224 → 532 of 625 in a day |
| 2026-09-30 | First commit |
## Revision history
| Date | Change | Summary |
|---|---|---|
| 2026-10-11 | minor | Toolbox count 56 of 68 (12 missing) with the Convert Point tool (#3204) |
| 2026-10-10 | minor | Readiness by audience with hours per tier |
| 2026-10-10 | minor | Mainstream-practitioner and essentials-user numbers added |
| 2026-10-10 | minor | Alpha gate result (passes; stays alpha) in the stage explanation |
| 2026-10-10 | major | First version, per craftrules `standards/progress-docs.md` |
+145 -13
View File
@@ -7,6 +7,7 @@ use std::io::Write;
use std::path::{Path, PathBuf};
use photocraft_automation::{AuthorizedWorkspace, Headless, PhotocraftMcp, files, security};
use photocraft_engine::actions_cmds::Action;
use photocraft_io::ExportOptions;
use serde_json::{Value, json};
@@ -14,20 +15,25 @@ pub const USAGE: &str = "\
photocraft-cli: headless Photocraft
USAGE:
photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>] [--tiff-layers]
photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>]
Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …).
TIFF output is flat unless --tiff-layers keeps the layers (Photoshop layer data).
--quality sets the JPEG or WebP quality; a WebP written with a quality is lossy, without one lossless.
--tga-bits sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as
its alpha, 24 none. Without it: 32 with an alpha channel or transparency, else 24.
photocraft-cli info <file> [--compact]
Print the document as JSON (size, mode, depth, layer tree).
photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers]
photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>]
Open a file, run engine commands in order, save the result. Each --params
applies to the preceding --cmd. Prints each command's JSON result.
photocraft-cli batch --actions <actions.json> --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers]
photocraft-cli batch --actions <actions.json> [--action <name>] --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>]
Apply an action list to every image in a directory. Steps are [id, params] pairs,
{\"command\": id, \"params\": {…}} objects or bare ids, as a recorded action or droplet stores them
(a list, or wrapped in {\"actions\": …}, {\"steps\": …} or a droplet). An --out folder that is the
--in folder is refused, as the results would replace the originals; --in-place allows it.
(a list, or wrapped in {\"actions\": …}, {\"steps\": …} or a droplet). An Actions set (the Actions
panel's actions.json, {\"actions\": [{\"name\", \"steps\"}…]}) plays the action --action names (needed
when the set holds more than one) with the whole set loaded, so its steps can play other actions
of the set. An --out folder that is the --in folder is refused, as the results would replace
the originals; --in-place allows it.
photocraft-cli droplet <file.pcdroplet> <file-or-dir>… [--out <dir>]
Run a droplet (File › Automate › Create Droplet) on images and folders.
photocraft-cli commands [--json] [--filter <text>]
@@ -39,7 +45,7 @@ USAGE:
[--automation-read-root <dir>] [--automation-write-root <dir>]
Keep one headless session open and answer JSON lines ({\"id\",\"method\",\"params\"}) on stdio,
or on 127.0.0.1:<port>. Methods: engine.execute, jobs.list/cancel, engine.commands,
doc.open/new/save/inspect/render/select/close, session.list, batch, methods
doc.open/new/place/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close, session.list, batch, methods
(docs/control-protocol.md#headless-server).
photocraft-cli <subcommand> --help (or -h) prints this text. A flag the subcommand doesn't take is
@@ -61,10 +67,20 @@ struct Subcommand {
}
const SUBCOMMANDS: &[Subcommand] = &[
Subcommand { name: "convert", values: &["--format", "--quality"], bare: &["--tiff-layers"], run: convert },
Subcommand { name: "convert", values: &["--format", "--quality", "--tga-bits"], bare: &["--tiff-layers"], run: convert },
Subcommand { name: "info", values: &[], bare: &["--compact"], run: |a, out, _| info(a, out) },
Subcommand { name: "run", values: &["--new", "--cmd", "--params", "--out", "--format", "--quality"], bare: &["--tiff-layers"], run: run_cmds },
Subcommand { name: "batch", values: &["--actions", "--in", "--out", "--format", "--quality"], bare: &["--in-place", "--tiff-layers"], run: batch },
Subcommand {
name: "run",
values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits"],
bare: &["--tiff-layers"],
run: run_cmds,
},
Subcommand {
name: "batch",
values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits"],
bare: &["--in-place", "--tiff-layers"],
run: batch,
},
Subcommand { name: "droplet", values: &["--out"], bare: &[], run: droplet },
Subcommand { name: "commands", values: &["--filter"], bare: &["--json"], run: |a, out, _| commands(a, out) },
Subcommand {
@@ -194,6 +210,9 @@ fn export_opts(a: &Args) -> Result<ExportOptions, String> {
o.encode.webp_quality = q;
o.encode.webp_lossless = false;
}
if let Some(b) = a.get("--tga-bits") {
o.tga_bits = Some(b.parse().ok().and_then(photocraft_io::TgaBits::from_bits).ok_or_else(|| format!("bad --tga-bits `{b}`: expected 24 or 32"))?);
}
Ok(o)
}
@@ -330,7 +349,39 @@ fn run_cmds(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
/// list or wrapped in `{"actions": […]}`, `{"steps": […]}` or a droplet (#489).
pub fn parse_actions(text: &str) -> Result<Vec<(String, Value)>, String> {
let v: Value = serde_json::from_str(text).map_err(|e| format!("actions JSON: {e}"))?;
photocraft_engine::automate_cmds::parse_action(v.get("actions").unwrap_or(&v), "batch --actions").map_err(|e| e.to_string())
steps_of(&v)
}
fn steps_of(v: &Value) -> Result<Steps, String> {
photocraft_engine::automate_cmds::parse_action(v.get("actions").unwrap_or(v), "batch --actions").map_err(|e| e.to_string())
}
/// Engine commands to run in order: `(id, params)`.
pub type Steps = Vec<(String, Value)>;
/// The steps `batch` plays on each file, and the actions they can call. An Actions set (the
/// Actions panel's `actions.json`: `{"actions": [{"name", "steps"}…]}`, or the bare list) plays
/// the action `name` picks (optional when the set holds one) with the whole set loaded, as
/// Photoshop's Batch does; anything else is one action's steps ([`parse_actions`]) (#2786).
pub fn load_actions(text: &str, name: Option<&str>) -> Result<(Steps, Vec<Action>), String> {
let v: Value = serde_json::from_str(text).map_err(|e| format!("actions JSON: {e}"))?;
let list = v.get("actions").unwrap_or(&v);
let is_set = list.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|x| x.get("name").is_some_and(Value::is_string)));
if !is_set {
if name.is_some() {
return Err("--action picks an action from an Actions set ({\"actions\": [{\"name\", \"steps\"}…]}), but this file holds one action's steps".into());
}
return Ok((steps_of(&v)?, Vec::new()));
}
let set: Vec<Action> = serde_json::from_value(list.clone()).map_err(|e| format!("Actions set: {e}"))?;
let names = || set.iter().map(|a| format!("`{}`", a.name)).collect::<Vec<_>>().join(", ");
let action = match (name, set.as_slice()) {
(Some(n), _) => set.iter().find(|a| a.name == n).ok_or_else(|| format!("no action named `{n}` in the set (it holds {})", names()))?,
(None, [only]) => only,
(None, _) => return Err(format!("the Actions set holds {} actions: pick one with --action <name> ({})", set.len(), names())),
};
let play = vec![("actions.play".to_string(), json!({"action": action.name}))];
Ok((play, set))
}
/// Whether `a` and `b` name the same existing folder, however they are spelt (relative, with a
@@ -341,7 +392,7 @@ fn same_dir(a: &Path, b: &Path) -> bool {
fn is_input(p: &Path) -> bool {
let known = |e: &str| {
matches!(e, "pcraft" | "psd" | "psb" | "af" | "afdesign" | "afphoto" | "afpub")
matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "af" | "afdesign" | "afphoto" | "afpub")
|| photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read)
};
p.is_file() && p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase()))
@@ -352,7 +403,7 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
let in_dir = PathBuf::from(a.get("--in").ok_or("batch needs --in <dir>")?);
let out_dir = PathBuf::from(a.get("--out").ok_or("batch needs --out <dir>")?);
let text = std::fs::read_to_string(actions_path).map_err(|e| format!("{actions_path}: {e}"))?;
let actions = parse_actions(&text)?;
let (actions, set) = load_actions(&text, a.get("--action"))?;
let opts = export_opts(a)?;
// Results are saved as `<out>/<stem>.<ext>`, so an `--out` that is the `--in` folder would
// replace the originals (#492).
@@ -378,9 +429,19 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
let r = (|| -> Result<Vec<String>, String> {
written.check(&target_text)?;
let mut h = Headless::trusted_local();
// Steps that play another action find it in the set; the session's playback stack
// stops an action that calls itself.
h.session.actions.list = set.clone();
h.open(input).map_err(|e| e.to_string())?;
for (id, p) in &actions {
h.command_run(id, p.clone()).map_err(|e| format!("`{id}`: {e}"))?;
if photocraft_engine::actions_cmds::shell_view_command(id) || photocraft_engine::actions_cmds::shell_save_command(id) {
continue;
}
let r = h.command_run(id, p.clone()).map_err(|e| format!("`{id}`: {e}"))?;
// A failed step inside a called action makes this file an error, not a saved result.
if let Some(e) = photocraft_engine::actions_cmds::nested_failure(id, &r) {
return Err(format!("`{id}`: {e}"));
}
}
let r = h.save(None, Some(&target), Some(&ext), &opts).map_err(|e| e.to_string())?;
Ok(serde_json::from_value(r["warnings"].clone()).unwrap_or_default())
@@ -548,6 +609,26 @@ mod missing_font_warning_tests {
let _ = std::fs::remove_dir_all(&folder);
}
#[test]
fn convert_reads_and_writes_openraster() {
let folder = std::env::temp_dir().join(format!("photocraft-cli-ora-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
let path = |name: &str| folder.join(name).to_string_lossy().to_string();
let (native, ora, png) = (path("layers.pcraft"), path("layers.ora"), path("back.png"));
let (code, _, stderr) = invoke(&["run", "--new", r#"{"width":16,"height":12}"#, "--cmd", "layer.new.layer", "--out", &native]);
assert_eq!(code, 0, "{stderr}");
let (code, _, stderr) = invoke(&["convert", &native, &ora]);
assert_eq!(code, 0, "{stderr}");
let (code, stdout, stderr) = invoke(&["info", &ora, "--compact"]);
assert_eq!(code, 0, "{stderr}");
let info: Value = serde_json::from_str(&stdout).unwrap();
assert_eq!(info["layers"].as_array().map(Vec::len), Some(2), "{info}");
let (code, _, stderr) = invoke(&["convert", &ora, &png]);
assert_eq!(code, 0, "{stderr}");
assert!(is_input(std::path::Path::new(&ora)));
let _ = std::fs::remove_dir_all(&folder);
}
#[test]
fn no_type_layers_do_not_produce_missing_font_warnings() {
let folder = std::env::temp_dir().join(format!("photocraft-cli-no-font-warning-{}", std::process::id()));
@@ -569,3 +650,54 @@ mod missing_font_warning_tests {
let _ = std::fs::remove_dir_all(&folder);
}
}
#[cfg(test)]
mod batch_action_set_tests {
use super::*;
fn invoke(args: &[&str]) -> (i32, String, String) {
let (mut output, mut errors) = (Vec::new(), Vec::new());
let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
let code = run(&args, &mut output, &mut errors);
(code, String::from_utf8(output).unwrap(), String::from_utf8(errors).unwrap())
}
/// A batched action that plays another action of its set finds it in every file's session; a
/// failure inside the called action fails the file, and a self-call stops instead of looping.
#[test]
fn batch_plays_an_action_that_calls_another_action_of_its_set() {
let dir = std::env::temp_dir().join(format!("photocraft-cli-action-set-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = |name: &str| dir.join(name).to_string_lossy().to_string();
std::fs::create_dir_all(dir.join("in")).unwrap();
for name in ["a", "b"] {
let (code, _, stderr) = invoke(&["run", "--new", r#"{"width":8,"height":6}"#, "--out", &path(&format!("in/{name}.png"))]);
assert_eq!(code, 0, "{stderr}");
}
let set = json!({"version": 1, "actions": [
{"name": "Outer", "steps": [["actions.play", {"action": "Rotate"}]]},
{"name": "Rotate", "steps": [["image.imageRotation.90cw", {}]]},
{"name": "Calls bad", "steps": [["actions.play", {"action": "Bad"}]]},
{"name": "Bad", "steps": [["layer.delete", {"layer": 999_999}]]},
{"name": "Loop", "steps": [["actions.play", {"action": "Loop"}]]},
]});
std::fs::write(dir.join("actions.json"), set.to_string()).unwrap();
let batch = |action: &str| invoke(&["batch", "--actions", &path("actions.json"), "--action", action, "--in", &path("in"), "--out", &path(action)]);
let (code, stdout, stderr) = batch("Outer");
assert_eq!(code, 0, "{stdout}{stderr}");
for name in ["a", "b"] {
let (code, info, stderr) = invoke(&["info", &path(&format!("Outer/{name}.png")), "--compact"]);
assert_eq!(code, 0, "{stderr}");
let info: Value = serde_json::from_str(&info).unwrap();
assert_eq!((info["width"].as_u64(), info["height"].as_u64()), (Some(6), Some(8)), "rotated by the called action");
}
for action in ["Calls bad", "Loop"] {
let (code, stdout, stderr) = batch(action);
assert_ne!(code, 0, "{stdout}");
assert_eq!(stderr.matches("FAIL").count(), 2, "{stderr}");
assert!(!dir.join(action).join("a.png").exists(), "a file whose called action failed is not saved");
}
let _ = std::fs::remove_dir_all(&dir);
}
}
+80 -2
View File
@@ -136,7 +136,8 @@ fn info_prints_layer_tree_json() {
let v: Value = serde_json::from_str(&out).unwrap();
assert_eq!(v["width"], 10);
assert_eq!(v["height"], 6);
assert_eq!(v["layers"][0]["name"], "Background");
// An RGBA PNG opens as a normal "Layer 0", not the locked Background (as in Photoshop).
assert_eq!(v["layers"][0]["name"], "Layer 0");
assert!(v.get("history").is_none());
let (out, _) = ok(bin().arg("info").arg(&a).arg("--compact"));
assert_eq!(out.trim().lines().count(), 1);
@@ -188,9 +189,11 @@ fn run_commands_and_save() {
let lines: Vec<Value> = out.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(lines.len(), 3);
assert_eq!(lines[2]["command"], "document.inspect");
assert_eq!(lines[2]["result"]["name"], "Run");
let (info, _) = ok(bin().arg("info").arg(&out_pc));
let v: Value = serde_json::from_str(&info).unwrap();
assert_eq!(v["name"], "Run");
// Saving a native document gives the reopened bundle its output filename.
assert_eq!(v["name"], "r.pcraft");
let names: Vec<&str> = v["layers"].as_array().unwrap().iter().filter_map(|l| l["name"].as_str()).collect();
assert_eq!(names, ["Ink", "Background"]);
// Continue from the saved file and export PNG.
@@ -220,6 +223,24 @@ fn run_errors() {
assert!(e.contains("layer.new.layer") && e.contains("must be a JSON object"), "{e}");
}
#[test]
fn run_rejects_invalid_filter_parameters_without_exporting() {
let d = tmp("invalid-filter-params");
let out = d.join("result.png");
for (params, key) in [(r#"{"radius":"big"}"#, "radius"), (r#"{"radus":3}"#, "radus"), (r#"{"radius":5000}"#, "radius"), (r#"{"radius":-4}"#, "radius")] {
let result = bin()
.args(["run", "--new", r#"{"width":8,"height":8}"#, "--cmd", "filter.blur.gaussianBlur", "--params", params, "--out"])
.arg(&out)
.output()
.unwrap();
assert_eq!(result.status.code(), Some(1));
let error = String::from_utf8_lossy(&result.stderr);
assert!(error.contains("filter.blur.gaussianBlur") && error.contains(key), "{error}");
assert!(!out.exists());
}
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn batch_applies_actions_to_directory() {
let d = tmp("batch");
@@ -245,6 +266,37 @@ fn batch_applies_actions_to_directory() {
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn batch_skips_recorded_view_and_save_steps() {
let d = tmp("batch-shell-steps");
let input = d.join("in");
std::fs::create_dir_all(&input).unwrap();
let source = input.join("a.png");
write_png(&source, 12, 8, 3);
let original = std::fs::read(&source).unwrap();
let recorded_save = d.join("recorded-save.psd");
let mut cases = Vec::new();
for (name, id) in [("zoom-in", "view.zoomIn"), ("zoom-out", "view.zoomOut"), ("fit", "view.fitOnScreen"), ("actual-pixels", "view.actualPixels")] {
cases.push((name, json!([[id, {}], ["image.imageRotation.90cw", {}]]).to_string()));
}
cases.push(("save", json!([["file.save", {}], ["image.imageRotation.90cw", {}]]).to_string()));
cases.push(("save-as", json!([["file.saveAs", {"path": recorded_save.to_string_lossy()}], ["image.imageRotation.90cw", {}]]).to_string()));
for (name, actions) in cases {
let o = batch_with(&d, &input, name, &actions, &[]);
let (stdout, stderr) = (String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
assert!(o.status.success(), "{name}: {stdout}\n{stderr}");
assert!(stdout.contains("1 succeeded, 0 failed"), "{name}: {stdout}");
let output = d.join(name).join("a.png");
let (info, _) = ok(bin().arg("info").arg(&output));
let info: Value = serde_json::from_str(&info).unwrap();
assert_eq!((info["width"].as_u64(), info["height"].as_u64()), (Some(8), Some(12)), "{name}: {info}");
assert_eq!(std::fs::read(&source).unwrap(), original, "{name} changed its input");
assert!(!recorded_save.exists(), "{name} wrote the recorded Save As path");
}
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn parse_actions_formats() {
let a = photocraft_cli::parse_actions(r#"[{"command":"a","params":{"x":1}},{"id":"b"}]"#).unwrap();
@@ -359,6 +411,32 @@ fn quality_outside_1_to_100_is_refused() {
assert!(sizes[0] <= sizes[1] && sizes[1] <= sizes[2], "{sizes:?}");
}
/// `--tga-bits` picks a TGA's bits per pixel (byte 16 of its header); anything but 24 or 32 is
/// refused and nothing is written.
#[test]
fn tga_bits_choose_the_targa_depth() {
let d = tmp("tga-bits");
let a = d.join("a.png");
write_png(&a, 8, 4, 3);
for (bits, want) in [(None, 32), (Some("24"), 24), (Some("32"), 32)] {
let out = d.join("a.tga");
let mut convert = bin();
convert.arg("convert").arg(&a).arg(&out);
if let Some(b) = bits {
convert.args(["--tga-bits", b]);
}
ok(&mut convert);
assert_eq!(std::fs::read(&out).unwrap()[16], want, "--tga-bits {bits:?}");
}
for bad in ["16", "0", "abc", ""] {
let out = d.join("bad.tga");
let o = bin().arg("convert").arg(&a).arg(&out).args(["--tga-bits", bad]).output().unwrap();
assert_eq!(o.status.code(), Some(1), "--tga-bits {bad}");
assert!(String::from_utf8_lossy(&o.stderr).contains(&format!("bad --tga-bits `{bad}`: expected 24 or 32")), "--tga-bits {bad}");
assert!(!out.exists(), "--tga-bits {bad} wrote a file");
}
}
/// #492: an `--out` folder that is the `--in` folder, however it is spelt, is refused before
/// anything is written, unless `--in-place` asks for it.
#[test]
+7 -2
View File
@@ -125,14 +125,19 @@ fn orientation_6_jpeg_converts_upright_and_rotates_back() {
let (a, b) = (d.join("a.pcraft"), d.join("b.pcraft"));
ok(bin().arg("convert").arg(&jpg).arg(&a));
ok(bin().arg("convert").arg(&a).arg(&b));
// Everything but the file's own path must match.
// Everything but the file's own path and saved document name must match.
let info = |p: &Path| {
let mut v = serde_json::from_str::<Value>(&ok(bin().arg("info").arg(p))).unwrap();
v.as_object_mut().unwrap().remove("file");
v.as_object_mut().unwrap().remove("path");
v
};
let (ia, ib) = (info(&a), info(&b));
let (mut ia, mut ib) = (info(&a), info(&b));
assert_eq!((ia["width"].as_u64(), ia["height"].as_u64()), (Some(16), Some(32)));
assert_eq!(ia["name"], "a.pcraft");
assert_eq!(ib["name"], "b.pcraft");
ia.as_object_mut().unwrap().remove("name");
ib.as_object_mut().unwrap().remove("name");
assert_eq!(ia, ib);
let (pa, pb) = (d.join("a.png"), d.join("b.png"));
ok(bin().arg("convert").arg(&a).arg(&pa));
+6 -1
View File
@@ -34,4 +34,9 @@ rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException", "Response", "IdbFactory", "IdbOpenDbRequest", "IdbDatabase", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbObjectStore", "IdbCursor", "IdbCursorWithValue", "RequestInit", "Navigator"] }
[dev-dependencies]
serde_json = { workspace = true }
photocraft-paint = { workspace = true }
photocraft-psd = { workspace = true }
+255
View File
@@ -0,0 +1,255 @@
//! IndexedDB owns durable bytes; the engine sees only the bounded, Send memory bridge.
//! Each batch commits tips, groups and index together, and success means transaction completion.
use js_sys::{Array, Function, Promise, Uint8Array};
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
use wasm_bindgen_futures::JsFuture;
use web_sys::{Blob, Event, EventTarget, IdbDatabase, IdbRequest, IdbTransactionMode};
use crate::preset_bridge::{Batch, Bridge, MAX_RECORDS, record_limit};
use photocraft_engine::preset_store::MAX_STORE_BYTES;
const DATABASE: &str = "photocraft.presets";
const FILES: &str = "files";
const TIMEOUT_MS: f64 = 10_000.0;
fn js(e: JsValue) -> String {
if let Some(exception) = e.dyn_ref::<web_sys::DomException>() {
format!("{}: {}", exception.name(), exception.message())
} else {
e.as_string().unwrap_or_else(|| format!("{e:?}"))
}
}
/// Listeners are detached even when startup or a write times out.
type Listener = (EventTarget, &'static str, Closure<dyn FnMut(Event)>);
struct Listeners(Vec<Listener>);
impl Listeners {
fn new() -> Self {
Self(Vec::new())
}
fn add(&mut self, target: &EventTarget, name: &'static str, f: impl FnMut(Event) + 'static) -> Result<(), JsValue> {
let cb = Closure::<dyn FnMut(Event)>::new(f);
target.add_event_listener_with_callback(name, cb.as_ref().unchecked_ref())?;
self.0.push((target.clone(), name, cb));
Ok(())
}
}
impl Drop for Listeners {
fn drop(&mut self) {
for (target, name, cb) in &self.0 {
let _ = target.remove_event_listener_with_callback(name, cb.as_ref().unchecked_ref());
}
}
}
struct Pending {
promise: Promise,
_listeners: Listeners,
}
fn request(request: &IdbRequest) -> Pending {
let mut listeners = Listeners::new();
let promise = Promise::new(&mut |resolve, reject| {
let req = request.clone();
let failed = reject.clone();
if let Err(e) = listeners.add(request, "success", move |_| match req.result() {
Ok(v) => {
let _ = resolve.call1(&JsValue::NULL, &v);
}
Err(e) => {
let _ = failed.call1(&JsValue::NULL, &e);
}
}) {
let _ = reject.call1(&JsValue::NULL, &e);
}
let req = request.clone();
let failed = reject.clone();
if let Err(e) = listeners.add(request, "error", move |_| {
let e = req.error().ok().flatten().map(JsValue::from).unwrap_or_else(|| JsValue::from_str("IndexedDB request failed"));
let _ = failed.call1(&JsValue::NULL, &e);
}) {
let _ = reject.call1(&JsValue::NULL, &e);
}
});
Pending { promise, _listeners: listeners }
}
/// A single deadline bounds the whole startup read, not ten seconds per record.
async fn before(promise: &Promise, deadline: f64) -> Result<JsValue, String> {
let window = web_sys::window().ok_or("no window")?;
let mut timer = None;
let mut callback = None;
let timeout = Promise::new(&mut |_, reject| {
let cb = Closure::<dyn FnMut()>::new(move || {
let _ = reject.call1(&JsValue::NULL, &JsValue::from_str("browser preset storage timed out"));
});
timer = Some(window.set_timeout_with_callback_and_timeout_and_arguments_0(
cb.as_ref().unchecked_ref(),
(deadline - js_sys::Date::now()).clamp(0.0, TIMEOUT_MS) as i32,
));
callback = Some(cb);
});
let id = timer.ok_or("could not start storage timeout")?.map_err(js)?;
let result = JsFuture::from(Promise::race(&Array::of2(promise, &timeout))).await.map_err(js);
window.clear_timeout_with_handle(id);
drop(callback);
result
}
async fn open(deadline: f64) -> Result<IdbDatabase, String> {
let factory = web_sys::window().ok_or("no window")?.indexed_db().map_err(js)?.ok_or("IndexedDB unavailable")?;
let req = factory.open_with_u32(DATABASE, 1).map_err(js)?;
let mut upgrade = Listeners::new();
let upgrade_req = req.clone();
upgrade
.add(&req, "upgradeneeded", move |_| {
let result = upgrade_req.result().and_then(|v| v.dyn_into::<IdbDatabase>()).and_then(|db| db.create_object_store(FILES));
if result.is_err()
&& let Some(tx) = upgrade_req.transaction()
{
let _ = tx.abort();
}
})
.map_err(js)?;
let pending = request(&req);
match before(&pending.promise, deadline).await {
Ok(value) => value.dyn_into().map_err(|_| "invalid preset database".into()),
Err(e) => {
// An open request cannot be cancelled (another tab may block its upgrade). Keep
// its handlers alive and close any late connection; never hydrate a live session.
wasm_bindgen_futures::spawn_local(async move {
if let Ok(value) = JsFuture::from(pending.promise.clone()).await
&& let Ok(db) = value.dyn_into::<IdbDatabase>()
{
db.close();
}
drop(pending);
drop(upgrade);
});
Err(e)
}
}
}
pub async fn load() -> Result<(IdbDatabase, Bridge, Vec<String>), String> {
let deadline = js_sys::Date::now() + TIMEOUT_MS;
let db = open(deadline).await?;
let result = read(&db, deadline).await;
match result {
Ok((bridge, warnings)) => Ok((db, bridge, warnings)),
Err(e) => {
db.close();
Err(e)
}
}
}
async fn read(db: &IdbDatabase, deadline: f64) -> Result<(Bridge, Vec<String>), String> {
let tx = db.transaction_with_str_and_mode(FILES, IdbTransactionMode::Readonly).map_err(js)?;
let req = tx.object_store(FILES).map_err(js)?.open_cursor().map_err(js)?;
let mut records = Vec::new();
let mut warnings = Vec::new();
let mut unreadable = Vec::new();
let mut total = 0u64;
let mut seen = 0usize;
let mut next = request(&req);
loop {
let value = before(&next.promise, deadline).await?;
if value.is_null() {
break;
}
let cursor = value.dyn_into::<web_sys::IdbCursorWithValue>().map_err(|_| "invalid preset cursor")?;
seen += 1;
if seen > MAX_RECORDS {
return Err(format!("browser preset record limit ({MAX_RECORDS}) exceeded"));
}
let key = cursor.key().map_err(js)?;
// Inspect key length in JS before allocating its Rust String.
let name = if key.is_string() && js_sys::JsString::from(key.clone()).length() <= 133 { key.as_string().unwrap_or_default() } else { String::new() };
let blob = cursor.value().map_err(js)?.dyn_into::<Blob>();
let record = record_limit(&name).and_then(|limit| {
let blob = blob.map_err(|_| "record is not a Blob".to_string())?;
if blob.size() > limit as f64 {
return Err("record is too large".into());
}
Ok(blob)
});
match record {
Ok(blob) => {
total = total.saturating_add(blob.size() as u64);
if total > MAX_STORE_BYTES {
return Err("browser preset store exceeds size limit".into());
}
records.push((name, blob));
}
Err(e) => {
// Leave an unreadable placeholder in the engine's file inventory. In
// particular, a skipped group must protect its tip records from orphan GC.
if record_limit(&name).is_ok() {
unreadable.push(name.clone());
}
if warnings.len() < 8 {
warnings.push(format!("Brush presets: {name} skipped: {e}"));
}
}
}
// Register the next callback before continuing the cursor. Blob reads happen after
// enumeration, since awaiting them here would let this transaction become inactive.
next = request(&req);
cursor.continue_().map_err(js)?;
}
let bridge = Bridge::default();
for name in unreadable {
bridge.load(&name, Vec::new())?;
}
for (name, blob) in records {
let buffer = before(&blob.array_buffer(), deadline).await?;
bridge.load(&name, Uint8Array::new(&buffer).to_vec())?;
}
Ok((bridge, warnings))
}
pub async fn write(db: &IdbDatabase, batch: &Batch) -> Result<(), String> {
let tx = db.transaction_with_str_and_mode(FILES, IdbTransactionMode::Readwrite).map_err(js)?;
let store = tx.object_store(FILES).map_err(js)?;
let queued = (|| -> Result<(), String> {
for (name, bytes) in batch {
let key = JsValue::from_str(name);
if let Some(bytes) = bytes {
let blob = Blob::new_with_u8_array_sequence(&Array::of1(&Uint8Array::from(bytes.as_ref()))).map_err(js)?;
store.put_with_key(&blob, &key).map_err(js)?;
} else {
store.delete(&key).map_err(js)?;
}
}
Ok(())
})();
if let Err(e) = queued {
let _ = tx.abort();
return Err(e);
}
let mut listeners = Listeners::new();
let promise = Promise::new(&mut |resolve, reject| {
if let Err(e) = listeners.add(&tx, "complete", move |_| {
let _ = resolve.call0(&JsValue::NULL);
}) {
let _ = reject.call1(&JsValue::NULL, &e);
}
for event in ["abort", "error"] {
let tx = tx.clone();
let failed: Function = reject.clone();
let target: EventTarget = tx.clone().into();
if let Err(e) = listeners.add(&target, event, move |_| {
let e = tx.error().map(JsValue::from).unwrap_or_else(|| JsValue::from_str("preset transaction aborted"));
let _ = failed.call1(&JsValue::NULL, &e);
}) {
let _ = reject.call1(&JsValue::NULL, &e);
}
}
});
let result = before(&promise, js_sys::Date::now() + TIMEOUT_MS).await.map(|_| ());
if result.is_err() {
let _ = tx.abort();
}
result
}
+6
View File
@@ -16,6 +16,12 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(any(target_arch = "wasm32", test))]
mod preset_bridge;
#[cfg(target_arch = "wasm32")]
mod indexed_presets;
#[cfg(target_arch = "wasm32")]
mod web;
+389
View File
@@ -0,0 +1,389 @@
//! Synchronous engine boundary for asynchronous browser storage. No browser handles cross the
//! engine's `Send` boundary. Byte buffers are shared with the single in-flight transaction.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex, MutexGuard};
use photocraft_engine::{
Session,
preset_store::{self, PresetBackend, *},
};
pub type Batch = BTreeMap<String, Option<Arc<[u8]>>>;
/// Three sampled images per preset (tip, dual tip, texture), plus group/index/action records.
pub const MAX_RECORDS: usize = MAX_GROUPS + MAX_PRESETS_PER_GROUP * 3 + 2;
#[derive(Default)]
struct State {
files: BTreeMap<String, Arc<[u8]>>,
bytes: u64,
dirty: BTreeSet<String>,
writing: bool,
error: Option<String>,
rejected: BTreeMap<String, String>,
preserve_tips: bool,
}
#[derive(Clone, Default)]
pub struct Bridge(Arc<Mutex<State>>);
pub fn session(backend: Bridge) -> (Session, Vec<String>) {
let mut session = Session::new();
let opened = preset_store::open(Box::new(backend.clone()));
// An unreadable group may reference any tip, including one shared with a good group.
// Keep all tips until the damaged library can be recovered; unrelated edits still save.
backend.state().preserve_tips = !opened.warnings.is_empty();
let warnings = session.attach_preset_store(opened);
(session, warnings)
}
/// Check metadata before copying a browser record into Rust memory.
pub fn record_limit(name: &str) -> Result<u64, String> {
let leaf = name.strip_prefix("tips/").unwrap_or(name);
if leaf.is_empty() || leaf.len() > 128 || leaf.starts_with('.') || !leaf.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '_' | '-' | '.')) {
return Err("invalid preset record name".into());
}
match name {
INDEX_FILE => Ok(MAX_INDEX_BYTES),
ACTIONS_FILE => Ok(MAX_ACTIONS_BYTES),
_ if name.starts_with("tips/") && leaf.ends_with(".pctip") => Ok(MAX_TIP_BYTES),
_ if !name.contains('/') && name.ends_with(".pcbrushes") => Ok(MAX_GROUP_BYTES),
_ => Err("unknown preset record type".into()),
}
}
impl Bridge {
fn state(&self) -> MutexGuard<'_, State> {
self.0.lock().unwrap_or_else(|e| e.into_inner())
}
fn insert(s: &mut State, name: &str, bytes: &[u8]) -> Result<(), String> {
if bytes.len() as u64 > record_limit(name)? {
return Err(format!("{name}: preset record too large"));
}
let old = s.files.get(name).map_or(0, |b| b.len() as u64);
let size = s.bytes.saturating_sub(old).saturating_add(bytes.len() as u64);
if size > MAX_STORE_BYTES || (!s.files.contains_key(name) && s.files.len() >= MAX_RECORDS) {
return Err("browser preset store is full".into());
}
s.files.insert(name.to_string(), Arc::from(bytes));
s.bytes = size;
Ok(())
}
pub fn load(&self, name: &str, bytes: Vec<u8>) -> Result<(), String> {
Self::insert(&mut self.state(), name, &bytes)
}
pub fn begin(&self) -> Option<Batch> {
let mut s = self.state();
if s.writing || s.error.is_some() || s.dirty.is_empty() {
return None;
}
s.writing = true;
Some(
std::mem::take(&mut s.dirty)
.into_iter()
.map(|name| {
let bytes = s.files.get(&name).cloned();
(name, bytes)
})
.collect(),
)
}
pub fn finish(&self, batch: Batch, result: Result<(), String>) {
let mut s = self.state();
s.writing = false;
if let Err(e) = result {
// Requeue names, never old bytes: edits/deletes made during the failed write win.
s.dirty.extend(batch.into_keys());
s.error = Some(e);
}
}
pub fn unavailable(&self, error: String) {
self.state().error = Some(error);
}
pub fn retry(&self) {
self.state().error = None;
}
pub fn error(&self) -> Option<String> {
let s = self.state();
s.rejected.values().next().cloned().or_else(|| s.error.clone())
}
pub fn unsaved(&self) -> bool {
let s = self.state();
s.writing || !s.dirty.is_empty() || !s.rejected.is_empty()
}
}
impl PresetBackend for Bridge {
fn list(&self) -> Result<Vec<(String, u64)>, String> {
Ok(self.state().files.iter().map(|(k, b)| (k.clone(), b.len() as u64)).collect())
}
fn read(&self, name: &str, max: u64) -> Result<Vec<u8>, String> {
let s = self.state();
let bytes = s.files.get(name).ok_or_else(|| format!("{name}: not found"))?;
if bytes.len() as u64 > max {
return Err(format!("{name}: preset record too large"));
}
Ok(bytes.to_vec())
}
fn write(&self, name: &str, bytes: &[u8]) -> Result<(), String> {
let mut s = self.state();
if s.files.get(name).is_some_and(|old| old.as_ref() == bytes) {
s.rejected.remove(name);
return Ok(());
}
if !s.dirty.contains(name) && s.dirty.len() >= MAX_RECORDS {
let e = "too many pending preset records".to_string();
s.rejected.insert(name.to_string(), e.clone());
return Err(e);
}
if let Err(e) = Self::insert(&mut s, name, bytes) {
s.rejected.insert(name.to_string(), e.clone());
return Err(e);
}
s.dirty.insert(name.to_string());
// This current replacement resolves only its own omitted edit. Pending transactions
// still keep unsaved() true; Retry or an older successful batch cannot clear it.
s.rejected.remove(name);
Ok(())
}
fn remove(&self, name: &str) -> Result<(), String> {
record_limit(name)?;
let mut s = self.state();
if s.preserve_tips && name.starts_with("tips/") {
s.rejected.remove(name);
return Ok(());
}
if !s.dirty.contains(name) && s.dirty.len() >= MAX_RECORDS {
let e = "too many pending preset records".to_string();
s.rejected.insert(name.to_string(), e.clone());
return Err(e);
}
if let Some(bytes) = s.files.remove(name) {
s.bytes = s.bytes.saturating_sub(bytes.len() as u64);
s.dirty.insert(name.to_string());
}
s.rejected.remove(name);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use photocraft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12};
use serde_json::json;
fn import(s: &mut Session) {
let abr = write_v12(
2,
&[LegacyBrush {
name: "Browser seam brush".into(),
spacing: 25,
anti_alias: true,
tip: LegacyTip::Sampled(AbrSample { id: String::new(), width: 6, height: 4, depth: 8, data: vec![255; 24] }),
}],
false,
)
.unwrap();
s.execute("brush.presets.importAbr", json!({"data": photocraft_paint::tile::b64_encode(&abr), "group": "Browser samples"})).unwrap();
}
#[test]
fn browser_session_reloads_imported_tip_settings_group_and_order() {
let backend = Bridge::default();
let (mut first, _) = session(backend.clone());
import(&mut first);
let (second, warnings) = session(backend);
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(first.tools.presets, second.tools.presets);
}
#[test]
fn pending_writes_coalesce_and_only_one_transaction_runs() {
let b = Bridge::default();
b.write("index.json", b"one").unwrap();
b.write("index.json", b"two").unwrap();
let batch = b.begin().unwrap();
assert_eq!(batch.get("index.json").unwrap().as_deref(), Some(&b"two"[..]));
b.remove("index.json").unwrap();
assert!(b.begin().is_none());
assert!(b.unsaved());
b.finish(batch, Ok(()));
let batch = b.begin().unwrap();
assert!(batch.get("index.json").unwrap().is_none());
b.finish(batch, Ok(()));
assert!(!b.unsaved());
}
#[test]
fn failed_transaction_retains_latest_writes_until_explicit_retry() {
let b = Bridge::default();
b.write("index.json", b"old").unwrap();
let batch = b.begin().unwrap();
b.write("index.json", b"new").unwrap();
b.finish(batch, Err("QuotaExceededError".into()));
assert!(b.unsaved());
assert!(b.error().unwrap().contains("QuotaExceeded"));
assert!(b.begin().is_none());
b.retry();
let batch = b.begin().unwrap();
assert_eq!(batch.get("index.json").unwrap().as_deref(), Some(&b"new"[..]));
b.finish(batch, Ok(()));
assert!(!b.unsaved());
assert!(b.error().is_none());
}
#[test]
fn browser_deletion_and_reordering_survive_reload() {
let b = Bridge::default();
let (mut s, _) = session(b.clone());
import(&mut s);
let deleted = s.tools.presets[0].name.clone();
s.execute("brush.presets.delete", json!({"name": deleted})).unwrap();
s.execute("brush.presets.moveGroup", json!({"group":"Browser samples", "index":0})).unwrap();
let persisted = b.begin().unwrap();
let restored = Bridge::default();
for (key, value) in &persisted {
if let Some(bytes) = value {
restored.load(key, bytes.to_vec()).unwrap();
}
}
b.finish(persisted, Ok(()));
let (loaded, warnings) = session(restored);
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(s.tools.presets, loaded.tools.presets);
s.execute("brush.presets.delete", json!({"name":"Browser seam brush"})).unwrap();
let (loaded, _) = session(b);
assert_eq!(s.tools.presets, loaded.tools.presets);
}
#[test]
fn corrupt_record_is_skipped_with_warning_and_kept_for_recovery() {
let b = Bridge::default();
b.load("bad.pcbrushes", b"corrupt".to_vec()).unwrap();
let (s, warnings) = session(b.clone());
assert_eq!(s.tools.presets, Session::new().tools.presets);
assert!(warnings.iter().any(|w| w.contains("bad.pcbrushes")));
assert_eq!(b.read("bad.pcbrushes", 100).unwrap(), b"corrupt");
}
#[test]
fn rejects_invalid_and_oversized_records_before_copying() {
assert!(record_limit("../index.json").is_err());
assert!(record_limit("unknown.bin").is_err());
assert_eq!(record_limit("index.json").unwrap(), MAX_INDEX_BYTES);
assert_eq!(record_limit("tips/a.pctip").unwrap(), MAX_TIP_BYTES);
let b = Bridge::default();
b.load("index.json", b"initial".to_vec()).unwrap();
assert!(!b.unsaved(), "hydration is not a user edit");
assert!(b.read("index.json", 2).is_err());
assert!(b.write("index.json", &vec![0; MAX_INDEX_BYTES as usize + 1]).is_err());
assert!(b.error().is_some());
b.retry();
assert!(b.error().is_some(), "staging errors cannot be cleared by retrying older writes");
assert_eq!(b.read("index.json", 100).unwrap(), b"initial");
}
#[test]
fn accepted_replacement_resolves_only_its_own_staging_rejection() {
let b = Bridge::default();
b.load("index.json", b"initial".to_vec()).unwrap();
let oversized = vec![0; MAX_INDEX_BYTES as usize + 1];
assert!(b.write("index.json", &oversized).is_err());
b.retry();
assert!(b.error().is_some(), "retrying older bytes cannot save the rejected edit");
b.write("index.json", b"repaired").unwrap();
assert!(b.unsaved(), "accepted replacement still needs its transaction");
b.finish(b.begin().unwrap(), Ok(()));
assert!(b.error().is_none());
assert!(!b.unsaved());
assert_eq!(b.read("index.json", 100).unwrap(), b"repaired");
assert!(b.write("index.json", &oversized).is_err());
assert!(b.write("other.pcbrushes", &vec![0; MAX_GROUP_BYTES as usize + 1]).is_err());
b.write("index.json", b"repaired").unwrap();
assert!(b.error().is_some(), "an unchanged accepted record cannot clear another record's rejection");
assert!(b.unsaved());
b.remove("other.pcbrushes").unwrap();
assert!(b.error().is_none());
assert!(!b.unsaved(), "discarding the rejected absent record resolves its pending edit");
}
#[test]
fn older_successful_transaction_does_not_resolve_an_omitted_edit() {
let b = Bridge::default();
b.write("index.json", b"older").unwrap();
let older = b.begin().unwrap();
assert!(b.write("index.json", &vec![0; MAX_INDEX_BYTES as usize + 1]).is_err());
b.finish(older, Ok(()));
assert!(b.error().is_some());
assert!(b.unsaved());
b.write("index.json", b"older").unwrap();
assert!(b.error().is_none(), "explicitly restoring the already saved bytes resolves the omitted edit");
assert!(!b.unsaved());
}
#[test]
fn denied_storage_keeps_imports_in_memory_and_marks_them_unsaved() {
let b = Bridge::default();
b.unavailable("SecurityError".into());
let (mut s, _) = session(b.clone());
import(&mut s);
assert!(s.tools.presets.iter().any(|p| p.name == "Browser seam brush"));
assert!(b.unsaved());
assert!(b.error().unwrap().contains("SecurityError"));
assert!(b.begin().is_none());
}
#[test]
fn corrupt_group_and_shared_tip_survive_unrelated_save_delete_and_reload() {
let b = Bridge::default();
let (mut s, _) = session(b.clone());
import(&mut s);
let tip = b.list().unwrap().into_iter().find(|(n, _)| n.starts_with("tips/")).unwrap().0;
b.load("damaged.pcbrushes", b"recoverable broken group".to_vec()).unwrap();
let (mut s, warnings) = session(b.clone());
assert!(!warnings.is_empty());
s.execute("brush.presets.save", json!({"name":"Unrelated brush"})).unwrap();
s.execute("brush.presets.delete", json!({"name":"Browser seam brush"})).unwrap();
assert_eq!(b.read("damaged.pcbrushes", 100).unwrap(), b"recoverable broken group");
assert!(b.read(&tip, MAX_TIP_BYTES).is_ok());
let (reloaded, warnings) = session(b.clone());
assert!(!warnings.is_empty());
assert!(reloaded.tools.presets.iter().any(|p| p.name == "Unrelated brush"));
assert!(!reloaded.tools.presets.iter().any(|p| p.name == "Browser seam brush"));
assert_eq!(b.read("damaged.pcbrushes", 100).unwrap(), b"recoverable broken group");
assert!(b.read(&tip, MAX_TIP_BYTES).is_ok());
}
#[test]
fn indexed_brush_store_coexists_with_imported_gradient_preferences() {
use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop, write};
let b = Bridge::default();
let (mut s, _) = session(b.clone());
import(&mut s);
let data = write(&[GrdGradient {
name: "Browser gradient".into(),
noise: false,
stops: vec![
GrdStop { location: 0.0, midpoint: 0.5, color: GrdColor::Foreground },
GrdStop { location: 1.0, midpoint: 0.5, color: GrdColor::Rgb([1.0, 0.0, 0.0]) },
],
opacity: vec![(0.0, 1.0, 0.5), (1.0, 0.5, 0.5)],
}]);
s.execute("gradient.presets.importGrd", json!({"data":photocraft_paint::tile::b64_encode(&data),"group":"Browser gradients"})).unwrap();
let prefs = s.prefs_to_json();
let (mut loaded, _) = session(b);
loaded.load_prefs_json(&prefs).unwrap();
assert_eq!(loaded.tools.presets, s.tools.presets);
assert_eq!(loaded.presets.gradients, s.presets.gradients);
assert!(loaded.presets.gradients.iter().any(|g| g.name == "Browser gradients"));
}
}
+211 -15
View File
@@ -1,26 +1,46 @@
//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner.
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use photocraft_codecs::{ChannelLayout, EncodeOptions, Image};
use photocraft_doc::Document;
use photocraft_engine::Session;
use photocraft_ui_egui::i18n;
use photocraft_ui_egui::served_fonts;
use photocraft_ui_egui::theme::ThemeKind;
use photocraft_ui_egui::{FileDialogAnswer, FileDialogRequest, PhotocraftApp, Services};
use wasm_bindgen::JsCast as _;
type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and
/// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster and Affinity documents, flat images, and
/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
const OPEN_EXTS: &[&str] = &[
"pcraft", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam",
"pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af",
"afdesign", "afphoto", "afpub",
"pcraft", "pdn", "ora", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm",
"ppm", "pam", "pfm", "fits", "fit", "fts", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd",
"svg", "svgz", "aco", "ase", "af", "afdesign", "afphoto", "afpub",
];
const SVG_EXTS: &[&str] = &["svg", "svgz"];
const CANVAS_ID: &str = "photocraft_canvas";
/// Fonts the host serves next to the page (`photocraft_ui_egui::served_fonts`): craft-fonts' manifest
/// format, each file relative to the site root. No manifest (a 404) means no served fonts.
const FONTS_MANIFEST: &str = "fonts/manifest.txt";
/// The served fonts: the manifest once read, and what the network has delivered.
#[derive(Default)]
struct ServedFonts {
/// Font files by family, each with its Subresource Integrity value when the manifest has one.
files: HashMap<String, Vec<(String, Option<String>)>>,
/// Families fetched or being fetched: each one once per page load.
fetched: HashSet<String>,
/// Downloaded files waiting for the next frame: (family, bytes).
arrived: Vec<(String, Vec<u8>)>,
}
type Served = Arc<Mutex<ServedFonts>>;
pub fn start() {
eframe::WebLogger::init(log::LevelFilter::Info).ok();
wasm_bindgen_futures::spawn_local(async {
@@ -41,6 +61,16 @@ pub fn start() {
{
create.instance_descriptor.backends = eframe::wgpu::Backends::GL;
}
// Hydrate before constructing an interactive session: a late load must never undo a
// user deletion/reorder. Storage denial or timeout still opens a usable session.
let (database, presets, mut preset_warnings) = match crate::indexed_presets::load().await {
Ok((db, bridge, warnings)) => (Some(db), bridge, warnings),
Err(e) => {
let bridge = crate::preset_bridge::Bridge::default();
bridge.unavailable(e);
(None, bridge, Vec::new())
}
};
let pen_target = canvas.clone();
let result = eframe::WebRunner::new()
.start(
@@ -49,7 +79,14 @@ pub fn start() {
Box::new(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, ThemeKind::Pro);
let inbox: Inbox = Arc::default();
let mut app = PhotocraftApp::new(Session::new(), services(inbox.clone()));
let served: Served = Arc::default();
load_font_manifest(served.clone(), cc.egui_ctx.clone());
let (session, warnings) = crate::preset_bridge::session(presets.clone());
preset_warnings.extend(warnings);
let mut app = PhotocraftApp::new(session, services(inbox.clone()));
if !preset_warnings.is_empty() {
photocraft_ui_egui::notices::post(&mut app, i18n::t("Some brush presets could not be loaded"), preset_warnings, true, None);
}
listen_pen(&pen_target, app.stylus.feed.clone());
app.set_theme(&cc.egui_ctx, ThemeKind::Pro);
if let Some(rs) = cc.wgpu_render_state.clone()
@@ -60,7 +97,7 @@ pub fn start() {
}
let unsaved = Arc::new(AtomicBool::new(false));
guard_unload(unsaved.clone());
Ok(Box::new(WebShell { app, inbox, unsaved }))
Ok(Box::new(WebShell { app, inbox, unsaved, served, database, presets }))
}),
)
.await;
@@ -125,6 +162,62 @@ fn query() -> String {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
/// Reads the served font manifest, if the host has one, and lists its families in the font menus.
fn load_font_manifest(served: Served, ctx: egui::Context) {
wasm_bindgen_futures::spawn_local(async move {
// Most hosts serve no fonts: a missing manifest is the normal case, not an error.
let Ok(bytes) = fetch_bytes(FONTS_MANIFEST, None).await else { return };
let text = String::from_utf8_lossy(&bytes);
// A host that answers unknown paths with its HTML page (single-page app fallback).
if text.trim_start().starts_with('<') {
return;
}
let (fonts, skipped) = served_fonts::parse_manifest(&text);
for s in skipped {
log::warn!("{FONTS_MANIFEST}: skipped {s}");
}
let mut files: HashMap<String, Vec<(String, Option<String>)>> = HashMap::new();
for f in &fonts {
files.entry(f.family.clone()).or_default().push((f.file.clone(), f.integrity.clone()));
}
log::info!("photocraft-web: {} served font families", files.len());
served.lock().unwrap_or_else(|e| e.into_inner()).files = files;
// The families for the font menus, and the script fallbacks (the manifest's `scripts`).
served_fonts::add_fonts(&fonts);
// Fetch now the fallbacks of the scripts the browser's languages use (an Arabic reader gets
// the Arabic font before typing); the rest is fetched when text or a font menu needs it.
served_fonts::request_for_languages(browser_languages().iter().map(String::as_str));
ctx.request_repaint();
});
}
/// The browser's preferred languages (`navigator.languages`, e.g. `["ar-EG", "en"]`).
fn browser_languages() -> Vec<String> {
web_sys::window().map(|w| w.navigator().languages().iter().filter_map(|l| l.as_string()).collect()).unwrap_or_default()
}
/// GET `url` (relative to the page) and read the whole body. With `integrity` (a Subresource
/// Integrity value), the browser rejects a body whose hash differs.
async fn fetch_bytes(url: &str, integrity: Option<&str>) -> Result<Vec<u8>, String> {
use wasm_bindgen_futures::JsFuture;
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
let window = web_sys::window().ok_or("no window")?;
let request = match integrity {
Some(sri) => {
let init = web_sys::RequestInit::new();
init.set_integrity(sri);
window.fetch_with_str_and_init(url, &init)
}
None => window.fetch_with_str(url),
};
let resp: web_sys::Response = JsFuture::from(request).await.map_err(js)?.dyn_into().map_err(|_| "not a Response")?;
if !resp.ok() {
return Err(format!("HTTP {}", resp.status()));
}
let body = JsFuture::from(resp.array_buffer().map_err(js)?).await.map_err(js)?;
Ok(js_sys::Uint8Array::new(&body).to_vec())
}
/// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously,
/// so the app's own drop path can't handle them) and feed them through the inbox.
struct WebShell {
@@ -132,6 +225,61 @@ struct WebShell {
inbox: Inbox,
/// Read by the `beforeunload` listener ([`guard_unload`]).
unsaved: Arc<AtomicBool>,
served: Served,
database: Option<web_sys::IdbDatabase>,
presets: crate::preset_bridge::Bridge,
}
impl WebShell {
fn save_presets(&mut self, ctx: &egui::Context) {
if let Some(db) = self.database.clone()
&& let Some(batch) = self.presets.begin()
{
let presets = self.presets.clone();
let wake = ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let result = crate::indexed_presets::write(&db, &batch).await;
if let Err(e) = &result {
log::error!("Could not save browser presets: {e}");
}
presets.finish(batch, result);
wake.request_repaint();
});
}
self.unsaved.store(self.app.has_unsaved_work() || self.presets.unsaved(), Ordering::Relaxed);
}
/// Fetches the served families asked for (picked in a font menu, or needed by a layout) and
/// installs the files that arrived.
fn serve_fonts(&mut self, ctx: &egui::Context) {
let requested = served_fonts::take_requests();
let (fetch, arrived) = {
let mut s = self.served.lock().unwrap_or_else(|e| e.into_inner());
let mut fetch = Vec::new();
for family in requested {
if let Some(files) = s.files.get(&family).cloned()
&& s.fetched.insert(family.clone())
{
fetch.extend(files.into_iter().map(|(file, integrity)| (family.clone(), file, integrity)));
}
}
(fetch, std::mem::take(&mut s.arrived))
};
for (family, file, integrity) in fetch {
let served = self.served.clone();
let ctx = ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
match fetch_bytes(&file, integrity.as_deref()).await {
Ok(bytes) => {
served.lock().unwrap_or_else(|e| e.into_inner()).arrived.push((family, bytes));
ctx.request_repaint();
}
Err(e) => log::error!("couldn't fetch served font {file}: {e}"),
}
});
}
served_fonts::install(&mut self.app, arrived);
}
}
impl eframe::App for WebShell {
@@ -151,19 +299,46 @@ impl eframe::App for WebShell {
}
});
}
self.serve_fonts(ctx);
self.app.logic(ctx, frame);
self.unsaved.store(self.app.has_unsaved_work(), Ordering::Relaxed);
self.save_presets(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
let error = self.presets.error();
if error.is_some() || self.presets.unsaved() {
egui::Panel::top("browser_preset_storage").show(ui, |ui| {
if let Some(error) = error {
let tokens = photocraft_ui_egui::theme::Tokens::for_kind(self.app.ui.theme);
// Put retry first so floating brush windows cannot cover the control.
ui.horizontal_wrapped(|ui| {
if self.database.is_some() && ui.button(i18n::t("Retry saving presets")).clicked() {
self.presets.retry();
ui.ctx().request_repaint();
}
ui.colored_label(tokens.warning, i18n::fmt(i18n::t("Brush preset changes are not saved: {error}"), &[("error", &error)]));
});
ui.label(if self.database.is_some() {
i18n::t("Keep this tab open to retain your brushes.")
} else {
i18n::t("Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them.")
});
} else {
ui.label(i18n::t("Saving brush presets… Keep this tab open until saving finishes."));
}
});
}
self.app.ui(ui, frame);
self.save_presets(ui.ctx());
}
}
fn services(inbox: Inbox) -> Services {
Services {
screen_pick: screen_color_service(),
import: Some(Box::new(|name: &str, bytes: &[u8]| photocraft_io::import(name, bytes).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()))),
import: Some(Box::new(|name: &str, bytes: &[u8], max_svg_group_depth: usize| {
photocraft_io::import_with_svg_group_depth(name, bytes, max_svg_group_depth).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string())
})),
export: Some(Box::new(|doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings| {
let mut opts = photocraft_io::ExportOptions::default();
if let Some(q) = settings.jpeg_quality {
@@ -175,15 +350,35 @@ fn services(inbox: Inbox) -> Services {
}
opts.tiff_layers = settings.tiff_layers;
opts.xmp = if settings.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None };
opts.tga_bits = settings.tga_bits;
opts.image_previews = settings.image_previews;
photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string())
})),
file_dialog: Some(Box::new(|request, _parent, reply| match request {
// The browser's file picker hands over the file's contents, not a path.
FileDialogRequest::Open { .. } => wasm_bindgen_futures::spawn_local(async move {
let picked = rfd::AsyncFileDialog::new().add_filter("All Formats", OPEN_EXTS).pick_file().await;
let answer = match picked {
Some(file) => Some(FileDialogAnswer::Contents(file.file_name(), file.read().await)),
None => None,
// The browser's file picker hands over the files' contents, not paths. File › Open
// asks for several files (`multiple`), each opened in its own tab.
FileDialogRequest::Open { multiple, extensions, .. } => wasm_bindgen_futures::spawn_local(async move {
let dialog = if let Some(exts) = extensions {
rfd::AsyncFileDialog::new().add_filter("Supported Files", &exts)
} else {
rfd::AsyncFileDialog::new().add_filter("All Formats", OPEN_EXTS).add_filter("SVG", SVG_EXTS)
};
let answer = if multiple {
match dialog.pick_files().await {
Some(picked) if !picked.is_empty() => {
let mut files = Vec::with_capacity(picked.len());
for file in picked {
files.push((file.file_name(), file.read().await));
}
Some(FileDialogAnswer::ContentsMany(files))
}
_ => None,
}
} else {
match dialog.pick_file().await {
Some(file) => Some(FileDialogAnswer::Contents(file.file_name(), file.read().await)),
None => None,
}
};
reply.send(answer);
}),
@@ -247,6 +442,7 @@ fn mime_for(name: &str) -> &'static str {
Some("webp") => "image/webp",
Some("gif") => "image/gif",
Some("psd" | "psb") => "image/vnd.adobe.photoshop",
Some("ora") => "image/openraster",
_ => "application/octet-stream",
}
}
+7 -4
View File
@@ -43,7 +43,8 @@ ron = "0.12"
[target.'cfg(target_os = "macos")'.dependencies]
# Safe CoreGraphics bindings, compatible with the existing macOS 11 deployment target.
core-graphics2 = { version = "=0.6.1", default-features = false, features = ["display", "window", "link"] }
# `event` (CGEventSource) is used for the Caps Lock poll (#1758).
core-graphics2 = { version = "=0.6.1", default-features = false, features = ["display", "window", "link", "event"] }
# Finder double-click / Open With / Dock drops arrive as Apple events; this small audited crate
# registers the handler (Objective-C interop needs unsafe, which our workspace forbids) behind a
# safe API. Pinned exactly: review the diff before bumping.
@@ -63,7 +64,8 @@ dispatch2 = { version = "=0.3.1", default-features = false, features = ["std"] }
# Drop position on X11 (`cursor.rs`): pure-Rust X client, already in Cargo.lock; pinned exactly.
[target.'cfg(target_os = "linux")'.dependencies]
x11rb = { version = "=0.13.2", default-features = false, features = ["image", "randr"] }
photocraft-cms = { workspace = true }
x11rb = { version = "=0.13.2", default-features = false, features = ["image", "randr", "xkb"] }
# Wayland desktop color selection through the existing XDG portal transport.
zbus = "=5.19.0"
# Already used by the portal stack; bounded waits let cancelling close the OS request.
@@ -73,8 +75,9 @@ async-io = "=2.6.0"
# re-export winit's `EventLoopBuilderExtX11`. Already in Cargo.lock (eframe); pinned exactly.
winit = { version = "=0.30.13", default-features = false, features = ["x11"] }
# Drop position on Windows (`cursor.rs`): safe Win32 wrappers (GetCursorPos), no dependencies of
# its own. Pinned exactly: review the diff before bumping.
# Safe Win32 wrappers on Windows: the pointer position for file drops (`cursor.rs`,
# GetCursorPos) and the window frame for the custom title bar (`window_frame.rs`, window styles),
# no dependencies of its own. Pinned exactly: review the diff before bumping.
[target.'cfg(target_os = "windows")'.dependencies]
# Safe Windows screen-capture bindings; Linux uses the pure-Rust X11 client/portal.
xcap = "=0.9.8"
+218
View File
@@ -0,0 +1,218 @@
//! Linux desktop colour scheme, including Wayland compositors that do not report a winit theme.
#[cfg(target_os = "linux")]
const PORTAL_NAMESPACE: &str = "org.freedesktop.appearance";
#[cfg(target_os = "linux")]
const PORTAL_KEY: &str = "color-scheme";
#[cfg(target_os = "linux")]
fn portal_proxy() -> Option<zbus::blocking::Proxy<'static>> {
let conn = zbus::blocking::connection::Builder::session().ok()?.method_timeout(std::time::Duration::from_secs(2)).build().ok()?;
zbus::blocking::Proxy::new(&conn, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Settings").ok()
}
#[cfg(target_os = "linux")]
fn portal_theme(proxy: &zbus::blocking::Proxy<'_>) -> Option<egui::Theme> {
let value: zbus::zvariant::OwnedValue = proxy.call("Read", &(PORTAL_NAMESPACE, PORTAL_KEY)).ok()?;
decode(portal_code(value)?)
}
#[cfg(target_os = "linux")]
fn portal_code(value: zbus::zvariant::OwnedValue) -> Option<u32> {
let mut value: zbus::zvariant::Value<'_> = value.into();
// The Settings.Read result is a variant; some portals nest another variant inside it.
for _ in 0..4 {
match value {
zbus::zvariant::Value::Value(inner) => value = *inner,
other => return u32::try_from(other).ok(),
}
}
None
}
#[cfg(target_os = "linux")]
fn decode(code: u32) -> Option<egui::Theme> {
match code {
1 => Some(egui::Theme::Dark),
2 => Some(egui::Theme::Light),
_ => None,
}
}
/// One-shot fallback for desktops without the settings portal. It runs once at start-up, by
/// absolute path, and is never repeated.
#[cfg(target_os = "linux")]
fn gtk_theme() -> Option<egui::Theme> {
let exe = ["/usr/bin/gsettings", "/bin/gsettings", "/usr/local/bin/gsettings"].into_iter().find(|p| std::path::Path::new(p).is_file())?;
let output = std::process::Command::new(exe).args(["get", "org.gnome.desktop.interface", "color-scheme"]).output().ok()?;
if !output.status.success() {
return None;
}
parse_gtk_scheme(std::str::from_utf8(&output.stdout).ok()?)
}
#[cfg(target_os = "linux")]
fn parse_gtk_scheme(s: &str) -> Option<egui::Theme> {
match s.trim().trim_matches('\'') {
"prefer-dark" => Some(egui::Theme::Dark),
"prefer-light" => Some(egui::Theme::Light),
_ => None,
}
}
#[cfg(target_os = "linux")]
fn code_of(theme: Option<egui::Theme>) -> u8 {
match theme {
Some(egui::Theme::Dark) => 1,
Some(egui::Theme::Light) => 2,
None => 0,
}
}
#[cfg(target_os = "linux")]
fn portal_startup<T>(subscribe: impl FnOnce(), read: impl FnOnce() -> T) -> T {
subscribe();
read()
}
/// Reads the colour scheme once, then follows the portal's `SettingChanged` signal. There is no
/// polling: the worker sleeps in the signal iterator and wakes the UI only when the value changes.
pub fn service() -> Option<photocraft_ui_egui::SystemThemeFn> {
#[cfg(target_os = "linux")]
{
start(|publisher| {
let proxy = portal_proxy();
// Subscribe before the first read, so a change during start-up isn't lost.
let mut signals = None;
let initial = portal_startup(
|| signals = proxy.as_ref().and_then(|proxy| proxy.receive_signal("SettingChanged").ok()),
|| proxy.as_ref().and_then(portal_theme).or_else(gtk_theme),
);
publisher.publish(initial);
let Some(signals) = signals else { return };
for message in signals {
let Ok((namespace, key, changed)) = message.body().deserialize::<(String, String, zbus::zvariant::OwnedValue)>() else {
continue;
};
if namespace != PORTAL_NAMESPACE || key != PORTAL_KEY {
continue;
}
publisher.publish(portal_code(changed).and_then(decode));
}
})
}
#[cfg(not(target_os = "linux"))]
{
None
}
}
/// The worker's handle on the shared value. Every change wakes the registered UI, including the
/// first read when it lands after the start-up wait below.
#[cfg(target_os = "linux")]
struct Publisher {
value: std::sync::Arc<std::sync::atomic::AtomicU8>,
wake: std::sync::Arc<std::sync::OnceLock<egui::Context>>,
ready: std::sync::mpsc::Sender<()>,
}
#[cfg(target_os = "linux")]
impl Publisher {
fn publish(&self, theme: Option<egui::Theme>) {
let code = code_of(theme);
if self.value.swap(code, std::sync::atomic::Ordering::Relaxed) != code
&& let Some(ctx) = self.wake.get()
{
ctx.request_repaint();
}
let _ = self.ready.send(());
}
}
/// Runs `worker` on its own thread and waits up to 250 ms for its first value, so a fast desktop
/// answers before the first frame.
#[cfg(target_os = "linux")]
fn start(worker: impl FnOnce(&Publisher) + Send + 'static) -> Option<photocraft_ui_egui::SystemThemeFn> {
use std::sync::{Arc, OnceLock, atomic::AtomicU8};
let value = Arc::new(AtomicU8::new(0));
let wake: Arc<OnceLock<egui::Context>> = Arc::new(OnceLock::new());
let (ready, wait) = std::sync::mpsc::channel();
let publisher = Publisher { value: Arc::clone(&value), wake: Arc::clone(&wake), ready };
std::thread::Builder::new().name("appearance-portal".into()).spawn(move || worker(&publisher)).ok()?;
let _ = wait.recv_timeout(std::time::Duration::from_millis(250));
Some(Box::new(move |ctx| {
let _ = wake.set(ctx.clone());
decode(u32::from(value.load(std::sync::atomic::Ordering::Relaxed)))
}))
}
#[cfg(test)]
mod tests {
#[cfg(target_os = "linux")]
#[test]
fn startup_keeps_changes_emitted_during_initial_read() {
use std::cell::Cell;
for (initial_value, changed_value) in [(2, 1), (1, 2), (2, 2)] {
let subscribed = Cell::new(false);
let mut portal_value = initial_value;
let mut pending_signal = None;
let initial = super::portal_startup(
|| subscribed.set(true),
|| {
let initial = portal_value;
portal_value = changed_value;
if subscribed.get() && portal_value != initial {
pending_signal = Some(portal_value);
}
initial
},
);
let cached = pending_signal.unwrap_or(initial);
assert_eq!(cached, changed_value, "portal changed during startup but cached {cached}");
}
}
#[cfg(target_os = "linux")]
#[test]
fn portal_scheme_values() {
assert_eq!(super::decode(0), None);
assert_eq!(super::decode(1), Some(egui::Theme::Dark));
assert_eq!(super::decode(2), Some(egui::Theme::Light));
assert_eq!(super::decode(9), None);
let nested = zbus::zvariant::Value::Value(Box::new(zbus::zvariant::Value::Value(Box::new(zbus::zvariant::Value::U32(2)))));
assert_eq!(super::portal_code(zbus::zvariant::OwnedValue::try_from(nested).unwrap()), Some(2));
assert_eq!(super::parse_gtk_scheme("'prefer-light'\n"), Some(egui::Theme::Light));
assert_eq!(super::parse_gtk_scheme("'prefer-dark'\n"), Some(egui::Theme::Dark));
assert_eq!(super::parse_gtk_scheme("'default'\n"), None);
}
/// #2798: a first read that misses the start-up wait still wakes the idle UI.
#[cfg(target_os = "linux")]
#[test]
fn late_initial_read_requests_repaint() {
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
let (release, gate) = std::sync::mpsc::channel::<()>();
let (done, finished) = std::sync::mpsc::channel::<()>();
let reader = super::start(move |publisher| {
let _ = gate.recv();
publisher.publish(Some(egui::Theme::Light));
let _ = done.send(());
})
.expect("worker thread");
let ctx = egui::Context::default();
let repaints = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&repaints);
ctx.set_request_repaint_callback(move |_| {
counter.fetch_add(1, Ordering::Relaxed);
});
assert_eq!(reader(&ctx), None, "start-up wait elapsed without an answer");
release.send(()).unwrap();
finished.recv().unwrap();
assert_eq!(repaints.load(Ordering::Relaxed), 1);
assert_eq!(reader(&ctx), Some(egui::Theme::Light));
}
}
+121
View File
@@ -0,0 +1,121 @@
//! Caps Lock state, read from the OS once per frame so the canvas can show the precise crosshair
//! for painting tools whatever the cursor preference (Photoshop's ⇪ behaviour, #1758).
//!
//! winit and egui have no Caps Lock key or modifier — `egui::Key` has no variant, `Modifiers` no
//! field, and egui-winit's `key_from_named_key` drops the `NamedKey::CapsLock` key event before it
//! reaches the app. So the state is polled here instead, from the platform:
//!
//! - **X11 (and XWayland)**: XKB's Lock modifier state, via the pure-Rust x11rb client. The app
//! already opens on X11 when the `Preferences › Performance › Linux display server` preference
//! asks for it, and on Wayland through XWayland for pen support, so this is the common path.
//! - **Windows**: `GetKeyState(VK_CAPITAL)` through the safe `winsafe` binding.
//! - **macOS**: `CGEventSourceFlagsState` (`kCGEventFlagAlphaShift`) through `core-graphics2`.
//! - **Native Wayland**: there is no global keyboard-state query (no equivalent of XKB GetState or
//! VK_CAPITAL); the service is `None` there and Caps Lock leaves the cursor preference alone.
//!
//! No `unsafe`: every OS call goes through a safe binding.
pub use platform::service;
#[cfg(target_os = "macos")]
mod platform {
use core_graphics2::event_source::CGEventSource;
use core_graphics2::event_types::{CGEventFlags, CGEventSourceStateID};
use photocraft_ui_egui::CapsLockFn;
pub fn service(_cc: &eframe::CreationContext<'_>) -> Option<CapsLockFn> {
Some(Box::new(|| {
let flags = CGEventSource::flags_state(CGEventSourceStateID::CombinedSessionState);
flags.contains(CGEventFlags::MaskAlphaShift)
}))
}
}
#[cfg(target_os = "windows")]
mod platform {
use photocraft_ui_egui::CapsLockFn;
pub fn service(_cc: &eframe::CreationContext<'_>) -> Option<CapsLockFn> {
Some(Box::new(|| {
// The second element of the pair is "key toggled on", which is Caps Lock's state.
let (_, toggled) = winsafe::GetKeyState(winsafe::co::VK::CAPITAL);
toggled
}))
}
}
#[cfg(target_os = "linux")]
mod platform {
use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle};
use photocraft_ui_egui::CapsLockFn;
use x11rb::protocol::xkb::{self, ConnectionExt as _};
use x11rb::protocol::xproto::ModMask;
use x11rb::rust_connection::RustConnection;
pub fn service(cc: &eframe::CreationContext<'_>) -> Option<CapsLockFn> {
// XKB keyboard state lives on the X server. The window is our window: whether it is X11
// (or XWayland) is whether there is an X server to ask. Native Wayland has no such
// connection and degrades to the cursor preference (no service).
let is_x11 = matches!(cc.window_handle().ok()?.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_));
if !is_x11 {
return None;
}
// Lazily opened on first use and kept: the Lock-modifier mask is stable per keymap, so it
// is queried once and only the toggle state is re-read every frame.
let mut conn: Option<(RustConnection, ModMask)> = None;
// After a failure, wait before reconnecting (and warn once per failure), so a broken X
// connection doesn't reconnect and log on every frame.
let mut retry_at: Option<std::time::Instant> = None;
Some(Box::new(move || {
if retry_at.is_some_and(|t| std::time::Instant::now() < t) {
return false;
}
match caps_lock_on(&mut conn) {
Ok(on) => {
retry_at = None;
on
}
Err(error) => {
log::warn!("couldn't read the Caps Lock state: {error}");
conn = None;
retry_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(5));
false
}
}
}))
}
/// Caps Lock is on when the Lock modifier is both engaged (`locked_mods`) and present in the
/// keyboard's indicator map (so a re-mapped lock key is still recognised).
fn caps_lock_on(conn: &mut Option<(RustConnection, ModMask)>) -> Result<bool, String> {
if conn.is_none() {
let (c, _) = RustConnection::connect(None).map_err(|e| e.to_string())?;
// XKB requests need the extension active first (it is, on every modern server).
let enabled = c.xkb_use_extension(1, 0).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?;
if !enabled.supported {
return Err("the X server has no XKB extension".into());
}
let device = u16::from(xkb::ID::USE_CORE_KBD);
// Indicator 0 is the Caps Lock indicator; its `.mods` is the Lock-modifier mask.
let map = c.xkb_get_indicator_map(device, 1).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?;
let lock = map.maps.first().map_or(ModMask::LOCK, |m| m.mods);
*conn = Some((c, lock));
}
let (conn, lock) = match conn.as_ref() {
Some((conn, lock)) => (conn, *lock),
None => return Err("no X connection".into()),
};
let device = u16::from(xkb::ID::USE_CORE_KBD);
let state = conn.xkb_get_state(device).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?;
Ok(u16::from(state.locked_mods) & u16::from(lock) != 0)
}
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
mod platform {
use photocraft_ui_egui::CapsLockFn;
pub fn service(_cc: &eframe::CreationContext<'_>) -> Option<CapsLockFn> {
None
}
}
+6 -3
View File
@@ -5,13 +5,14 @@ use std::io::{BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::{Duration, Instant};
use std::time::Instant;
use photocraft_automation::budgets::write_reply;
use photocraft_automation::security::{
ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream, read_bounded_line,
};
use photocraft_ui_egui::ControlRequest;
use photocraft_ui_egui::control::{REPLY_DEADLINE, timeout_error};
use serde_json::{Value, json};
pub fn start(port: u16, token: String, ctx: egui::Context) -> Receiver<ControlRequest> {
@@ -83,14 +84,15 @@ fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
let params = msg.get("params").cloned().unwrap_or(json!({}));
let deadline = Instant::now() + Duration::from_secs(60);
let deadline = Instant::now() + REPLY_DEADLINE;
let (mut req, rrx) = ControlRequest::new(method, params);
req.deadline = Some(deadline);
if tx.send(req).is_err() {
break;
}
ctx.request_repaint();
let mut r = rrx.recv_timeout(deadline.saturating_duration_since(Instant::now())).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"}));
let mut r =
rrx.recv_timeout(deadline.saturating_duration_since(Instant::now())).unwrap_or_else(|_| json!({"ok": false, "error": timeout_error()}));
if let Some(o) = r.as_object_mut() {
o.insert("id".into(), id);
}
@@ -111,6 +113,7 @@ fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::
mod tests {
use super::*;
use std::io::BufRead;
use std::time::Duration;
#[test]
fn oversized_reply_preserves_framing_id_and_the_next_control_request() {
+129
View File
@@ -0,0 +1,129 @@
//! Why a File › Open / Save dialog may never appear on Linux (#3354).
//!
//! `rfd` talks to the XDG file-chooser portal through `libdbus-1`, which it loads at runtime, and
//! falls back to `zenity`. When neither works (a minimal window-manager session without a portal
//! backend) it logs the failure and answers "nothing picked", which the app took for Cancel: the
//! menu item did nothing and said nothing. [`start`] looks for the pieces once, in the background,
//! and [`known_problem`] returns what to install when a dialog came back empty and none of them
//! is there.
//!
//! The probe only ever explains an empty answer; it never stops a dialog from opening. Anything
//! it can't tell counts as present, so a working system never sees the message.
use std::sync::OnceLock;
/// What the probe found. `None` means it couldn't tell, which counts as present.
// Only Linux probes; the types and helpers stay testable on every platform.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Findings {
/// `libdbus-1.so.3` is in the linker cache (`rfd` loads it for the portal).
pub libdbus: Option<bool>,
/// The session bus has the portal's `FileChooser` interface (a portal and a backend for it).
pub file_chooser_portal: Option<bool>,
/// `zenity` is on `PATH` (`rfd`'s fallback).
pub zenity: bool,
}
/// The message for `findings`, or `None` when some file dialog should work.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub fn problem(findings: Findings) -> Option<String> {
let portal = findings.libdbus != Some(false) && findings.file_chooser_portal != Some(false);
if portal || findings.zenity {
return None;
}
let cause = if findings.libdbus == Some(false) { "libdbus is missing" } else { "no desktop portal offers a file chooser" };
Some(format!(
"No file dialog can open: {cause}. Install xdg-desktop-portal with a backend (xdg-desktop-portal-gtk, -kde or -gnome) and libdbus, or zenity. Meanwhile, drop a file onto the window or paste a copied image."
))
}
static RESULT: OnceLock<Option<String>> = OnceLock::new();
/// The problem found by [`start`], once it has finished.
pub fn known_problem() -> Option<String> {
RESULT.get().cloned().flatten()
}
/// Whether `program` is an executable file in one of the `path` directories.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn on_path(program: &str, path: &std::ffi::OsStr) -> bool {
std::env::split_paths(path).any(|dir| dir.join(program).is_file())
}
/// Look for the file dialog backends on a helper thread (the portal call can take a moment).
#[cfg(target_os = "linux")]
pub fn start() {
let spawned = std::thread::Builder::new().name("file dialog probe".into()).spawn(|| {
let findings = Findings {
libdbus: crate::linux_libs::cached("libdbus-1.so.3"),
file_chooser_portal: file_chooser_portal(),
zenity: std::env::var_os("PATH").is_some_and(|path| on_path("zenity", &path)),
};
log::info!("file dialog backends: {findings:?}");
let _ = RESULT.set(problem(findings));
});
if let Err(e) = spawned {
log::warn!("couldn't start the file dialog probe: {e}");
}
}
/// Whether the portal's `FileChooser` interface is on the session bus: `Some(false)` only when the
/// bus or the interface is definitely absent, `None` for anything inconclusive (a slow reply).
#[cfg(target_os = "linux")]
fn file_chooser_portal() -> Option<bool> {
let Ok(conn) = zbus::blocking::connection::Builder::session().and_then(|b| b.method_timeout(std::time::Duration::from_secs(5)).build()) else {
return Some(false);
};
let proxy = zbus::blocking::proxy::Builder::<zbus::blocking::Proxy<'_>>::new(&conn)
.destination("org.freedesktop.portal.Desktop")
.and_then(|b| b.path("/org/freedesktop/portal/desktop"))
.and_then(|b| b.interface("org.freedesktop.portal.FileChooser"))
.and_then(|b| b.cache_properties(zbus::proxy::CacheProperties::No).build())
.ok()?;
match proxy.get_property::<u32>("version") {
Ok(_) => Some(true),
Err(zbus::Error::MethodError(name, _, _)) => {
let name = name.as_str();
let absent = ["ServiceUnknown", "UnknownObject", "UnknownInterface", "UnknownProperty"].iter().any(|n| name.ends_with(n));
absent.then_some(false)
}
Err(_) => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn found(libdbus: Option<bool>, file_chooser_portal: Option<bool>, zenity: bool) -> Findings {
Findings { libdbus, file_chooser_portal, zenity }
}
#[test]
fn a_working_backend_is_not_reported() {
assert_eq!(problem(found(Some(true), Some(true), false)), None, "portal");
assert_eq!(problem(found(Some(false), Some(false), true)), None, "zenity alone");
assert_eq!(problem(found(None, None, false)), None, "unknown counts as present");
assert_eq!(problem(found(Some(true), None, false)), None, "slow portal reply");
}
#[test]
fn nothing_to_show_a_dialog_with_is_explained() {
let no_portal = problem(found(Some(true), Some(false), false)).unwrap();
assert!(no_portal.contains("no desktop portal offers a file chooser") && no_portal.contains("xdg-desktop-portal"), "{no_portal}");
let no_dbus = problem(found(Some(false), Some(true), false)).unwrap();
assert!(no_dbus.contains("libdbus is missing"), "{no_dbus}");
}
#[test]
fn programs_are_found_on_the_given_path() {
let dir = std::env::temp_dir().join(format!("photocraft-probe-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("zenity"), b"").unwrap();
let path = std::env::join_paths([std::path::Path::new("/nonexistent"), dir.as_path()]).unwrap();
assert!(on_path("zenity", &path));
assert!(!on_path("kdialog", &path));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+69 -6
View File
@@ -16,7 +16,9 @@
//! overrides everything, and `--safe-gpu` forces the CPU path for one launch.
//!
//! "CPU" composites on the CPU and draws the window with a software adapter where the platform
//! has one (WARP on Windows, llvmpipe over GL elsewhere).
//! has one (WARP on Windows, llvmpipe over GL elsewhere). On Linux a GL adapter that can't present
//! (NVIDIA's EGL, which also hides llvmpipe) falls back to a Vulkan adapter for the window only
//! (#1337); before, CPU mode then couldn't start at all.
use std::fs::{File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
@@ -189,7 +191,9 @@ pub fn backends(plan: &Plan, os: Os) -> Option<wgpu::Backends> {
GpuBackend::Cpu => match os {
Os::Windows => wgpu::Backends::DX12,
Os::Mac => wgpu::Backends::METAL,
Os::Other => wgpu::Backends::GL,
// Vulkan only for the window when no GL adapter can present (`rank`): with NVIDIA's
// EGL the GL adapter can't, and CPU mode failed every start (#1337).
Os::Other => wgpu::Backends::GL | wgpu::Backends::VULKAN,
},
})
}
@@ -222,8 +226,10 @@ pub struct Candidate {
/// Rank of an adapter (lower is better): high-performance device types first (egui's power
/// preference) or software adapters first for `cpu`; then backends, with DX12 before Vulkan for
/// Intel on Windows.
fn rank(a: &Candidate, backend: GpuBackend, os: Os) -> (u8, u8) {
/// Intel on Windows. For `cpu`, any GL adapter comes before Vulkan, which is only the fallback
/// for presenting the window (see [`backends`]).
fn rank(a: &Candidate, backend: GpuBackend, os: Os) -> (u8, u8, u8) {
let fallback = u8::from(backend == GpuBackend::Cpu && a.backend == wgpu::Backend::Vulkan);
let ty = match a.device_type {
wgpu::DeviceType::DiscreteGpu => 0,
wgpu::DeviceType::IntegratedGpu => 1,
@@ -243,7 +249,7 @@ fn rank(a: &Candidate, backend: GpuBackend, os: Os) -> (u8, u8) {
wgpu::Backend::Gl => 3,
wgpu::Backend::BrowserWebGpu | wgpu::Backend::Noop => 4,
};
(ty, be)
(fallback, ty, be)
}
/// The adapter to use among `adapters` (`None` when there is none).
@@ -261,6 +267,14 @@ pub fn intel_dx12_applied(adapters: &[Candidate], chosen: usize, os: Os) -> bool
&& adapters.iter().any(|a| a.vendor == INTEL && a.backend == wgpu::Backend::Vulkan)
}
/// wgpu compiles indirect-call validation shaders inside `request_device`; Metal's compiler
/// crashes on them on old Intel Macs (Iris Pro, GPUFamily 1 on Monterey), so no mode could start
/// (#3107). Only Intel Macs skip them: PhotoCraft issues no indirect draws or dispatches, but every
/// other GPU keeps wgpu's default. `WGPU_VALIDATION_INDIRECT_CALL=1` still wins.
fn skips_indirect_validation(os: Os, intel: bool) -> bool {
os == Os::Mac && intel
}
/// Configure eframe's wgpu setup for `plan`: instance backends, the DX12 shader compiler, adapter
/// selection (Intel on Windows, software adapters for `cpu`) and the marker update once the
/// adapter is chosen. `note` receives a remark for System Info (e.g. the Intel default).
@@ -269,6 +283,9 @@ pub fn configure(setup: &mut egui_wgpu::WgpuSetup, plan: &Plan, os: Os, sentinel
if let Some(b) = backends(plan, os) {
create.instance_descriptor.backends = b;
}
if skips_indirect_validation(os, cfg!(target_arch = "x86_64")) {
create.instance_descriptor.flags = create.instance_descriptor.flags.difference(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
}
if os == Os::Windows {
let exe = std::env::current_exe().ok();
let env = std::env::var("WGPU_DX12_COMPILER").ok();
@@ -529,7 +546,7 @@ mod tests {
let p = plan(Vulkan, Some(&crashed("vulkan", "vulkan")), None, true, Os::Other);
assert_eq!((p.backend, p.remember), (Cpu, false));
assert_eq!(backends(&p, Os::Windows), Some(wgpu::Backends::DX12));
assert_eq!(backends(&p, Os::Other), Some(wgpu::Backends::GL));
assert_eq!(backends(&p, Os::Other), Some(wgpu::Backends::GL | wgpu::Backends::VULKAN));
assert_eq!(backends(&p, Os::Mac), Some(wgpu::Backends::METAL));
}
@@ -569,6 +586,28 @@ mod tests {
assert_eq!(pick(&a[..1], Cpu, Os::Windows), Some(0));
}
/// #1337: on Linux with NVIDIA, the only GL adapter (NVIDIA's EGL) can't present, so CPU mode
/// found no adapter and never started. GL still wins whenever it can present.
#[test]
fn cpu_on_linux_falls_back_to_vulkan_only_when_gl_cannot_present() {
use wgpu::{Backend as B, DeviceType as T};
const NVIDIA: u32 = 0x10de;
let llvmpipe = cand(0x10005, T::Cpu, B::Gl);
let nvidia_gl = cand(NVIDIA, T::DiscreteGpu, B::Gl);
let nvidia_vk = cand(NVIDIA, T::DiscreteGpu, B::Vulkan);
let lavapipe = cand(0x10005, T::Cpu, B::Vulkan);
// GL presents: same choice as GL-only, software first, then hardware GL over any Vulkan.
assert_eq!(pick(&[nvidia_vk, lavapipe, llvmpipe], Cpu, Os::Other), Some(2));
assert_eq!(pick(&[nvidia_vk, lavapipe, nvidia_gl], Cpu, Os::Other), Some(2));
// GL can't present: Vulkan for the window, software first.
let mut gl = nvidia_gl;
gl.surface_ok = false;
assert_eq!(pick(&[gl, nvidia_vk, lavapipe], Cpu, Os::Other), Some(2));
assert_eq!(pick(&[gl, nvidia_vk], Cpu, Os::Other), Some(1));
// Other backends rank as before.
assert_eq!(pick(&[nvidia_gl, nvidia_vk], Auto, Os::Other), Some(1));
}
#[test]
fn adapters_must_present_even_when_none_support_the_surface() {
let mut a = cand(INTEL, wgpu::DeviceType::IntegratedGpu, wgpu::Backend::Dx12);
@@ -769,4 +808,28 @@ mod tests {
assert!(safe, "{:?}", create.instance_descriptor.backend_options.dx12.shader_compiler);
}
}
#[test]
fn intel_macs_skip_the_indirect_validation_shaders() {
// Metal's compiler crashed on them on Intel Iris Pro, losing the device in every mode (#3107).
assert!(skips_indirect_validation(Os::Mac, true));
// Apple silicon, Windows and Linux keep wgpu's validation.
for (os, intel) in [(Os::Mac, false), (Os::Windows, true), (Os::Other, true), (Os::Other, false)] {
assert!(!skips_indirect_validation(os, intel), "{os:?} intel={intel}");
}
for (os, safe_gpu) in [(Os::Windows, false), (Os::Other, true), (Os::Other, false)] {
let mut setup = egui_wgpu::WgpuSetup::without_display_handle();
let egui_wgpu::WgpuSetup::CreateNew(before) = &setup else { panic!("a new instance") };
let before = before.instance_descriptor.flags;
configure(&mut setup, &plan(Auto, None, None, safe_gpu, os), os, Arc::new(Mutex::new(None)), Arc::default());
let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") };
assert_eq!(create.instance_descriptor.flags, before, "{os:?}: flags untouched");
}
if cfg!(target_arch = "x86_64") && std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() {
let mut setup = egui_wgpu::WgpuSetup::without_display_handle();
configure(&mut setup, &plan(Auto, None, None, false, Os::Mac), Os::Mac, Arc::new(Mutex::new(None)), Arc::default());
let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") };
assert!(!create.instance_descriptor.flags.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL));
}
}
}
+59 -35
View File
@@ -9,8 +9,8 @@
//!
//! No `dlopen` here (that needs `unsafe`): we read the dynamic linker's cache (`ldconfig -p`) and
//! look in `LD_LIBRARY_PATH` and the usual library directories. Only the cache is conclusive: if
//! it can't be read (NixOS, some containers) and a library isn't found in the directories, we
//! warn and start anyway. `PHOTOCRAFT_SKIP_LIB_CHECK=1` skips the check.
//! it can't be read (musl, NixOS, some containers) and a library isn't found in the directories,
//! that proves nothing, so we start silently. `PHOTOCRAFT_SKIP_LIB_CHECK=1` skips the check.
//!
//! The parsing and decision logic is pure and tested on every platform; only [`preflight`]
//! and [`available`] touch the system, and they are only called on Linux.
@@ -111,9 +111,10 @@ pub fn ldconfig_has(output: &str, soname: &str, arch_tag: Option<&str>) -> bool
})
}
/// A real `ldconfig -p` listing starts with "N libs found in cache".
/// A real `ldconfig -p` listing starts with "N libs found in cache" (translated on a system whose
/// locale `LC_ALL=C` doesn't reach): a count, then the cache's name.
fn ldconfig_output_is_valid(output: &str) -> bool {
output.lines().next().is_some_and(|l| l.contains("libs found in cache"))
output.lines().next().is_some_and(|l| l.split_whitespace().next().is_some_and(|n| n.parse::<u32>().is_ok()))
}
/// Where we look for libraries, and what we found there.
@@ -200,7 +201,7 @@ fn install_command(packages: &[&str], distro: Distro) -> String {
}
/// The message for missing libraries: what's missing, and the command that installs it.
pub fn missing_message(session: DisplaySession, missing: &[AnyOf], distro: Distro, conclusive: bool) -> String {
pub fn missing_message(session: DisplaySession, missing: &[AnyOf], distro: Distro) -> String {
let session_name = match session {
DisplaySession::Wayland => "Wayland",
DisplaySession::X11 => "X11",
@@ -214,26 +215,26 @@ pub fn missing_message(session: DisplaySession, missing: &[AnyOf], distro: Distr
packages.push(p);
}
}
let mut msg = if conclusive {
format!("photocraft: cannot start: the {session_name} session needs libraries that are not installed: {}.\n", names.join(", "))
} else {
format!("photocraft: warning: could not find these libraries the {session_name} session needs: {}. Starting anyway.\n", names.join(", "))
};
let mut msg = format!("photocraft: cannot start: the {session_name} session needs libraries that are not installed: {}.\n", names.join(", "));
msg.push_str(&format!("Install them with:\n {}\n", install_command(&packages, distro)));
if distro == Distro::Unknown {
let fedora: Vec<&str> = missing.iter().filter_map(|any| any.first()).map(|l| l.fedora).collect();
msg.push_str(&format!(" Fedora: sudo dnf install {}\n", fedora.join(" ")));
}
if conclusive {
msg.push_str("(Set PHOTOCRAFT_SKIP_LIB_CHECK=1 to start anyway.)\n");
}
msg.push_str("(Set PHOTOCRAFT_SKIP_LIB_CHECK=1 to start anyway.)\n");
msg
}
/// Library directories to search: `LD_LIBRARY_PATH`, then the usual system and Flatpak paths.
fn search_dirs(ld_library_path: Option<&str>) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = ld_library_path.unwrap_or("").split(':').filter(|d| !d.is_empty()).map(PathBuf::from).collect();
let triplet = if cfg!(target_arch = "aarch64") { "aarch64-linux-gnu" } else { "x86_64-linux-gnu" };
let triplet = if cfg!(target_arch = "aarch64") {
"aarch64-linux-gnu"
} else if cfg!(target_arch = "riscv64") {
"riscv64-linux-gnu"
} else {
"x86_64-linux-gnu"
};
for d in ["/app/lib", "/usr/local/lib", "/usr/lib64", "/lib64", "/usr/lib", "/lib"] {
dirs.push(PathBuf::from(d));
}
@@ -245,7 +246,9 @@ fn search_dirs(ld_library_path: Option<&str>) -> Vec<PathBuf> {
/// `ldconfig -p`, from the usual locations (`/sbin` isn't on a normal user's PATH on Debian).
fn read_ldconfig() -> Option<String> {
for cmd in ["/sbin/ldconfig", "/usr/sbin/ldconfig", "ldconfig"] {
if let Ok(out) = std::process::Command::new(cmd).arg("-p").output()
// The listing is parsed, so it must be the untranslated one: a German system prints
// "5522 Bibliotheken im Cache", which `ldconfig_output_is_valid` took for no cache at all.
if let Ok(out) = std::process::Command::new(cmd).arg("-p").env("LC_ALL", "C").output()
&& out.status.success()
{
let text = String::from_utf8_lossy(&out.stdout).into_owned();
@@ -262,6 +265,12 @@ fn system_probe() -> Probe {
Probe { ldconfig: read_ldconfig(), dirs: search_dirs(std::env::var("LD_LIBRARY_PATH").ok().as_deref()) }
}
/// Whether the linker cache lists `soname`; `None` when the cache can't be read, which proves
/// nothing (musl, NixOS, some containers).
pub fn cached(soname: &str) -> Option<bool> {
read_ldconfig().map(|text| ldconfig_has(&text, soname, ldconfig_arch_tag()))
}
/// Are all the libraries `session` needs found on this system? (For choosing a display server:
/// libraries the check can't find count as missing.)
pub fn available(session: DisplaySession) -> bool {
@@ -269,8 +278,7 @@ pub fn available(session: DisplaySession) -> bool {
}
/// Run the check for the display server the window opens on against this system. `Err` carries
/// the message to print before exiting with a non-zero status; a warning is printed here and the
/// app starts.
/// the message to print before exiting with a non-zero status.
pub fn preflight(session: DisplaySession) -> Result<(), String> {
if std::env::var_os("PHOTOCRAFT_SKIP_LIB_CHECK").is_some_and(|v| !v.is_empty() && v != "0") {
return Ok(());
@@ -278,18 +286,17 @@ pub fn preflight(session: DisplaySession) -> Result<(), String> {
if session == DisplaySession::None {
return Ok(());
}
match check(session, &system_probe(), |p| p.exists()) {
Verdict::Ok => Ok(()),
Verdict::Missing { missing, conclusive } => {
let distro = std::fs::read_to_string("/etc/os-release").map(|t| distro_from_os_release(&t)).unwrap_or(Distro::Unknown);
let msg = missing_message(session, &missing, distro, conclusive);
if conclusive {
Err(msg)
} else {
eprint!("{msg}");
Ok(())
}
}
let verdict = check(session, &system_probe(), |p| p.exists());
decide(session, verdict, || std::fs::read_to_string("/etc/os-release").map(|t| distro_from_os_release(&t)).unwrap_or(Distro::Unknown))
}
/// `Err` with the message to print only when the linker cache was read and the libraries are
/// really absent. Without the cache (musl has no `ldconfig -p`; NixOS, AppImages that ship their
/// own libraries) not finding a file proves nothing, so we start without a misleading warning.
fn decide(session: DisplaySession, verdict: Verdict, distro: impl FnOnce() -> Distro) -> Result<(), String> {
match verdict {
Verdict::Missing { missing, conclusive: true } => Err(missing_message(session, &missing, distro())),
Verdict::Missing { conclusive: false, .. } | Verdict::Ok => Ok(()),
}
}
@@ -327,6 +334,10 @@ mod tests {
fn ldconfig_parsing_matches_name_and_architecture() {
assert!(ldconfig_output_is_valid(CACHE));
assert!(!ldconfig_output_is_valid("ldconfig: command not found"));
// A translated listing is still a listing (it used to be rejected, so the check was
// silently skipped on non-English systems).
assert!(ldconfig_output_is_valid("5522 Bibliotheken im Cache »/etc/ld.so.cache« gefunden\n\tlibz.so.1 (libc6,x86-64) => /usr/lib/libz.so.1\n"));
assert!(!ldconfig_output_is_valid("Error: kein Cache\n"));
assert!(ldconfig_has(CACHE, "libxkbcommon.so.0", Some("x86-64")));
// Only the 32-bit build is installed: doesn't count for a 64-bit app.
assert!(!ldconfig_has(CACHE, "libxkbcommon-x11.so.0", Some("x86-64")));
@@ -362,7 +373,7 @@ mod tests {
assert!(conclusive);
assert_eq!(missing.len(), 1);
assert_eq!(missing[0][0].soname, "libxkbcommon-x11.so.0");
let msg = missing_message(DisplaySession::X11, &missing, Distro::Debian, conclusive);
let msg = missing_message(DisplaySession::X11, &missing, Distro::Debian);
assert!(msg.contains("libxkbcommon-x11.so.0"), "{msg}");
assert!(msg.contains("sudo apt install libxkbcommon-x11-0"), "{msg}");
assert!(msg.contains("PHOTOCRAFT_SKIP_LIB_CHECK"), "{msg}");
@@ -384,13 +395,13 @@ mod tests {
let probe = Probe { ldconfig: Some(cache_for_this_arch(&["libwayland-client.so.0", "libxkbcommon.so.0"])), dirs: vec![] };
let Verdict::Missing { missing, .. } = check(DisplaySession::Wayland, &probe, |_| false) else { panic!("expected missing") };
assert_eq!(missing.len(), 1);
let msg = missing_message(DisplaySession::Wayland, &missing, Distro::Fedora, true);
let msg = missing_message(DisplaySession::Wayland, &missing, Distro::Fedora);
assert!(msg.contains("libvulkan.so.1 or libEGL.so.1"), "{msg}");
assert!(msg.contains("sudo dnf install vulkan-loader"), "{msg}");
}
#[test]
fn library_dirs_count_and_unread_cache_only_warns() {
fn library_dirs_count_and_unread_cache_is_inconclusive() {
let dirs = search_dirs(Some("/opt/x/lib::/nix/store/abc/lib"));
assert_eq!(dirs[0], PathBuf::from("/opt/x/lib"));
assert_eq!(dirs[1], PathBuf::from("/nix/store/abc/lib"));
@@ -398,16 +409,29 @@ mod tests {
let probe = Probe { ldconfig: None, dirs: vec![PathBuf::from("/nix/lib")] };
let present = ["/nix/lib/libwayland-client.so.0", "/nix/lib/libxkbcommon.so.0", "/nix/lib/libEGL.so.1"];
assert_eq!(check(DisplaySession::Wayland, &probe, |p| present.iter().any(|q| Path::new(q) == p)), Verdict::Ok);
// Not found and no cache to confirm it: inconclusive, so a warning rather than an exit.
// Not found and no cache to confirm it: inconclusive (the app starts, see #1144).
let v = check(DisplaySession::Wayland, &probe, |_| false);
let Verdict::Missing { missing, conclusive } = v else { panic!("expected missing") };
assert!(!conclusive);
let msg = missing_message(DisplaySession::Wayland, &missing, Distro::Unknown, conclusive);
assert!(msg.contains("Starting anyway"), "{msg}");
let msg = missing_message(DisplaySession::Wayland, &missing, Distro::Unknown);
assert!(msg.contains("apt install libwayland-client0 libxkbcommon0 libvulkan1"), "{msg}");
assert!(msg.contains("dnf install libwayland-client libxkbcommon vulkan-loader"), "{msg}");
}
#[test]
fn unreadable_cache_never_warns_or_fails() {
// Issue #1144: Alpine (musl) has no `ldconfig -p`, so a library that exists was reported missing.
let probe = Probe { ldconfig: None, dirs: vec![] };
let verdict = check(DisplaySession::X11, &probe, |_| false);
assert_eq!(decide(DisplaySession::X11, verdict, || Distro::Debian), Ok(()));
// A readable cache that lacks a library is still an error.
let names: Vec<&str> = ALL_X11.iter().copied().filter(|n| *n != "libxkbcommon-x11.so.0").collect();
let probe = Probe { ldconfig: Some(cache_for_this_arch(&names)), dirs: vec![] };
let verdict = check(DisplaySession::X11, &probe, |_| false);
let Err(msg) = decide(DisplaySession::X11, verdict, || Distro::Debian) else { panic!("expected an error") };
assert!(msg.contains("libxkbcommon-x11.so.0"), "{msg}");
}
#[test]
fn distro_detection() {
assert_eq!(distro_from_os_release("NAME=\"Ubuntu\"\nID=ubuntu\nID_LIKE=debian\n"), Distro::Debian);
+42 -5
View File
@@ -5,13 +5,15 @@
//! - Item ids are command ids; a command in two menus (Keyboard Shortcuts is in Edit and Window)
//! gets `id#2` for its second copy, as muda ids must be unique.
//! - A structure change (a new Open Recent file, a language switch) rebuilds the menu; anything
//! else (labels, enabled, checked) is updated in place.
//! else (labels, enabled, checked) is updated in place. Opening or closing a document rebuilds
//! only the Window menu, whose list of documents changed: AppKit adds its own items to that
//! menu (window tiling, the window list), so muda can't insert rows there by position.
//! - A chosen item is a click or a key equivalent: AppKit's current event says which. Key
//! equivalents go back to egui as the key press that was made (the event's modifiers, not the
//! item's: AppKit may match ⌘R to a ⇧⌘R item), so PhotoCraft's key rules still apply.
//! - Hide is a custom item calling `NSApplication hide:`, as the predefined one always takes ⌘H.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::sync::mpsc::{Receiver, channel};
use muda::accelerator::{Accelerator, Code, Modifiers};
@@ -49,6 +51,8 @@ pub struct MacMenu {
entries: HashMap<String, Entry>,
rx: Receiver<Chosen>,
structure: u64,
/// The Window menu, the muda ids of its items, and its [`native_menu::window_key`].
window: Option<(Submenu, Vec<String>, u64)>,
}
impl MacMenu {
@@ -67,7 +71,7 @@ impl MacMenu {
// Wake egui, so the item runs now rather than on the next mouse move.
repaint.request_repaint();
}));
MacMenu { menu: None, entries: HashMap::new(), rx, structure: 0 }
MacMenu { menu: None, entries: HashMap::new(), rx, structure: 0, window: None }
}
fn build(&mut self, bar: &MenuBar) {
@@ -75,12 +79,15 @@ impl MacMenu {
old.remove_for_nsapp();
}
self.entries.clear();
self.window = None;
let menu = Menu::new();
let mut special = Vec::new();
for m in &bar.menus {
let sub = Submenu::new(escape(&m.title), true);
self.append(&sub, &m.children);
let (sub, ids) = self.submenu(m);
let _ = menu.append(&sub);
if m.role == MenuRole::Window {
self.window = Some((sub.clone(), ids, native_menu::window_key(bar)));
}
if matches!(m.role, MenuRole::Window | MenuRole::Help) {
special.push((m.role, sub));
}
@@ -97,6 +104,33 @@ impl MacMenu {
self.structure = native_menu::structure_key(bar);
}
/// A top-level menu, and the muda ids of the items it added.
fn submenu(&mut self, m: &native_menu::Menu) -> (Submenu, Vec<String>) {
let before: HashSet<String> = self.entries.keys().cloned().collect();
let sub = Submenu::new(escape(&m.title), true);
self.append(&sub, &m.children);
let ids = self.entries.keys().filter(|id| !before.contains(*id)).cloned().collect();
(sub, ids)
}
/// Replace the Window menu (a document opened or closed), leaving the other menus as they are.
fn rebuild_window(&mut self, bar: &MenuBar) {
let (Some(menu), Some((old, ids, _))) = (self.menu.clone(), self.window.take()) else { return self.build(bar) };
let Some((at, spec)) = bar.menus.iter().enumerate().find(|(_, m)| m.role == MenuRole::Window) else { return self.build(bar) };
if menu.remove(&old).is_err() {
return self.build(bar);
}
for id in ids {
self.entries.remove(&id);
}
let (sub, ids) = self.submenu(spec);
if menu.insert(&sub, at).is_err() {
return self.build(bar);
}
sub.set_as_windows_menu_for_nsapp();
self.window = Some((sub, ids, native_menu::window_key(bar)));
}
fn append(&mut self, sub: &Submenu, nodes: &[Node]) {
for n in nodes {
match n {
@@ -160,6 +194,9 @@ impl Backend for MacMenu {
self.build(bar);
return;
}
if self.window.as_ref().map(|w| w.2) != Some(native_menu::window_key(bar)) {
self.rebuild_window(bar);
}
let items: HashMap<&str, &native_menu::Item> = bar.items().into_iter().map(|it| (it.id.as_str(), it)).collect();
for e in self.entries.values_mut() {
let Some(it) = items.get(e.command.as_str()) else { continue };
+66 -3
View File
@@ -22,11 +22,14 @@
mod app_dirs;
mod app_icon;
mod appearance;
#[cfg(target_os = "macos")]
mod apple_events;
mod caps_lock;
mod control_server;
mod crash_guard;
mod cursor;
mod file_dialog_probe;
mod gpu_startup;
#[cfg(target_os = "macos")]
mod mac_menu;
@@ -37,12 +40,14 @@ mod mac_window;
mod linux_libs;
mod logging;
mod monitor_profile;
mod photoshop_settings;
mod screen_color;
mod services;
// Windows gets pen pressure from winit (WM_POINTER); the web runner has its own listener.
#[cfg(any(target_os = "macos", target_os = "linux", test))]
mod tablet;
mod ui_state;
mod window_frame;
use photocraft_engine::Session;
use photocraft_ui_egui::PhotocraftApp;
@@ -85,10 +90,25 @@ fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
// eframe saves native window geometry and egui panel/window sizes on exit.
// Keep that state beside preferences, including config overrides and portable mode.
persistence_path: services::config_dir().map(|dir| dir.join("ui.ron")),
window_builder: Some(Box::new(at_least_min_size)),
..Default::default()
}
}
/// Grow a restored window that is smaller than the minimum size, keeping its centre. On
/// Windows, eframe saves a minimized window's size (160 pt wide, 64 pt tall once eframe has
/// clamped it), and the minimum size isn't applied to a restored one: PhotoCraft then reopened
/// as a 160 × 64 strip on every launch.
fn at_least_min_size(mut builder: egui::ViewportBuilder) -> egui::ViewportBuilder {
let (Some(size), Some(min)) = (builder.inner_size, builder.min_inner_size) else { return builder };
let grown = size.max(min);
if grown != size {
builder.position = builder.position.map(|pos| pos - (grown - size) / 2.0);
builder.inner_size = Some(grown);
}
builder
}
/// Parse a `--control` / `PHOTOCRAFT_CONTROL_PORT` value. An unparseable port is an error that
/// names the value (issue #701): silently running with no control server leaves a launcher or
/// agent unable to tell a typo from a successful grant.
@@ -135,6 +155,8 @@ fn main() -> eframe::Result {
// First, so the panic hook and every start-up warning are recorded (`logging`).
let logger = logging::install();
crash_guard::install_hook();
// The system font scan can take seconds (minutes on some Macs): run it off the UI thread.
photocraft_ui_egui::type_tool::warm_fonts();
let mut control_port: Option<u16> = None;
let mut control_arg_errors: Vec<String> = Vec::new();
if let Some(value) = std::env::var("PHOTOCRAFT_CONTROL_PORT").ok().filter(|v| !v.trim().is_empty()) {
@@ -208,6 +230,8 @@ fn main() -> eframe::Result {
// The display server to open the window on: Xwayland for a pen on Wayland, which gives this
// app no pen input (#639).
#[cfg(target_os = "linux")]
let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok());
#[cfg(target_os = "linux")]
let session = tablet::display_session();
// Preferences › Performance › Linux display server = X11: Xwayland on a Wayland session too,
// where native file drops work (winit 0.30 has none on Wayland, #386). Only when Xwayland can
@@ -238,7 +262,7 @@ fn main() -> eframe::Result {
Ok(token) => token,
Err(e) => {
eprintln!("photocraft: cannot configure control authentication: {e}");
return Ok(());
std::process::exit(2);
}
};
if let Some(path) = token_file {
@@ -252,7 +276,7 @@ fn main() -> eframe::Result {
Ok(workspace) => workspace,
Err(error) => {
eprintln!("photocraft: cannot configure automation workspace: {error}");
return Ok(());
std::process::exit(2);
}
};
Some((port, token, workspace))
@@ -275,6 +299,9 @@ fn main() -> eframe::Result {
// Read the displays' ICC profiles while the window opens (colour-managed canvas; `None`
// where the platform has no reader).
#[cfg(target_os = "linux")]
let monitor = monitor_profile::detect_async_for_session(native_session);
#[cfg(not(target_os = "linux"))]
let monitor = monitor_profile::detect_async();
// Brush presets load in the background; the app attaches them when they arrive.
let presets = services::presets_dir().map(photocraft_engine::preset_store::open_dir_async);
@@ -338,6 +365,7 @@ fn main() -> eframe::Result {
#[cfg(target_os = "linux")]
{
services.is_wayland = display == Some(tablet::DisplayKind::Wayland);
file_dialog_probe::start();
if services.is_wayland {
let var = |name| std::env::var(name).ok();
services.xwayland_command =
@@ -356,7 +384,14 @@ fn main() -> eframe::Result {
// the right profile; a slower reading is applied when it arrives, and the shell reads
// again when the displays may have changed.
if let Some(rx) = monitor {
app.services.read_displays = Some(std::sync::Arc::new(monitor_profile::detect_async));
#[cfg(target_os = "linux")]
{
app.services.read_displays = Some(std::sync::Arc::new(move || monitor_profile::detect_async_for_session(native_session)));
}
#[cfg(not(target_os = "linux"))]
{
app.services.read_displays = Some(std::sync::Arc::new(monitor_profile::detect_async));
}
match rx.recv_timeout(std::time::Duration::from_secs(2)) {
Ok(r) => photocraft_ui_egui::monitor_status::apply(&mut app, r),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => photocraft_ui_egui::monitor_status::pending(&mut app, rx),
@@ -444,6 +479,12 @@ fn main() -> eframe::Result {
let _ = in_window_menus;
// Where file drags and drops are (winit 0.30 doesn't say).
app.services.cursor_pos = cursor::service(cc);
// The custom title bar's undecorated window must stay borderless, or its caption and
// border offset the content and the pointer on some Windows systems (#2246).
app.services.window_frame = window_frame::service(cc, custom_titlebar);
// Caps Lock state (X11/Windows/macOS; `None` on native Wayland): the canvas shows the
// precise crosshair for painting tools while it is toggled on (#1758).
app.services.caps_lock = caps_lock::service(cc);
app.services.screen_pick = screen_color::service(cc, app.services.is_wayland);
// Tablet pressure/tilt/eraser (winit drops them): the macOS monitor and the X11 reader
// write into the stylus feed. The monitor goes in here, not before the event loop:
@@ -561,6 +602,28 @@ mod tests {
assert_ne!(o.viewport.clamp_size_to_monitor_size, Some(false));
}
#[test]
fn a_window_saved_while_minimized_reopens_at_the_minimum_size() {
let hook = super::native_options(super::CUSTOM_TITLEBAR).window_builder.expect("a window builder hook");
// Saved minimized on Windows, then centred on a 1920 × 1080 monitor by eframe.
let saved = super::native_options(super::CUSTOM_TITLEBAR).viewport.with_inner_size([160.0, 64.0]).with_position([880.0, 508.0]);
let opened = hook(saved);
assert_eq!(opened.inner_size, Some(egui::vec2(760.0, 480.0)));
assert_eq!(opened.position, Some(egui::pos2(580.0, 300.0)), "still centred");
// Too narrow only: only the width grows.
let opened = super::at_least_min_size(super::native_options(false).viewport.with_inner_size([500.0, 900.0]));
assert_eq!(opened.inner_size, Some(egui::vec2(760.0, 900.0)));
// A window at or above the minimum, or with no size, is left alone.
for size in [[760.0, 480.0], [1100.0, 760.0]] {
let builder = super::native_options(false).viewport.with_inner_size(size).with_position([10.0, 20.0]);
let opened = super::at_least_min_size(builder);
assert_eq!((opened.inner_size, opened.position), (Some(egui::Vec2::from(size)), Some(egui::pos2(10.0, 20.0))));
}
let mut builder = super::native_options(false).viewport;
builder.inner_size = None;
assert_eq!(super::at_least_min_size(builder).inner_size, None);
}
#[test]
fn the_system_title_bar_preference_keeps_the_window_decorations() {
// #1271, #1316: Preferences › Interface › System Title Bar gives the window back its
+246 -6
View File
@@ -6,7 +6,12 @@
//! AppleScriptObjC) so the app needs no `unsafe` FFI. A read takes about 0.4 s on a background
//! thread; the shell starts one at launch and again when the displays may have changed
//! (`photocraft_ui_egui::monitor_status`), and each window then uses the profile of the display
//! it is on. Other platforms report no displays (sRGB, or the profile chosen in Color Settings).
//! it is on. Linux X11: RandR output names and CRTC frames are matched to colord display devices
//! by the exact `XRANDR_name` metadata; cloned outputs get a profile only when every output has
//! the same ICC bytes. Native Wayland, including Xwayland windows opened from a Wayland session,
//! reports no display profiles: eframe/winit has no safe way to set the app surface's Wayland
//! image description, so applying the output ICC in PhotoCraft could double-transform it.
//! Other platforms report no displays (sRGB, or the profile chosen in Color Settings).
use std::sync::mpsc::Receiver;
@@ -16,15 +21,33 @@ use photocraft_engine::display_color::Display;
pub type Detection = Result<Vec<Display>, String>;
/// Starts reading the displays in the background; `None` when the platform has no reader.
#[cfg(not(target_os = "linux"))]
pub fn detect_async() -> Option<Receiver<Detection>> {
if !cfg!(target_os = "macos") {
return None;
#[cfg(target_os = "macos")]
{
Some(spawn_reader(detect))
}
#[cfg(not(target_os = "macos"))]
{
None
}
}
/// Linux display profile reads are supported only for an X11 session. In particular, an app
/// window opened through Xwayland still belongs to the Wayland desktop and must not apply a
/// compositor-managed output profile a second time.
#[cfg(target_os = "linux")]
pub fn detect_async_for_session(session: crate::linux_libs::DisplaySession) -> Option<Receiver<Detection>> {
(session == crate::linux_libs::DisplaySession::X11).then(|| spawn_reader(detect))
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn spawn_reader(detect: fn() -> Detection) -> Receiver<Detection> {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(detect());
});
Some(rx)
rx
}
/// One line per screen, primary (menu-bar) screen first: id, frame (x, y, width, height in
@@ -110,9 +133,225 @@ fn run_helper(cmd: &mut std::process::Command, timeout: std::time::Duration) ->
Ok(String::from_utf8_lossy(&out).into_owned())
}
#[cfg(not(target_os = "macos"))]
#[cfg(target_os = "linux")]
fn detect() -> Detection {
Err("this platform doesn't report display profiles".into())
linux::detect()
}
#[cfg(target_os = "linux")]
mod linux {
use std::collections::{BTreeMap, HashMap};
use std::io::Read as _;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use photocraft_engine::display_color::Display;
use x11rb::connection::Connection as _;
use x11rb::protocol::randr;
use zbus::blocking::{connection::Builder, proxy::Proxy};
use zbus::zvariant::OwnedObjectPath;
use super::Detection;
const MAX_ICC_BYTES: usize = 64 * 1024 * 1024;
const COLORD: &str = "org.freedesktop.ColorManager";
const COLORD_ROOT: &str = "/org/freedesktop/ColorManager";
const COLORD_MANAGER: &str = "org.freedesktop.ColorManager";
const COLORD_DEVICE: &str = "org.freedesktop.ColorManager.Device";
const COLORD_PROFILE: &str = "org.freedesktop.ColorManager.Profile";
struct IccProfile {
name: String,
bytes: Arc<Vec<u8>>,
}
pub(super) fn detect() -> Detection {
let (connection, screen) = x11rb::connect(None).map_err(|e| format!("couldn't connect to the X11 display: {e}"))?;
let root = connection.setup().roots.get(screen).ok_or_else(|| "the X11 server didn't provide a screen".to_string())?.root;
let resources = randr::get_screen_resources_current(&connection, root)
.map_err(|e| format!("couldn't request XRandR outputs: {e}"))?
.reply()
.map_err(|e| format!("couldn't read XRandR outputs: {e}"))?;
let mut output_names = HashMap::new();
let mut active_crtcs = BTreeMap::new();
for output in resources.outputs {
let info = match randr::get_output_info(&connection, output, resources.config_timestamp) {
Ok(cookie) => match cookie.reply() {
Ok(info) => info,
Err(e) => {
log::debug!("couldn't read one XRandR output: {e}");
continue;
}
},
Err(e) => {
log::debug!("couldn't request one XRandR output: {e}");
continue;
}
};
if info.connection != randr::Connection::CONNECTED || info.crtc == 0 {
continue;
}
let Ok(name) = String::from_utf8(info.name) else {
log::debug!("skipping an XRandR output with a non-UTF-8 name");
continue;
};
if !name.is_empty() {
output_names.insert(output, name);
active_crtcs.insert(info.crtc, ());
}
}
let profiles = match colord_profiles() {
Ok(profiles) => profiles,
Err(e) => {
log::warn!("couldn't read X11 display profiles from colord: {e}");
HashMap::new()
}
};
let mut displays = Vec::with_capacity(active_crtcs.len());
for crtc in active_crtcs.into_keys() {
let crtc_info = match randr::get_crtc_info(&connection, crtc, resources.config_timestamp) {
Ok(cookie) => match cookie.reply() {
Ok(info) if info.status == randr::SetConfig::SUCCESS && info.width > 0 && info.height > 0 => info,
Ok(_) => continue,
Err(e) => {
log::debug!("couldn't read XRandR CRTC {crtc}: {e}");
continue;
}
},
Err(e) => {
log::debug!("couldn't request XRandR CRTC {crtc}: {e}");
continue;
}
};
let Some(output_names) = crtc_info.outputs.iter().map(|output| output_names.get(output).cloned()).collect::<Option<Vec<_>>>() else { continue };
let Some(primary_name) = output_names.first() else { continue };
let profile = unambiguous_clone_profile(&output_names, &profiles);
displays.push(Display {
id: crtc,
name: primary_name.clone(),
frame: [f64::from(crtc_info.x), f64::from(crtc_info.y), f64::from(crtc_info.width), f64::from(crtc_info.height)],
profile_name: profile.as_ref().map(|p| p.name.clone()),
icc: profile.map(|p| p.bytes),
});
}
if displays.is_empty() {
return Err("X11 reported no active RandR outputs".into());
}
Ok(displays)
}
fn colord_profiles() -> Result<HashMap<String, Vec<IccProfile>>, String> {
let connection = Builder::system()
.map_err(|e| format!("couldn't connect to the system bus: {e}"))?
.method_timeout(Duration::from_secs(2))
.build()
.map_err(|e| format!("couldn't connect to the system bus: {e}"))?;
let manager = Proxy::new(&connection, COLORD, COLORD_ROOT, COLORD_MANAGER).map_err(|e| format!("couldn't access colord: {e}"))?;
let devices: Vec<OwnedObjectPath> =
manager.call("GetDevicesByKind", &("display",)).map_err(|e| format!("colord couldn't list display devices: {e}"))?;
let mut profiles: HashMap<String, Vec<IccProfile>> = HashMap::new();
for device_path in devices {
let device = Proxy::new(&connection, COLORD, &device_path, COLORD_DEVICE).map_err(|e| format!("couldn't access a colord display device: {e}"))?;
let metadata: HashMap<String, String> = device.get_property("Metadata").map_err(|e| format!("couldn't read colord display metadata: {e}"))?;
let Some(output_name) = metadata.get("XRANDR_name").filter(|name| !name.is_empty()) else { continue };
// `*` is colord's default profile qualifier. A display without one is kept, with no
// ICC, so the engine reports the normal sRGB fallback.
let profile_path: OwnedObjectPath = match device.call("GetProfileForQualifiers", &(vec!["*"],)) {
Ok(path) => path,
Err(_) => continue,
};
let profile = Proxy::new(&connection, COLORD, &profile_path, COLORD_PROFILE).map_err(|e| format!("couldn't access a colord ICC profile: {e}"))?;
let filename: String = match profile.get_property::<String>("Filename") {
Ok(filename) if !filename.is_empty() => filename,
_ => continue,
};
let Some(profile) = read_icc(Path::new(&filename)) else {
log::warn!("couldn't read a valid ICC profile assigned to X11 output {output_name}");
continue;
};
profiles.entry(output_name.clone()).or_default().push(profile);
}
Ok(profiles)
}
fn read_icc(path: &Path) -> Option<IccProfile> {
let mut bytes = Vec::new();
std::fs::File::open(path).ok()?.take((MAX_ICC_BYTES + 1) as u64).read_to_end(&mut bytes).ok()?;
let bytes = checked_icc_bytes(bytes)?;
let name = path.file_name()?.to_str()?.to_owned();
Some(IccProfile { name, bytes: Arc::new(bytes) })
}
fn checked_icc_bytes(mut bytes: Vec<u8>) -> Option<Vec<u8>> {
if bytes.len() > MAX_ICC_BYTES || bytes.len() < 132 || bytes.get(36..40) != Some(b"acsp") {
return None;
}
let declared = u32::from_be_bytes(bytes.get(0..4)?.try_into().ok()?) as usize;
if declared < 132 || declared > bytes.len() {
return None;
}
bytes.truncate(declared);
let profile = photocraft_cms::Profile::parse(&bytes).ok()?;
(profile.color_space == photocraft_cms::ColorSpace::Rgb).then_some(bytes)
}
fn unambiguous_clone_profile(output_names: &[String], profiles: &HashMap<String, Vec<IccProfile>>) -> Option<IccProfile> {
let mut selected: Option<&IccProfile> = None;
for output in output_names {
let candidates = profiles.get(output)?;
let first = candidates.first()?;
if candidates.iter().any(|candidate| candidate.bytes != first.bytes) {
return None;
}
if selected.is_some_and(|profile| profile.bytes != first.bytes) {
return None;
}
selected = Some(first);
}
selected.map(|profile| IccProfile { name: profile.name.clone(), bytes: profile.bytes.clone() })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn checked_icc_bytes_require_a_bounded_parseable_rgb_profile() {
let rgb = photocraft_cms::Builtin::Srgb.profile().to_bytes();
let bytes = rgb.as_ref().clone();
assert_eq!(checked_icc_bytes(bytes.clone()), Some(bytes));
let cmyk = photocraft_cms::Builtin::CoatedCmyk.profile().to_bytes();
assert!(checked_icc_bytes(cmyk.as_ref().clone()).is_none());
assert!(checked_icc_bytes(vec![0; 132]).is_none());
assert!(checked_icc_bytes(vec![0; MAX_ICC_BYTES + 1]).is_none());
}
#[test]
fn cloned_outputs_use_only_one_unambiguous_profile() {
let srgb = photocraft_cms::Builtin::Srgb.profile().to_bytes();
let p3 = photocraft_cms::Builtin::DisplayP3.profile().to_bytes();
let profile = |name: &str, bytes: std::sync::Arc<Vec<u8>>| IccProfile { name: name.into(), bytes };
let outputs = ["DP-1".to_owned(), "HDMI-1".to_owned()];
let matching =
HashMap::from([("DP-1".to_owned(), vec![profile("sRGB", srgb.clone())]), ("HDMI-1".to_owned(), vec![profile("sRGB", srgb.clone())])]);
assert_eq!(unambiguous_clone_profile(&outputs, &matching).map(|p| p.name), Some("sRGB".into()));
let differing =
HashMap::from([("DP-1".to_owned(), vec![profile("sRGB", srgb.clone())]), ("HDMI-1".to_owned(), vec![profile("Display P3", p3.clone())])]);
assert!(unambiguous_clone_profile(&outputs, &differing).is_none());
let missing = HashMap::from([("DP-1".to_owned(), vec![profile("sRGB", srgb.clone())])]);
assert!(unambiguous_clone_profile(&outputs, &missing).is_none());
let conflicting = HashMap::from([("DP-1".to_owned(), vec![profile("sRGB", srgb), profile("Display P3", p3)])]);
assert!(unambiguous_clone_profile(&["DP-1".to_owned()], &conflicting).is_none());
}
}
}
/// The helper's reply ([`SCRIPT`]) → displays, frames flipped to a top-left origin with y down
@@ -285,6 +524,7 @@ mod tests {
}
/// On a Mac, every display is read, and the profiles parse as RGB profiles.
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn detected_displays_parse() {
if let Ok(displays) = detect() {
+156
View File
@@ -0,0 +1,156 @@
//! Photoshop's live keyboard shortcut set on this machine, for the one-time offer to import it
//! at first launch (`photocraft_ui_egui::kys_import::offer_import`).
//!
//! Photoshop keeps the set in use as `Keyboard Shortcuts.psp` in its per-version settings
//! folder; it is the same XML a saved `.kys` holds, named after the set the user chose.
//! macOS: `~/Library/Preferences/Adobe Photoshop <version> Settings/`. Windows:
//! `%APPDATA%\Adobe\Adobe Photoshop <version>\Adobe Photoshop <version> Settings\`. Every
//! installed version has one; the newest version wins (the number in the folder name, then
//! the file's modification time), since that is the Photoshop the user runs. Linux has no
//! Photoshop; a copied set is imported by hand (Edit › Keyboard Shortcuts).
use std::ffi::OsString;
use std::path::{Path, PathBuf};
/// The file is a few tens of kilobytes; anything far larger is not a shortcut set.
const MAX_BYTES: u64 = 4 << 20;
/// The platform whose folder layout applies.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Platform {
Mac,
Windows,
Other,
}
const fn this_platform() -> Platform {
if cfg!(target_os = "macos") {
Platform::Mac
} else if cfg!(target_os = "windows") {
Platform::Windows
} else {
Platform::Other
}
}
/// Every `Adobe Photoshop <version> Settings` folder that could hold a set, newest first.
pub fn settings_dirs(os: Platform, env: &impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let var = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
let mut dirs = match os {
Platform::Mac => var("HOME").map(|h| h.join("Library/Preferences")).into_iter().flat_map(|prefs| settings_in(&prefs)).collect::<Vec<_>>(),
// `%APPDATA%\Adobe\Adobe Photoshop 2026\Adobe Photoshop 2026 Settings`.
Platform::Windows => var("APPDATA")
.map(|a| a.join("Adobe"))
.into_iter()
.flat_map(|adobe| std::fs::read_dir(adobe).into_iter().flatten().flatten().map(|e| e.path()))
.filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("Adobe Photoshop ")))
.flat_map(|p| settings_in(&p))
.collect(),
Platform::Other => Vec::new(),
};
dirs.sort_by_key(|d| std::cmp::Reverse(version_key(d)));
dirs
}
/// `Adobe Photoshop <version> Settings` folders directly inside `parent`.
fn settings_in(parent: &Path) -> Vec<PathBuf> {
std::fs::read_dir(parent)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| {
let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
name.starts_with("Adobe Photoshop ") && name.ends_with(" Settings") && p.is_dir()
})
.collect()
}
/// Newest first: the version number in the folder name (2026; CC 2019 → 2019; CS6 → 6), then
/// the set's modification time.
fn version_key(dir: &Path) -> (u64, std::time::SystemTime) {
let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let number = name.split(|c: char| !c.is_ascii_digit()).filter(|s| !s.is_empty()).filter_map(|s| s.parse::<u64>().ok()).max().unwrap_or(0);
let modified = std::fs::metadata(dir.join(FILE)).and_then(|m| m.modified()).unwrap_or(std::time::SystemTime::UNIX_EPOCH);
(number, modified)
}
/// The live set's file name inside a settings folder.
pub const FILE: &str = "Keyboard Shortcuts.psp";
/// The newest install's live set as (path, XML text), `None` without a readable one. A file that
/// is not a shortcut set (another version's binary `.psp`, a truncated file) is skipped.
pub fn live_keyboard_shortcuts_on(os: Platform, env: &impl Fn(&str) -> Option<OsString>) -> Option<(String, String)> {
settings_dirs(os, env).into_iter().map(|d| d.join(FILE)).find_map(|path| {
let len = std::fs::metadata(&path).ok()?.len();
if len > MAX_BYTES {
return None;
}
let text = std::fs::read_to_string(&path).ok()?;
text.contains("<photoshop-keyboard-shortcuts").then(|| (path.to_string_lossy().into_owned(), text))
})
}
/// [`live_keyboard_shortcuts_on`] for this platform.
pub fn live_keyboard_shortcuts(env: &impl Fn(&str) -> Option<OsString>) -> Option<(String, String)> {
live_keyboard_shortcuts_on(this_platform(), env)
}
#[cfg(test)]
mod tests {
use super::*;
const SET: &str = "\u{feff}<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<photoshop-keyboard-shortcuts version=\"4\" filename=\"texcuts\" modified=\"1\" multi-undo=\"1\">\n</photoshop-keyboard-shortcuts>\n";
/// A fresh scratch directory per test (removed first, so a rerun starts clean).
fn temp_root(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("photocraft-photoshop-settings-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn write(dir: &Path, text: &[u8]) {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join(FILE), text).unwrap();
}
fn env_for(root: &Path) -> impl Fn(&str) -> Option<OsString> + '_ {
move |k| match k {
"HOME" => Some(root.join("home").into_os_string()),
"APPDATA" => Some(root.join("appdata").into_os_string()),
_ => None,
}
}
#[test]
fn newest_version_wins_on_macos() {
let root = temp_root("mac");
let prefs = root.join("home/Library/Preferences");
write(&prefs.join("Adobe Photoshop 2024 Settings"), SET.as_bytes());
write(&prefs.join("Adobe Photoshop 2026 Settings"), SET.replace("texcuts", "newest").as_bytes());
write(&prefs.join("Adobe Photoshop CC 2019 Settings"), SET.as_bytes());
write(&prefs.join("Adobe Photoshop 2025 Paths"), SET.as_bytes()); // not a Settings folder
let env = env_for(&root);
let dirs: Vec<String> = settings_dirs(Platform::Mac, &env).iter().map(|d| d.file_name().unwrap().to_string_lossy().into_owned()).collect();
assert_eq!(dirs, ["Adobe Photoshop 2026 Settings", "Adobe Photoshop 2024 Settings", "Adobe Photoshop CC 2019 Settings"]);
let (path, text) = live_keyboard_shortcuts_on(Platform::Mac, &env).unwrap();
assert!(path.replace('\\', "/").ends_with("Adobe Photoshop 2026 Settings/Keyboard Shortcuts.psp"), "{path}");
assert!(text.contains("filename=\"newest\""));
}
#[test]
fn windows_layout_and_unreadable_sets_are_skipped() {
let root = temp_root("win");
let adobe = root.join("appdata/Adobe");
// The newest install's file is not a shortcut set (binary); the older one is used.
write(&adobe.join("Adobe Photoshop 2026/Adobe Photoshop 2026 Settings"), &[0x80, 0x00, 0xff, 0xfe]);
write(&adobe.join("Adobe Photoshop 2025/Adobe Photoshop 2025 Settings"), SET.as_bytes());
std::fs::create_dir_all(adobe.join("Adobe Illustrator 30/Adobe Illustrator 30 Settings")).unwrap();
let env = env_for(&root);
let (path, _) = live_keyboard_shortcuts_on(Platform::Windows, &env).unwrap();
assert!(path.replace('\\', "/").ends_with("Adobe Photoshop 2025/Adobe Photoshop 2025 Settings/Keyboard Shortcuts.psp"), "{path}");
assert!(live_keyboard_shortcuts_on(Platform::Other, &env).is_none());
assert!(live_keyboard_shortcuts_on(Platform::Mac, &|_| None).is_none(), "no HOME, no set");
}
}
+88 -16
View File
@@ -48,6 +48,66 @@ fn count(width: usize, height: usize) -> Result<usize, String> {
width.checked_mul(height).filter(|&n| n > 0 && n <= MAX_PIXELS).ok_or_else(|| "Screen capture exceeds the 64 MP memory budget".into())
}
#[cfg(target_os = "linux")]
const MAX_ICC_PROFILE_BYTES: usize = 1024 * 1024;
#[cfg(target_os = "linux")]
const ICC_PROFILE_PROPERTY_LONG_LENGTH: u32 = 256 * 1024;
#[cfg(target_os = "linux")]
fn icc_profile(bytes: Vec<u8>) -> Option<Vec<u8>> {
if bytes.is_empty() || bytes.len() > MAX_ICC_PROFILE_BYTES {
return None;
}
let profile = match photocraft_cms::Profile::parse(&bytes) {
Ok(profile) => profile,
Err(_) => return None,
};
(profile.color_space == photocraft_cms::ColorSpace::Rgb).then_some(bytes)
}
#[cfg(target_os = "linux")]
fn icc_profile_atom<C: x11rb::connection::RequestConnection>(conn: &C, name: &str) -> Option<u32> {
use x11rb::protocol::xproto::ConnectionExt as _;
let cookie = match conn.intern_atom(true, name.as_bytes()) {
Ok(cookie) => cookie,
Err(_) => return None,
};
let atom = match cookie.reply() {
Ok(reply) => reply.atom,
Err(_) => return None,
};
(atom != 0).then_some(atom)
}
#[cfg(target_os = "linux")]
fn output_icc_profile<C: x11rb::connection::RequestConnection>(conn: &C, output: u32, atom: u32) -> Option<Vec<u8>> {
use x11rb::protocol::{randr::ConnectionExt as _, xproto::AtomEnum};
let cookie = match conn.randr_get_output_property(output, atom, AtomEnum::CARDINAL, 0, ICC_PROFILE_PROPERTY_LONG_LENGTH, false, false) {
Ok(cookie) => cookie,
Err(_) => return None,
};
let reply = match cookie.reply() {
Ok(reply) => reply,
Err(_) => return None,
};
if reply.type_ != u32::from(AtomEnum::CARDINAL) || reply.format != 8 || reply.bytes_after != 0 {
return None;
}
icc_profile(reply.data)
}
#[cfg(target_os = "linux")]
fn root_icc_profile<C: x11rb::connection::RequestConnection>(conn: &C, root: u32, atom: u32) -> Option<Vec<u8>> {
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt as _};
let cookie = match conn.get_property(false, root, atom, AtomEnum::ANY, 0, ICC_PROFILE_PROPERTY_LONG_LENGTH) {
Ok(cookie) => cookie,
Err(_) => return None,
};
let reply = match cookie.reply() {
Ok(reply) => reply,
Err(_) => return None,
};
if reply.format != 8 || reply.bytes_after != 0 {
return None;
}
icc_profile(reply.value)
}
#[cfg(target_os = "linux")]
fn capture(wayland: bool, scale: f32, stop: &std::sync::atomic::AtomicBool, placements: &[Placement]) -> Result<Capture, String> {
if wayland {
return portal(stop);
@@ -55,10 +115,7 @@ fn capture(wayland: bool, scale: f32, stop: &std::sync::atomic::AtomicBool, plac
use x11rb::{
connection::Connection,
image::{Image, PixelLayout},
protocol::{
randr::ConnectionExt as _,
xproto::{AtomEnum, ConnectionExt, VisualClass},
},
protocol::{randr::ConnectionExt as _, xproto::VisualClass},
};
let (conn, index) = x11rb::connect(None).map_err(|e| e.to_string())?;
let screen = conn.setup().roots.get(index).ok_or("X11 screen is missing")?;
@@ -71,13 +128,16 @@ fn capture(wayland: bool, scale: f32, stop: &std::sync::atomic::AtomicBool, plac
{
first.primary = true;
}
let regions: Vec<(i16, i16, u16, u16, bool)> =
if monitors.is_empty() { vec![(0, 0, w, h, true)] } else { monitors.iter().map(|m| (m.x, m.y, m.width, m.height, m.primary)).collect() };
let regions: Vec<(i16, i16, u16, u16, bool, Vec<x11rb::protocol::randr::Output>)> = if monitors.is_empty() {
vec![(0, 0, w, h, true, Vec::new())]
} else {
monitors.iter().map(|m| (m.x, m.y, m.width, m.height, m.primary, m.outputs.clone())).collect()
};
if regions.len() > 16 {
return Err("Too many screens for the color picker".into());
}
let mut total = 0usize;
for &(x, y, mw, mh, _) in &regions {
for &(x, y, mw, mh, _, _) in &regions {
if x < 0 || y < 0 || u32::from(x as u16) + u32::from(mw) > u32::from(w) || u32::from(y as u16) + u32::from(mh) > u32::from(h) {
return Err("Invalid X11 display geometry".into());
}
@@ -92,20 +152,20 @@ fn capture(wayland: bool, scale: f32, stop: &std::sync::atomic::AtomicBool, plac
return Err("Screen picking requires an X11 TrueColor visual".into());
}
let layout = PixelLayout::from_visual_type(*visual).map_err(|e| e.to_string())?;
let atom = conn.intern_atom(true, b"_ICC_PROFILE").map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?.atom;
let primary_profile = if atom == 0 {
None
} else {
let reply = conn.get_property(false, screen.root, atom, AtomEnum::ANY, 0, 256 * 1024).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?;
(reply.bytes_after == 0 && reply.format == 8 && !reply.value.is_empty()).then_some(reply.value)
};
let output_profile_atom = icc_profile_atom(&conn, "_ICC_PROFILE");
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let byte = |v: u16| ((u32::from(v) + 128) / 257) as u8;
let mut images = Vec::new();
for (x, y, mw, mh, primary) in regions {
for (x, y, mw, mh, primary, outputs) in regions {
if stop.load(std::sync::atomic::Ordering::Relaxed) {
return Ok(Capture::Color(None));
}
let profile = output_profile_atom.and_then(|atom| outputs.iter().find_map(|output| output_icc_profile(&conn, *output, atom))).or_else(|| {
if !primary {
return None;
}
icc_profile_atom(&conn, "_ICC_PROFILE").and_then(|atom| root_icc_profile(&conn, screen.root, atom))
});
let mut rgba = Vec::with_capacity(count(usize::from(mw), usize::from(mh))?.saturating_mul(4));
for row in 0..mh {
for col in 0..mw {
@@ -120,7 +180,7 @@ fn capture(wayland: bool, scale: f32, stop: &std::sync::atomic::AtomicBool, plac
width: usize::from(mw),
height: usize::from(mh),
rgba,
profile: if primary { primary_profile.clone() } else { None },
profile,
});
}
Ok(Capture::Images(images))
@@ -359,6 +419,18 @@ mod tests {
}
#[cfg(target_os = "linux")]
#[test]
fn x11_screen_capture_accepts_only_bounded_rgb_icc_profiles() {
let rgb = photocraft_cms::Builtin::Srgb.profile().to_bytes();
let bytes = rgb.as_ref().clone();
assert_eq!(icc_profile(bytes.clone()), Some(bytes));
assert!(icc_profile(Vec::new()).is_none());
assert!(icc_profile(vec![0; MAX_ICC_PROFILE_BYTES + 1]).is_none());
let cmyk = photocraft_cms::Builtin::CoatedCmyk.profile().to_bytes();
assert!(icc_profile(cmyk.as_ref().clone()).is_none());
}
#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires a live X11 display; draws only a tiny synthetic fixture"]
fn screen_capture_reads_a_known_x11_fixture_pixel() {
use x11rb::{
+171 -28
View File
@@ -5,7 +5,7 @@ use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Document, Layer, Size};
use photocraft_format::RecoveryStore;
use photocraft_geom::Rect;
use photocraft_ui_egui::{FileDialogAnswer, FileDialogReply, FileDialogRequest, Recovered, Services};
use photocraft_ui_egui::{FileDialogAnswer, FileDialogReply, FileDialogRequest, Recoverable, Services};
use std::cell::RefCell;
use std::future::Future;
use std::path::{Path, PathBuf};
@@ -13,13 +13,18 @@ use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;
/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and
/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
#[cfg(test)]
mod recovery_tests;
/// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster and Affinity documents, flat images, and
/// Photoshop brushes (.abr), gradients (.grd), swatches (.aco, .ase) and keyboard shortcut sets
/// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts.
const OPEN_EXTS: &[&str] = &[
"pcraft", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam",
"pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af",
"afdesign", "afphoto", "afpub",
"pcraft", "pdn", "ora", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm",
"ppm", "pam", "pfm", "fits", "fit", "fts", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd",
"svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub",
];
const SVG_EXTS: &[&str] = &["svg", "svgz"];
/// Open dialog extensions that also match uppercase and mixed-case names (`IMG_0001.JPG`).
/// On Linux and the BSDs rfd turns each extension into a case-sensitive `*.ext` glob for the XDG
@@ -31,18 +36,31 @@ fn open_filter_extensions(extensions: &[&str]) -> Vec<String> {
extensions.iter().map(|ext| if case_sensitive_globs { ext.chars().map(class).collect() } else { ext.to_string() }).collect()
}
/// An explicit SVG filter keeps vector artwork discoverable even when a native picker defaults to
/// the PhotoCraft-only filter. SVG is also included in All Formats for normal multi-format opens.
fn open_filters() -> Vec<(&'static str, Vec<String>)> {
vec![
("All Formats", open_filter_extensions(OPEN_EXTS)),
("PhotoCraft", open_filter_extensions(&["pcraft"])),
("OpenRaster", open_filter_extensions(&["ora"])),
("SVG", open_filter_extensions(SVG_EXTS)),
]
}
/// File › Save As formats: (filter name, extensions). The filter matching the suggested name's
/// extension comes first, so a .pcraft document saves as .pcraft by default and everything else
/// keeps defaulting to Photoshop.
/// keeps defaulting to PSD.
const SAVE_FILTERS: &[(&str, &[&str])] = &[
("Photoshop", &["psd", "psb"]),
("PSD Document", &["psd", "psb"]),
("PhotoCraft", &["pcraft"]),
("OpenRaster", &["ora"]),
("PNG", &["png"]),
("JPEG", &["jpg"]),
("WebP", &["webp"]),
("TIFF", &["tif"]),
("Targa", &["tga"]),
("OpenEXR", &["exr"]),
("FITS", &["fits", "fit"]),
];
/// Non-document files the shell saves (Swatches panel exports): offered alone, so the dialog
@@ -76,8 +94,19 @@ fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>,
dialog = dialog.set_parent(parent);
}
let answer: Pin<Box<dyn Future<Output = Option<FileDialogAnswer>> + Send>> = match request {
FileDialogRequest::Open { multiple } => {
let dialog = dialog.add_filter("All Formats", &open_filter_extensions(OPEN_EXTS)).add_filter("PhotoCraft", &open_filter_extensions(&["pcraft"]));
FileDialogRequest::Open { multiple, initial_dir, extensions } => {
if let Some(dir) = initial_dir {
dialog = dialog.set_directory(dir);
}
// A command-specific filter must not inherit the image formats used by File › Open.
let dialog = if let Some(exts) = extensions {
dialog.add_filter("Supported Files", &open_filter_extensions(&exts.iter().map(String::as_str).collect::<Vec<_>>()))
} else {
open_filters()
.into_iter()
.fold(dialog, |dialog, (name, extensions)| dialog.add_filter(name, &extensions))
.add_filter("Paint.NET", &open_filter_extensions(&["pdn"]))
};
if multiple {
let picked = dialog.pick_files();
Box::pin(async move { picked.await.map(|files| FileDialogAnswer::Paths(files.iter().map(path_of).collect())) })
@@ -93,12 +122,19 @@ fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>,
if let Some(name) = Path::new(&suggested).file_name() {
dialog = dialog.set_file_name(name.to_string_lossy());
}
if let Some(dir) = Path::new(&suggested).parent().filter(|p| !p.as_os_str().is_empty()) {
dialog = dialog.set_directory(dir);
}
let picked = dialog.save_file();
Box::pin(async move { picked.await.map(|file| FileDialogAnswer::SaveTo(path_of(&file))) })
}
};
// Without the thread the reply is dropped unanswered, which the app takes as Cancel.
if let Err(e) = std::thread::Builder::new().name("file dialog".into()).spawn(move || reply.send(block_on(answer))) {
if let Err(e) = std::thread::Builder::new().name("file dialog".into()).spawn(move || {
// An empty answer from a system with no dialog backend isn't a Cancel (#3354).
let answer = block_on(answer).or_else(|| crate::file_dialog_probe::known_problem().map(FileDialogAnswer::Unavailable));
reply.send(answer)
}) {
log::error!("couldn't wait for the file dialog: {e}");
}
}
@@ -155,6 +191,65 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
photocraft_format::atomic_write(path, bytes).map_err(|e| e.to_string())
}
/// [`write_atomic`] reporting the fraction written (a background save's progress, #3389).
fn write_atomic_progress(path: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> Result<(), String> {
photocraft_format::atomic_write_progress(path, bytes, progress).map_err(|e| e.to_string())
}
fn export_options(settings: &photocraft_ui_egui::ExportSettings) -> photocraft_io::ExportOptions {
let mut opts = photocraft_io::ExportOptions::default();
if let Some(q) = settings.jpeg_quality {
opts.encode.jpeg_quality = q;
}
opts.encode.webp_lossless = settings.webp_lossless;
if let Some(q) = settings.webp_quality {
opts.encode.webp_quality = q;
}
opts.tiff_layers = settings.tiff_layers;
opts.xmp = if settings.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None };
opts.tga_bits = settings.tga_bits;
opts.image_previews = settings.image_previews;
opts
}
/// The share of a save's progress bar that encoding fills; writing the file fills the rest. A
/// 24 MP, 5-layer PSD (572 MB) takes about 3 s to encode and 0.5 s or more to write and flush.
const ENCODE_SHARE: f32 = 0.85;
/// A save on a worker thread (`Services::save_file` and `Services::automation_save`, #2017):
/// encode, then write through `write`. Cancelling while encoding leaves the target untouched;
/// once writing starts the save can't be cancelled. The encoder's progress fills the first
/// [`ENCODE_SHARE`] of the job's progress, so the status bar and tab read "Saving NN%" (#3389).
fn save_through(
doc: &Document,
path: &str,
settings: &photocraft_ui_egui::ExportSettings,
ctl: &photocraft_ui_egui::jobs_ui::SaveCtl,
write: impl Fn(&str, &[u8], &dyn Fn(f32)) -> Result<(), String>,
) -> Result<Vec<String>, String> {
ctl.progress(0.0, "Encoding");
let opts = export_options(settings);
let cancelled = || ctl.check().is_err();
let progress = |f: f32| ctl.progress(f * ENCODE_SHARE, "");
let interrupt = photocraft_raster::Interrupt::new(&cancelled, &progress);
let r = crate::crash_guard::guard("Save", || photocraft_io::export_with(doc, path, &opts, &interrupt).map_err(|e| e.to_string()))?;
ctl.commit()?;
ctl.progress(ENCODE_SHARE, "Writing");
// The last bit is the flush and rename after the last chunk: 100% only once they're done.
write(path, &r.bytes, &|f| ctl.progress(ENCODE_SHARE + (0.99 - ENCODE_SHARE) * f, ""))?;
ctl.progress(1.0, "");
Ok(r.warnings)
}
fn save_file(
doc: &Document,
path: &str,
settings: &photocraft_ui_egui::ExportSettings,
ctl: &photocraft_ui_egui::jobs_ui::SaveCtl,
) -> Result<Vec<String>, String> {
save_through(doc, path, settings, ctl, |p, b, progress| write_atomic_progress(Path::new(p), b, progress))
}
type SharedRecovery = Rc<RefCell<Option<RecoveryStore>>>;
/// Run `f` on the recovery store (`Err` without a config directory). The service closures never
@@ -168,8 +263,9 @@ fn with_store<R>(store: &SharedRecovery, f: impl FnOnce(&mut RecoveryStore) -> R
/// directory, so autosaves fail and nothing is recovered). Recovered documents keep their entries
/// until a newer autosave replaces them or they're saved or closed (see [`RecoveryStore`]).
fn recovery_services(dir: Option<PathBuf>) -> Services {
let recover_dir = dir.clone();
let store: SharedRecovery = Rc::new(RefCell::new(dir.map(RecoveryStore::new)));
let (s1, s2, s3, s4) = (store.clone(), store.clone(), store.clone(), store.clone());
let (s1, s2, s4) = (store.clone(), store.clone(), store.clone());
Services {
autosave: Some(Box::new(move |doc: &Arc<Document>, revision: u64, path: Option<&str>| {
with_store(&s1, |s| s.autosave_checked(doc, revision, path.map(str::to_string)))?
@@ -179,8 +275,16 @@ fn recovery_services(dir: Option<PathBuf>) -> Services {
let _ = with_store(&s2, |s| s.discard(id));
})),
recover: Some(Box::new(move || {
let found = with_store(&s3, |s| s.recover()).unwrap_or_default();
found.into_iter().map(|(e, doc)| Recovered { key: e.info.key, path: e.info.original_path, doc }).collect()
let Some(dir) = recover_dir.as_ref() else { return Vec::new() };
photocraft_format::list_recovery(dir)
.into_iter()
.map(|e| Recoverable {
key: e.info.key.clone(),
name: e.info.document_name.clone(),
path: e.info.original_path.clone(),
load: Box::new(move || photocraft_format::recover(&e).map_err(|e| e.to_string())),
})
.collect()
})),
adopt_autosave: Some(Box::new(move |id: u64, key: &str| {
let _ = with_store(&store, |s| s.adopt(id, key));
@@ -243,6 +347,18 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
let automation_write = automation.clone().map(|workspace| {
Box::new(move |path: &str, bytes: &[u8]| workspace.write(path, bytes).map_err(|error| error.to_string())) as photocraft_ui_egui::AutomationWriteFn
});
let automation_open_pcraft = automation.clone().map(|workspace| {
Box::new(move |path: &str| {
let name = Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path).to_string();
let opened = crate::crash_guard::guard("Open", || workspace.open_pcraft(path).map_err(|e| e.to_string()))?;
Ok(opened.map(|doc| (name, doc)))
}) as photocraft_ui_egui::AutomationOpenPcraftFn
});
let automation_save = automation.clone().map(|workspace| {
std::sync::Arc::new(move |doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl| {
save_through(doc, path, settings, ctl, |p, b, _| workspace.write(p, b).map_err(|e| e.to_string()))
}) as photocraft_ui_egui::SaveFileFn
});
let step: fn(&str, &serde_json::Value) -> photocraft_engine::Result<()> = photocraft_automation::workspace::authorize_desktop_engine_step;
let automation_authorize = automation.is_some().then_some(step);
let automation_command = automation.map(|_| {
@@ -251,26 +367,22 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
}) as photocraft_ui_egui::AutomationCommandFn
});
Services {
import: Some(Box::new(|name: &str, bytes: &[u8]| {
crate::crash_guard::guard("Open", || photocraft_io::import(name, bytes).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()))
import: Some(Box::new(|name: &str, bytes: &[u8], max_svg_group_depth: usize| {
crate::crash_guard::guard("Open", || {
photocraft_io::import_with_svg_group_depth(name, bytes, max_svg_group_depth).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string())
})
})),
export: Some(Box::new(|doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings| {
let mut opts = photocraft_io::ExportOptions::default();
if let Some(q) = settings.jpeg_quality {
opts.encode.jpeg_quality = q;
}
opts.encode.webp_lossless = settings.webp_lossless;
if let Some(q) = settings.webp_quality {
opts.encode.webp_quality = q;
}
opts.tiff_layers = settings.tiff_layers;
opts.xmp = if settings.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None };
let opts = export_options(settings);
crate::crash_guard::guard("Export", || photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()))
})),
save_file: Some(Arc::new(save_file)),
file_dialog: Some(Box::new(show_file_dialog)),
write: Some(Box::new(|path: &str, bytes: &[u8]| write_atomic(Path::new(path), bytes))),
automation_read,
automation_write,
automation_open_pcraft,
automation_save,
automation_command,
automation_authorize,
encode_png: Some(Box::new(|w, h, rgba| {
@@ -279,6 +391,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
})),
inbox: None,
open_url: Some(Box::new(|url: &str| open::that(url).map_err(|e| e.to_string()))),
beep: Some(platform_beep),
clipboard_set_image: Some({
let clip = clip.clone();
Box::new(move |w: u32, h: u32, px: &[u8]| {
@@ -308,7 +421,9 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
})
}),
load_prefs: Some(Box::new(|| std::fs::read_to_string(prefs_file()?).ok())),
photoshop_shortcuts: Some(Box::new(|| crate::photoshop_settings::live_keyboard_shortcuts(&|k| std::env::var_os(k)))),
save_prefs: Some(Box::new(|text: &str| write_atomic(&prefs_file().ok_or("no config directory")?, text.as_bytes()))),
system_theme: crate::appearance::service(),
append_text: Some(Box::new(|path: &str, text: &str| {
use std::io::Write;
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path).map_err(|e| e.to_string())?;
@@ -323,6 +438,21 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
}
}
/// Preferences ▸ General ▸ Beep When Done: the platform's default information beep.
fn platform_beep() {
#[cfg(target_os = "windows")]
{
let _ = winsafe::MessageBeep(winsafe::co::MBP::OK);
}
#[cfg(not(target_os = "windows"))]
{
// No beep API among this app's other platforms' dependencies: write the terminal bell
// (audible when launched from a terminal, which is the same cue macOS terminals use).
use std::io::Write as _;
let _ = std::io::stdout().write_all(b"\x07").and_then(|()| std::io::stdout().flush());
}
}
/// Flat-image import via photocraft-codecs (kept for reference/tests; the app uses photocraft-io).
#[allow(dead_code)]
pub fn import_flat(name: &str, bytes: &[u8]) -> Result<Document, String> {
@@ -422,6 +552,9 @@ mod tests {
assert!(!matches(glob, &format!("{ext}x")) && !matches(glob, &ext[..ext.len() - 1]), "{glob} matches only .{ext}");
}
assert!(!globs.iter().any(|glob| matches(glob, "txt")));
let svg_filter = open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts).unwrap_or_default();
assert_eq!(svg_filter, open_filter_extensions(SVG_EXTS));
assert!(svg_filter.iter().any(|glob| matches(glob, "svg")) && svg_filter.iter().any(|glob| matches(glob, "svgz")));
}
#[cfg(not(all(unix, not(target_os = "macos"))))]
@@ -429,6 +562,7 @@ mod tests {
fn open_filters_keep_literal_extensions_on_windows_and_macos() {
assert_eq!(open_filter_extensions(OPEN_EXTS), OPEN_EXTS);
assert_eq!(open_filter_extensions(&["pcraft"]), ["pcraft"]);
assert_eq!(open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts), Some(vec!["svg".to_string(), "svgz".to_string()]));
}
#[test]
@@ -523,7 +657,7 @@ mod tests {
for (name, ext) in asked.iter().zip(exts) {
assert!(save_filters(name)[0].1.iter().any(|e| e == ext), "{name}: {:?}", save_filters(name)[0]);
}
assert_eq!(save_filters("Untitled")[0].0, "Photoshop", "no extension keeps the default");
assert_eq!(save_filters("Untitled")[0].0, "PSD Document", "no extension keeps the default");
}
#[test]
@@ -550,7 +684,16 @@ mod tests {
/// One app launch with crash recovery in `dir` (dropping it is the crash: background writes
/// already queued finish, nothing else runs).
fn launch(dir: &Path) -> PhotocraftApp {
PhotocraftApp::new(Session::new(), recovery_services(Some(dir.to_path_buf())))
let mut app = PhotocraftApp::new(Session::new(), recovery_services(Some(dir.to_path_buf())));
let ctx = egui::Context::default();
prefs_ui::tick(&mut app, &ctx);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.session.has_jobs() && std::time::Instant::now() < deadline {
photocraft_ui_egui::jobs_ui::tick(&mut app, &ctx);
std::thread::sleep(std::time::Duration::from_millis(1));
}
assert!(!app.session.has_jobs(), "recovery finished");
app
}
/// The first pixel of each open document, and whether it's unsaved.
@@ -0,0 +1,68 @@
use super::*;
use photocraft_color::Color;
use photocraft_format::{Autosaver, RecoveryEntry, SaveOptions, list_recovery};
use std::sync::atomic::{AtomicUsize, Ordering};
fn snapshot(tag: &str) -> (PathBuf, Document, RecoveryEntry) {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!("photocraft-deferred-recovery-{tag}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&dir);
let mut doc = Document::with_background("Recovered drawing", Size::new(4, 3), ColorMode::Rgb, SampleType::U16, Color::WHITE);
doc.layers[0].surface_mut().unwrap().write_pixel(1, 2, &[1.0, 0.0, 0.0, 1.0]);
let saver = Autosaver::new(&dir, "previous-session");
saver.request_checked(Arc::new(doc.clone()), 7, Some(dir.join("original.pcraft").to_string_lossy().into_owned()), SaveOptions::default()).unwrap();
assert!(saver.flush().unwrap().unwrap().tiles_written > 0);
let mut entries = list_recovery(&dir);
assert_eq!(entries.len(), 1);
(dir, doc, entries.pop().unwrap())
}
#[test]
fn recovery_discovers_metadata_before_decoding_and_keeps_a_failed_snapshot() {
let (dir, doc, entry) = snapshot("corrupt");
let tile = std::fs::read_dir(entry.bundle.join("tiles")).unwrap().next().unwrap().unwrap().path();
std::fs::write(&tile, b"corrupt compressed tile").unwrap();
let sidecar = dir.join(format!("{}.json", entry.info.key));
let metadata = std::fs::read(&sidecar).unwrap();
let mut services = recovery_services(Some(dir.clone()));
let mut found = services.recover.as_mut().unwrap()();
assert_eq!(found.len(), 1, "discovery lists metadata without decoding the corrupt pixels");
let pending = found.pop().unwrap();
assert_eq!(pending.key, entry.info.key);
assert_eq!(pending.name, doc.name);
assert_eq!(pending.path, entry.info.original_path);
assert!((pending.load)().is_err(), "decoding is deferred until the loader runs");
assert_eq!(std::fs::read(&tile).unwrap(), b"corrupt compressed tile");
assert_eq!(std::fs::read(&sidecar).unwrap(), metadata);
assert_eq!(list_recovery(&dir), vec![entry], "a failed recovery must leave the snapshot available");
drop(services);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn deferred_recovery_preserves_pixels_and_metadata_until_the_adopted_entry_is_discarded() {
let (dir, doc, entry) = snapshot("valid");
let mut services = recovery_services(Some(dir.clone()));
let mut found = services.recover.as_mut().unwrap()();
assert_eq!(found.len(), 1);
let pending = found.pop().unwrap();
assert_eq!(pending.key, entry.info.key);
assert_eq!(pending.name, doc.name);
assert_eq!(pending.path, entry.info.original_path);
// The loader can move to a worker without taking the main thread's recovery store with it.
let restored = std::thread::spawn(pending.load).join().unwrap().unwrap();
assert_eq!(restored, doc);
assert_eq!(restored.layers[0].surface().unwrap().pixel(1, 2), vec![1.0, 0.0, 0.0, 1.0]);
services.adopt_autosave.as_mut().unwrap()(restored.id.0, &pending.key);
assert_eq!(list_recovery(&dir), vec![entry.clone()], "loading and adopting retain the recovery files");
services.discard_autosave.as_mut().unwrap()(restored.id.0);
assert!(list_recovery(&dir).is_empty());
assert!(!entry.bundle.exists());
assert!(!dir.join(format!("{}.json", pending.key)).exists());
drop(services);
std::fs::remove_dir_all(dir).unwrap();
}
+198
View File
@@ -0,0 +1,198 @@
//! Keeps the custom (undecorated) title bar window truly borderless (#2246).
//!
//! winit 0.30 gives an undecorated window the `WS_CAPTION | WS_BORDER` styles and hides the
//! non-client area by spreading the client rect over it (`WM_NCCALCSIZE`). On some systems
//! (reported: Windows 10 LTSB, Intel HD Graphics 4600, 1366 × 768) the desktop compositor still
//! reserves that frame for the window surface: the content is drawn offset by the caption and
//! border, leaving black bars at the window's top-left, while the pointer keeps the un-offset
//! client coordinates, so it no longer points at what is drawn under it.
//!
//! winit 0.27 — before rust-windowing/winit#2419 — simply omitted those styles for undecorated
//! windows, and there was no offset. [`service`] restores that: it strips `WS_CAPTION` and
//! `WS_BORDER` and forces Windows to recalculate the frame. winit puts them back whenever it
//! changes the window flags (maximize, restore, …), so the returned guard checks every frame.
//!
//! Windows sizes a maximize by the frame its styles describe, so a window maximized while its
//! caption is gone is sized without one: its rect covers the whole monitor, taskbar included.
//! The shell reads a caption-less window covering its monitor as a full-screen app and drops the
//! taskbar's backdrop behind it — a black band on stock Windows 11, a glitched unresponsive one
//! under ExplorerPatcher (#3144). The guard therefore also trims a parked maximize's rect back to
//! the work area plus its own frame, clear of the taskbar. winit pins the client area to the work
//! area either way (`WM_NCCALCSIZE`), so the app's pixels do not move.
//!
//! The Windows calls go through safe `winsafe` wrappers; the workspace forbids `unsafe`, and
//! winsafe can't wrap a raw handle without it, so the window is found by its handle instead.
pub use platform::service;
#[cfg(target_os = "windows")]
mod platform {
use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle};
use photocraft_ui_egui::WindowFrameFn;
use winsafe::{HWND, HwndPlace, POINT, SIZE, co};
/// A guard that keeps the window borderless each frame, or `None` when the app uses the
/// system title bar (the window is decorated) or its handle can't be found.
pub fn service(cc: &eframe::CreationContext<'_>, custom_titlebar: bool) -> Option<WindowFrameFn> {
if !custom_titlebar {
return None;
}
let target = match cc.window_handle().ok()?.as_raw() {
RawWindowHandle::Win32(h) => h.hwnd.get(),
_ => return None,
};
let hwnd = find_window(target)?;
reapply(&hwnd);
Some(Box::new(move || reapply(&hwnd)))
}
/// The top-level window with the given raw handle. `EnumWindows` hands out real `HWND`s, so
/// this matches winit's own window without wrapping a raw handle (which needs `unsafe`).
fn find_window(target: isize) -> Option<HWND> {
let mut found = None;
let _ = winsafe::EnumWindows(|hwnd| {
if hwnd.ptr() as isize == target {
found = Some(hwnd);
false
} else {
true
}
});
found
}
/// One pass of the per-frame guard: the styles winit put back come off again, and a parked
/// maximize stays clear of the taskbar.
fn reapply(hwnd: &HWND) {
strip(hwnd);
keep_clear_of_the_taskbar(hwnd);
}
/// Removes `WS_CAPTION`/`WS_BORDER` and has Windows recalculate the frame. A no-op once they
/// are gone, so it is cheap to call every frame.
fn strip(hwnd: &HWND) {
let style = hwnd.style();
let without = borderless(style);
if without.raw() == style.raw() {
return;
}
hwnd.set_style(without);
let _ = hwnd.SetWindowPos(
HwndPlace::None,
POINT::new(),
SIZE::new(),
co::SWP::FRAMECHANGED | co::SWP::NOMOVE | co::SWP::NOSIZE | co::SWP::NOZORDER | co::SWP::NOACTIVATE,
);
}
/// How far a parked maximize reaches past its monitor on the left, top and right: the resize
/// border (about 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not
/// parked but being dragged or snapped, and is left alone.
const FRAME: i32 = 32;
/// [`clamped_height`] for this frame's window: trim a maximized window whose rect runs under
/// the taskbar back to the work area plus its frame (#3144). No-op otherwise.
fn keep_clear_of_the_taskbar(hwnd: &HWND) {
if !hwnd.IsZoomed() {
return;
}
let (Ok(r), Ok(mi)) = (hwnd.GetWindowRect(), hwnd.MonitorFromWindow(co::MONITOR::DEFAULTTONEAREST).GetMonitorInfo()) else {
return;
};
let (m, w) = (mi.rcMonitor, mi.rcWork);
let Some(height) = clamped_height((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom)) else {
return;
};
let _ = hwnd.SetWindowPos(
HwndPlace::None,
POINT::new(),
SIZE { cx: r.right - r.left, cy: height },
co::SWP::NOMOVE | co::SWP::NOZORDER | co::SWP::NOACTIVATE,
);
}
/// The height to trim a maximize to so its rect stops at the taskbar, or `None` when it
/// already does or `rect` (`left, top, right, bottom`, desktop coordinates) is not parked at
/// its maximize place. `monitor` is the monitor's full rect and `work` its work area (the
/// monitor less the taskbar) in the same coordinates. The parked check is against the full
/// monitor, because that is where Windows puts a maximize; the trim is against the work area.
fn clamped_height(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<i32> {
let (l, t, r, b) = rect;
let (ml, mt, mr, _) = monitor;
let (_, _, _, wb) = work;
let side = ml - l;
if !(0..=FRAME).contains(&side) || !(0..=FRAME).contains(&(mt - t)) || !(0..=FRAME).contains(&(r - mr)) {
return None;
}
if b <= wb + side {
return None;
}
Some(wb + side - t)
}
/// `style` without the OS title bar and frame (`WS_CAPTION`, which already includes
/// `WS_BORDER`). The sizing border (`WS_THICKFRAME`) stays, so edge resizing and Aero snap
/// keep working, as they did with winit 0.27's undecorated windows.
fn borderless(style: co::WS) -> co::WS {
style & !(co::WS::CAPTION | co::WS::BORDER)
}
#[cfg(test)]
mod tests {
use super::{borderless, clamped_height};
use winsafe::co;
#[test]
fn the_borderless_style_drops_the_caption_and_border_only() {
// `WS_CAPTION` is 0x00c0_0000 and already contains `WS_BORDER` (0x0080_0000).
let decorated = co::WS::CAPTION | co::WS::BORDER | co::WS::SYSMENU | co::WS::THICKFRAME | co::WS::MAXIMIZEBOX | co::WS::MINIMIZEBOX;
let bare = borderless(decorated);
assert!(!bare.has(co::WS::CAPTION), "caption gone");
assert!(!bare.has(co::WS::BORDER), "border gone");
assert!(bare.has(co::WS::THICKFRAME), "edge resizing kept");
assert!(bare.has(co::WS::MAXIMIZEBOX) && bare.has(co::WS::SYSMENU), "window buttons kept");
// Already borderless: unchanged, so the per-frame call does nothing.
assert_eq!(bare.raw(), borderless(bare).raw());
}
#[test]
fn a_maximize_covering_the_taskbar_is_trimmed_to_the_work_area() {
// 1920 × 1080 with a 34 pt taskbar: a caption-less maximize covers the whole
// monitor, taskbar included (#3144). Trimmed so the rect ends at the work area
// plus the frame the window was parked with.
let monitor = (0, 0, 1920, 1080);
let work = (0, 0, 1920, 1046);
assert_eq!(clamped_height((-7, -7, 1927, 1087), monitor, work), Some(1046 + 7 - (-7)));
}
#[test]
fn a_maximize_already_clear_of_the_taskbar_is_left_alone() {
// What Windows sizes a framed maximize to: the work area plus the frame.
assert_eq!(clamped_height((-8, -8, 1928, 1054), (0, 0, 1920, 1080), (0, 0, 1920, 1046)), None);
}
#[test]
fn a_maximize_beside_a_side_taskbar_is_left_alone() {
// Taskbar on the left: the work area starts further right, but the monitor's bottom
// is still clear, so the rect reaches nothing.
assert_eq!(clamped_height((-8, -8, 1928, 1088), (0, 0, 1920, 1080), (48, 0, 1920, 1080)), None);
}
#[test]
fn a_maximize_being_dragged_away_is_left_alone() {
let monitor = (0, 0, 1920, 1080);
let work = (0, 0, 1920, 1046);
assert_eq!(clamped_height((100, 200, 1100, 900), monitor, work), None, "moved");
assert_eq!(clamped_height((-500, -7, 1427, 1087), monitor, work), None, "resized");
}
}
}
#[cfg(not(target_os = "windows"))]
mod platform {
use photocraft_ui_egui::WindowFrameFn;
pub fn service(_cc: &eframe::CreationContext<'_>, _custom_titlebar: bool) -> Option<WindowFrameFn> {
None
}
}
@@ -0,0 +1,73 @@
//! `--control` setup failures must exit non-zero (#1816): a launcher that sees
//! status 0 believes the control server is running when it is not.
//!
//! These tests run the real binary as a subprocess and assert the exit code,
//! covering both failure paths in `main.rs`: control authentication and the
//! automation workspace.
/// A syntactically valid 64-hex-char token, so the workspace test reaches the
/// workspace check instead of failing on token validation first.
const VALID_TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
/// Run `photocraft` with the given arguments in an isolated config dir and
/// return the exit status and stderr. Each call gets its own config dir (tests run in
/// parallel), and no display variables, so a regression fails fast instead of opening a window.
fn run_photocraft(args: &[&str]) -> (std::process::ExitStatus, String) {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("photocraft-control-exit-{}-{n}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let output = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft"))
.args(args)
.env("PHOTOCRAFT_CONFIG_DIR", &dir)
// Isolate from the host environment so the test is reproducible.
.env_remove("PHOTOCRAFT_CONTROL_PORT")
.env_remove("PHOTOCRAFT_CONTROL_TOKEN")
.env_remove("PHOTOCRAFT_CONTROL_TOKEN_FILE")
.env_remove("PHOTOCRAFT_AUTOMATION_READ_ROOT")
.env_remove("PHOTOCRAFT_AUTOMATION_WRITE_ROOT")
.env_remove("DISPLAY")
.env_remove("WAYLAND_DISPLAY")
.env_remove("WAYLAND_SOCKET")
.output()
.expect("failed to run photocraft binary");
std::fs::remove_dir_all(&dir).ok();
(output.status, String::from_utf8_lossy(&output.stderr).into_owned())
}
#[test]
fn invalid_control_token_exits_with_status_2() {
// `validate_token` rejects a token that is not exactly 64 hex characters.
let (status, stderr) = run_photocraft(&["--control", "0", "--control-token", "invalid"]);
assert_eq!(status.code(), Some(2), "invalid control token must exit 2, stderr: {stderr}");
assert!(stderr.contains("cannot configure control authentication"), "stderr: {stderr}");
}
#[test]
fn both_token_and_token_file_exits_with_status_2() {
// `server_token` rejects the combination of a supplied token and a token file.
let dir = std::env::temp_dir().join(format!("photocraft-token-file-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let token_file = dir.join("token.txt");
std::fs::write(&token_file, VALID_TOKEN).unwrap();
let (status, stderr) = run_photocraft(&["--control", "0", "--control-token", VALID_TOKEN, "--control-token-file", token_file.to_str().unwrap()]);
std::fs::remove_dir_all(&dir).ok();
assert_eq!(status.code(), Some(2), "token + token file must exit 2, stderr: {stderr}");
assert!(stderr.contains("cannot configure control authentication"), "stderr: {stderr}");
}
#[test]
fn missing_automation_read_root_exits_with_status_2() {
// `AuthorizedWorkspace::new` fails when the read root does not exist.
let (status, stderr) = run_photocraft(&["--control", "0", "--control-token", VALID_TOKEN, "--automation-read-root", "/nonexistent/photocraft-test-path"]);
assert_eq!(status.code(), Some(2), "missing read root must exit 2, stderr: {stderr}");
assert!(stderr.contains("cannot configure automation workspace"), "stderr: {stderr}");
}
#[test]
fn missing_automation_write_root_exits_with_status_2() {
// `AuthorizedWorkspace::new` fails when the write root does not exist.
let (status, stderr) = run_photocraft(&["--control", "0", "--control-token", VALID_TOKEN, "--automation-write-root", "/nonexistent/photocraft-test-path"]);
assert_eq!(status.code(), Some(2), "missing write root must exit 2, stderr: {stderr}");
assert!(stderr.contains("cannot configure automation workspace"), "stderr: {stderr}");
}
+27 -1
View File
@@ -134,7 +134,8 @@ fn main() {
.iter()
.filter_map(|e| if let egui::Event::Key { key, pressed, modifiers, .. } = e { Some((*key, *pressed, modifiers.command)) } else { None })
.collect();
assert_eq!(keys, [(egui::Key::R, true, true), (egui::Key::R, false, true)], "the key press, then its release");
// AppKit took only the key-down; winit delivers the key-up itself (#1638).
assert_eq!(keys, [(egui::Key::R, true, true)], "the key press");
frame(&mut app, raw);
let ran: Vec<String> = photocraft_ui_egui::shortcut_dispatch::take_log(&ctx).into_iter().map(|(id, _)| id).collect();
assert_eq!(ran, ["view.rulers"], "⌘R ran Rulers, whichever ⌘R item AppKit matched");
@@ -164,6 +165,31 @@ fn main() {
frame(&mut app, raw);
assert_eq!(app.ui.extras.rulers, !rulers, "↩ on Rulers toggled it");
// Window ends with the open documents (#2991). Opening one rebuilds only the Window menu,
// which AppKit still knows as its Window menu; choosing a row brings that document forward.
app.run("file.new", json!({"width": 32, "height": 32})).expect("a second document");
frame(&mut app, egui::RawInput::default());
assert!(Retained::as_ptr(&bar) == Retained::as_ptr(&main_menu()), "a new document rebuilt only the Window menu");
let window = submenu(&main_menu(), "Window");
assert!(nsapp.windowsMenu().is_some_and(|w| Retained::as_ptr(&w) == Retained::as_ptr(&window)), "AppKit knows the new Window menu");
let names: Vec<String> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect();
// The last rows (both documents are "Untitled").
let rows = [window.numberOfItems() - 2, window.numberOfItems() - 1];
let shown: Vec<String> = rows.iter().filter_map(|&i| window.itemAtIndex(i)).map(|it| it.title().to_string()).collect();
assert_eq!(shown, names, "in tab order, after Bring All to Front: {:?}", titles(&window));
let checked = |menu: &NSMenu, at: isize| menu.itemAtIndex(at).is_some_and(|it| it.state() == 1);
assert!(!checked(&window, rows[0]) && checked(&window, rows[1]), "the active document is checked");
dequeue(&other());
window.performActionForItemAtIndex(rows[0]);
let mut raw = egui::RawInput::default();
if let Some(m) = app.services.native_menu.as_mut() {
m.raw_input(&mut raw);
}
frame(&mut app, raw);
assert_eq!(app.session.active_index(), Some(0), "choosing the first row brought it forward");
let window = submenu(&main_menu(), "Window");
assert!(checked(&window, rows[0]) && !checked(&window, rows[1]), "the check moved in place");
println!("mac_menu_appkit: ok");
}
+207
View File
@@ -0,0 +1,207 @@
Original painting symmetry axis icons by @shorbank (2026).
Files: symmetry-vertical.svg, symmetry-horizontal.svg, symmetry-dual.svg, symmetry-diagonal.svg.
SPDX-License-Identifier: MIT OR Apache-2.0
These original icons are available under either licence below, at your option.
MIT License
Copyright (c) 2026 shorbank
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+14
View File
@@ -0,0 +1,14 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor" />
</svg>

After

Width:  |  Height:  |  Size: 300 B

+16
View File
@@ -0,0 +1,16 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Artboard tool glyph (not from an icon set): a board with a tick at each end of its edges. -->
<rect x="7" y="7" width="10" height="10" rx="1" />
<path d="M7 2v2.5M17 2v2.5M7 19.5V22M17 19.5V22" />
<path d="M2 7h2.5M2 17h2.5M19.5 7H22M19.5 17H22" />
</svg>

After

Width:  |  Height:  |  Size: 487 B

+21
View File
@@ -0,0 +1,21 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M10 12.01h.01" />
<path d="M10 16.01h.01" />
<path d="M14 12.01h.01" />
<path d="M14 16.01h.01" />
<path d="M18 8v12" />
<path d="M6 8v12" />
<rect x="2" y="8" width="20" height="12" rx="2" />
<path d="M20 1v4" />
<path d="M22 3h-4" />
</svg>

After

Width:  |  Height:  |  Size: 471 B

+19
View File
@@ -0,0 +1,19 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m11 10 3 3" />
<path d="M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z" />
<path d="M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031" />
<path d="M2.5 9A6 6 0 0 1 8 3" />
<path d="m6 1.5 2 1.5-2 1.5" />
<path d="M21.5 15a6 6 0 0 1-5.5 6" />
<path d="m18 19.5-2 1.5 2 1.5" />
</svg>

After

Width:  |  Height:  |  Size: 544 B

@@ -9,6 +9,5 @@
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="18" height="18" x="3" y="3" rx="2" />
<circle cx="12" cy="12" r="1" />
<path d="m15 18-6-6 6-6" />
</svg>
+16
View File
@@ -0,0 +1,16 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Convert Point glyph: a corner point, an angle with a square anchor on its apex. -->
<rect x="9.75" y="4.75" width="4.5" height="4.5" />
<path d="M10.5 9.25 4 19" />
<path d="M13.5 9.25 20 19" />
</svg>

After

Width:  |  Height:  |  Size: 433 B

+15
View File
@@ -0,0 +1,15 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Frame tool glyph (not from an icon set): an empty placeholder frame, crossed corner to corner. -->
<rect x="3" y="4" width="18" height="16" rx="1" />
<path d="M6.5 7.5l11 9M17.5 7.5l-11 9" />
</svg>

After

Width:  |  Height:  |  Size: 428 B

+14
View File
@@ -0,0 +1,14 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="20" height="16" x="2" y="4" rx="2" />
<circle cx="12" cy="12" r="4" fill="currentColor" />
</svg>

After

Width:  |  Height:  |  Size: 316 B

+15
View File
@@ -0,0 +1,15 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M9 17H7A5 5 0 0 1 7 7h2" />
<path d="M15 7h2a5 5 0 1 1 0 10h-2" />
<line x1="8" x2="16" y1="12" y2="12" />
</svg>

After

Width:  |  Height:  |  Size: 330 B

+18
View File
@@ -0,0 +1,18 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Single Column Marquee glyph: a dashed column from edge to edge. -->
<path d="M8 3h8" />
<path d="M8 21h8" />
<path d="M12 6.5v1" />
<path d="M12 11.5v1" />
<path d="M12 16.5v1" />
</svg>

After

Width:  |  Height:  |  Size: 422 B

+18
View File
@@ -0,0 +1,18 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Single Row Marquee glyph: a dashed row from edge to edge. -->
<path d="M3 8v8" />
<path d="M21 8v8" />
<path d="M6.5 12h1" />
<path d="M11.5 12h1" />
<path d="M16.5 12h1" />
</svg>

After

Width:  |  Height:  |  Size: 416 B

+15
View File
@@ -0,0 +1,15 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="20" height="14" x="2" y="3" rx="2" />
<line x1="8" x2="16" y1="21" y2="21" />
<line x1="12" x2="12" y1="17" y2="21" />
</svg>

After

Width:  |  Height:  |  Size: 346 B

+13
View File
@@ -0,0 +1,13 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 29.33 30.81"
fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
>
<path stroke-width="2.48" d="M1.33,11.42c0-4.05,3.28-7.33,7.33-7.33,2.08,0,4.06.88,5.45,2.43.28.3.75.32,1.06.04.01-.01.02-.02.04-.04,2.69-3.02,7.31-3.29,10.33-.6,1.57,1.4,2.46,3.4,2.45,5.5,0,3.05-2,5.33-4,7.33l-7.32,7.08c-.97,1.11-2.65,1.23-3.76.26-.08-.07-.16-.15-.24-.23l-7.34-7.11c-2-2-4-4.27-4-7.33" />
<line stroke-width="2.41" x1="14.57" y1="1.3" x2="14.76" y2="29.51" />
</svg>

After

Width:  |  Height:  |  Size: 577 B

+18
View File
@@ -0,0 +1,18 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z" />
<path d="m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18" />
<path d="m2.3 2.3 7.286 7.286" />
<circle cx="11" cy="11" r="2" />
<path d="M18 3.5h5" />
<path d="M20.5 1v5" />
</svg>

After

Width:  |  Height:  |  Size: 594 B

+21
View File
@@ -0,0 +1,21 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<g transform="translate(7 7) scale(0.68)" stroke-width="2.6">
<path d="M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z" />
<path d="m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18" />
<path d="m2.3 2.3 7.286 7.286" />
<circle cx="11" cy="11" r="2" />
</g>
<path d="M3 12C3 7 7 3 12 3" />
<circle cx="3" cy="12" r="1" fill="currentColor" />
<circle cx="12" cy="3" r="1" fill="currentColor" />
</svg>

After

Width:  |  Height:  |  Size: 765 B

+17
View File
@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z" />
<path d="m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18" />
<path d="m2.3 2.3 7.286 7.286" />
<circle cx="11" cy="11" r="2" />
<path d="M18 3.5h5" />
</svg>

After

Width:  |  Height:  |  Size: 569 B

+19
View File
@@ -0,0 +1,19 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<g transform="translate(7 7) scale(0.68)" stroke-width="2.6">
<path d="M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z" />
<path d="m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18" />
<path d="m2.3 2.3 7.286 7.286" />
<circle cx="11" cy="11" r="2" />
</g>
<path d="M8.5 8.5C6 6 7.5 3 5 3S2 6 4 7.5 5.5 11 3 12" />
</svg>

After

Width:  |  Height:  |  Size: 683 B

+19
View File
@@ -0,0 +1,19 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Perspective Crop tool glyph (not from an icon set): a crop frame seen in
perspective, with its grid and two crop-mark ticks. -->
<path d="M8 6h8l4 12H4z" />
<path d="M12 6v12" />
<path d="M6 12h12" />
<path d="M8 2v2" />
<path d="M20 22v-2" />
</svg>

After

Width:  |  Height:  |  Size: 493 B

+15
View File
@@ -0,0 +1,15 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="7" />
<circle cx="12" cy="12" r="1.4" />
<path d="M12 2v3M12 19v3M2 12h3M19 12h3" />
</svg>

After

Width:  |  Height:  |  Size: 326 B

+13
View File
@@ -0,0 +1,13 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="currentColor"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" />
</svg>

After

Width:  |  Height:  |  Size: 596 B

+13
View File
@@ -0,0 +1,13 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" />
</svg>

After

Width:  |  Height:  |  Size: 588 B

+13
View File
@@ -0,0 +1,13 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 30.81 30.81"
fill="none"
stroke="currentColor"
stroke-width="2.41"
stroke-linecap="round"
stroke-linejoin="round"
>
<line x1="25.445" y1="25.32" x2="5.365" y2="5.5" />
</svg>

After

Width:  |  Height:  |  Size: 271 B

+14
View File
@@ -0,0 +1,14 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 30.81 30.81"
fill="none"
stroke="currentColor"
stroke-width="2.41"
stroke-linecap="round"
stroke-linejoin="round"
>
<line x1="29.51" y1="15.31" x2="1.3" y2="15.5" />
<line x1="15.5" y1="29.51" x2="15.31" y2="1.3" />
</svg>

After

Width:  |  Height:  |  Size: 321 B

+13
View File
@@ -0,0 +1,13 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 30.81 30.81"
fill="none"
stroke="currentColor"
stroke-width="2.41"
stroke-linecap="round"
stroke-linejoin="round"
>
<line x1="29.51" y1="15.315" x2="1.3" y2="15.505" />
</svg>

After

Width:  |  Height:  |  Size: 272 B

+13
View File
@@ -0,0 +1,13 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 30.81 30.81"
fill="none"
stroke="currentColor"
stroke-width="2.41"
stroke-linecap="round"
stroke-linejoin="round"
>
<line x1="15.315" y1="1.3" x2="15.505" y2="29.51" />
</svg>

After

Width:  |  Height:  |  Size: 272 B

+19
View File
@@ -0,0 +1,19 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Vertical Type Mask glyph (not from an icon set): a T drawn as marching
ants beside a downward arrow (the text runs top to bottom). -->
<path d="M2.5 7V4h12v3" stroke-dasharray="2.5 2.5" />
<path d="M8.5 4v16" stroke-dasharray="2.5 2.5" />
<path d="M6 20h5" stroke-dasharray="2.5 2.5" />
<path d="M20 8v12" />
<path d="M17.5 17.5 20 20l2.5-2.5" />
</svg>

After

Width:  |  Height:  |  Size: 596 B

+16
View File
@@ -0,0 +1,16 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Horizontal Type Mask glyph (not from an icon set): a T drawn as marching ants. -->
<path d="M4 7V4h16v3" stroke-dasharray="2.5 2.5" />
<path d="M12 4v16" stroke-dasharray="2.5 2.5" />
<path d="M8.5 20h7" stroke-dasharray="2.5 2.5" />
</svg>

After

Width:  |  Height:  |  Size: 472 B

+26
View File
@@ -35,6 +35,32 @@ Warnings do not change the saved document's font declarations and do not stop
the operation. To list or replace the missing families intentionally, use
`type.resolveMissingFonts` on the document.
### Export selected adjustment layers as a .cube LUT
The engine command `file.export.colorLookupTables` creates a 3D LUT from an
identity RGB lattice. It can export all visible top-level adjustment layers
(the default), the current Layers panel selection, or a supplied list of
adjustment layer IDs. The `scope` and `layers` parameters are mutually
exclusive when `scope` is `selected`:
```json
{"size": 33, "scope": "selected", "path": "chosen-look.cube"}
```
For automation that does not use the Layers panel, supply `"layers": [10, 14]`
instead. Input ID order does not change the final color look: adjustments are
always baked in **document stacking order**, bottom to top. When `path` is
omitted, the command returns the .cube text in `cube`; both forms return
`size` and `layerCount`.
Valid LUT dimensions are 2–129 (same maximum as PhotoCraft's LUT reader).
Selected IDs must exist, be visible top-level adjustment layers, and contain
no duplicates; invalid selections report an error rather than silently
exporting a different look. Masks, vector masks and clipping are spatial
operations and cannot be represented faithfully by a color-only LUT, so the
baker omits them. Group-contained adjustments are not exported as independent
layers because that would lose their group's blending semantics.
Paths supplied to the current CLI are ordinary operating-system paths. The CLI does not restrict them to a workspace root. Batch output creates the requested output directory, and save operations may create parent directories. `batch` refuses an output directory that is its input directory (the results would replace the originals) unless `--in-place` is given. Run untrusted action files only in an appropriately isolated account or environment.
CLI parsing reports malformed flags and JSON as errors, and a flag the subcommand doesn't take (a typo such as `--fromat`) is a usage error (exit status 2) rather than being ignored. It is not a security policy layer. Engine commands remain responsible for validating their own parameters.
+17
View File
@@ -19,6 +19,23 @@ photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file /private/path/co
Tools cover session/document operations, command discovery and execution, batching, and—when bridged—UI inspection and control. Tool schemas improve correctness but are not authorization boundaries.
## From an installed release
The release packages ship `photocraft-cli` alongside the desktop app, so no build is needed:
| Install | CLI |
|---|---|
| Windows (MSI) | `C:\Program Files\PhotoCraft\photocraft-cli.exe` by default (wherever you installed it otherwise), not on `PATH` |
| Linux (deb, rpm) | `/usr/bin/photocraft-cli` |
| macOS | the separate `photocraft-cli-<version>-macos-<arch>.zip` release asset (the `.app` holds only the desktop app) |
```sh
# Windows, default install folder
claude mcp add photocraft -- "C:\Program Files\PhotoCraft\photocraft-cli.exe" mcp --automation-read-root <dir> --automation-write-root <dir>
# Linux, or macOS with the CLI unzipped onto PATH
claude mcp add photocraft -- photocraft-cli mcp --automation-read-root <dir> --automation-write-root <dir>
```
## Security notes
Stdio MCP does not open a network listener. Its client receives only the read and write roots
+5
View File
@@ -11,6 +11,11 @@ PhotoCraft opens native Affinity documents: `.af` files from Affinity 3 and `.af
- placed JPEG and PNG images become embedded smart objects, and pixel layers become pixel layers;
- vector and pixel masks, opacity, visibility, locks, names and blend modes are kept.
Artboards are recognized from both the legacy flag and current Affinity 3 artboard properties.
They keep their names, bounds and editable children when saved as `.pcraft` or PSD; moving an
artboard moves its children together. Nested boards become masked groups, and rotated or curved
boards currently use their bounding rectangle.
The document is 8-bit RGB at the Affinity document's resolution. What PhotoCraft can't reproduce is
listed in a warning when the file opens, for example layer effects, adjustment layers and live
filters, brush strokes (drawn as plain strokes), special shapes such as clouds and hearts (drawn as
+4 -3
View File
@@ -17,7 +17,8 @@ Capability details such as sample depth, channel layout, alpha, ICC, EXIF, XMP,
Every route that writes a document to a flat format (Save As, the CLI, MCP `doc_export`, Layers to Files, Layer › Export As) flattens it the same way:
- Formats without transparency (JPEG, Radiance HDR) get the image composited over white, as Export As and Quick Export do; in CMYK, white is no ink.
- Formats that can't embed an ICC profile (GIF, BMP, TGA, QOI, ICO, Netpbm/PFM) get RGB documents in another profile (linear light, Display P3, …) converted to sRGB through the colour engine (perceptual intent), since an untagged file is read as sRGB. OpenEXR and Radiance HDR get linear sRGB instead.
- Formats that can't embed an ICC profile (GIF, BMP, TGA, QOI, ICO, Netpbm/PFM) get RGB documents in another profile (linear light, Display P3, …) converted to sRGB through the colour engine (perceptual intent), since an untagged file is read as sRGB. OpenEXR and Radiance HDR get linear sRGB instead (linear gray for a grayscale OpenEXR), which is how they are tagged when opened.
- TGA, as Photoshop's Targa: an RGB Targa is 24 or 32 bits per pixel. Save As and Save a Copy ask (Targa Options, starting at 32 with an alpha channel, else 24); Export As has a Resolution choice (Auto, 24 or 32 bits/pixel); scripts pass `tgaBits` (`--tga-bits` on the CLI). At 32 bits the document's alpha channel is the file's alpha when it has exactly one (spot channels don't count; with several, none is used), and the colours are written exactly, never premultiplied or cleared where the alpha is 0, so a game texture's mask and its colours both survive. Without a usable alpha channel the layers' transparency is the alpha (opaque without any). 24 bits write no alpha, compositing transparency over white. Without a choice: 32 with an alpha channel or transparency, else 24. A 32-bit Targa opens as an opaque Background with its alpha as "Alpha 1", so it round-trips. Grayscale Targas are 8-bit.
## Implemented decode limits
@@ -27,8 +28,8 @@ Every route that writes a document to a flat format (Save As, the CLI, MCP `doc_
|---|---:|
| Maximum width | 262,144 pixels |
| Maximum height | 262,144 pixels |
| Maximum pixel count | 268,435,456 pixels |
| Maximum decoded allocation | 2 GiB |
| Maximum pixel count | 1,073,741,824 pixels |
| Maximum decoded allocation | 8 GiB on 64-bit targets; 2 GiB on 32-bit targets (including wasm32) |
Format adapters pass compatible allocation limits into PNG, TIFF, WebP, and `image`-based decoders, while other implementations perform explicit checked dimension/buffer validation. Tests cover bomb-like headers, truncation, bit flips, header overwrites, and random data.
+4
View File
@@ -2,6 +2,10 @@
PhotoCraft uses the Rust workspace at the repository root. Install the stable Rust toolchain, clone the repository, and run commands from that root.
On Linux, install the windowing, GL and GTK development packages first. The development guide's
[Prerequisites](https://github.com/storytold/photocraft/blob/main/docs/development.md#prerequisites)
list them for Debian/Ubuntu, Fedora, Arch and openSUSE.
```sh
cargo build --workspace
cargo run --release -p photocraft -- image.psd
+1 -1
View File
@@ -1,6 +1,6 @@
# Roadmap
The live product roadmap, milestone definitions, parity measurements, and current focus are maintained in [`docs/roadmap.md`](https://github.com/storytold/photocraft/blob/main/docs/roadmap.md). Menu coverage is generated into [`docs/parity.md`](https://github.com/storytold/photocraft/blob/main/docs/parity.md) by `cargo xtask parity`.
The live product roadmap, milestone definitions, parity measurements, and current focus are maintained in [`docs/roadmap.md`](https://github.com/storytold/photocraft/blob/main/docs/roadmap.md). Menu coverage is generated into [`docs/parity-checklist.md`](https://github.com/storytold/photocraft/blob/main/docs/parity-checklist.md) by `cargo xtask parity`.
Security hardening is cross-cutting rather than a replacement for those product milestones. The current security sequence is:
+15 -7
View File
@@ -7,10 +7,15 @@ Automation is a privilege boundary because requests can cause filesystem access,
- Desktop control binds to `127.0.0.1` and uses one JSON request/reply per line.
- Headless TCP refuses a successfully bound non-loopback address.
- Every desktop-control and headless-TCP connection must authenticate with a 256-bit bearer token before method dispatch.
- Encoded request lines are limited to 1 MiB on desktop and headless TCP and on the headless
JSON-lines stdio server (`photocraft-cli serve`). MCP over stdio has no request-byte cap: the
MCP SDK reads its own lines, and only MCP tool results are size-checked. Active TCP connections
are limited to 16, and headless/MCP batches to 256 steps.
- Encoded request lines are limited to 1 MiB on desktop and headless TCP, the headless
JSON-lines stdio server (`photocraft-cli serve`), and MCP stdio. The MCP line limit is
enforced before rmcp's line buffer; an oversized MCP line closes that stdio session because
its request ID cannot safely be parsed. Active TCP connections are limited to 16, and
headless/MCP batches to 256 steps.
- Capability-scoped automation file opens read in chunks without reserving from the file's
metadata length. A read rejects data beyond the length observed on the opened file, so growth
after the metadata check cannot expand the read. Large PSB files have no fixed automation file
size ceiling; their materialized bytes and decoded document still require available memory.
- JSON-lines replies and encoded MCP tool results are limited to 8 MiB; retained batch replies
have an aggregate budget and stop later steps when exhausted. The headless stdio JSON-lines
transport enforces the same request/reply ceilings as TCP.
@@ -19,7 +24,9 @@ Automation is a privilege boundary because requests can cause filesystem access,
PNGs are limited to 5 MiB before base64 encoding or file writes. Trusted-local CLI rendering
retains its existing behavior.
- The MCP bridge bounds incoming replies and does not retry an operation after an oversized
reply. Screenshots are decoded under separate dimension, pixel, and allocation ceilings before
reply. Edits are never automatically resent after a transport failure (#1007); the server's
pure-read tools opt into a single retry on a fresh connection, which applies nothing.
Screenshots are decoded under separate dimension, pixel, and allocation ceilings before
downscaling; the 5 MiB PNG limit applies to the returned image.
- MCP normally uses stdio and can optionally bridge to loopback control TCP.
- The bridge and UI request paths use timeouts.
@@ -47,8 +54,9 @@ Automation is a privilege boundary because requests can cause filesystem access,
- no general per-client or per-tool capability model beyond filesystem read/write authority;
- no automated bulk apply of the Preferences dialog; agents can change individual safe keys with
`prefs.set`;
- no explicit JSON-depth policy, aggregate document/session-memory accounting, compositor
scratch-space accounting, or command-duration/cancellation budget;
- no application-specific JSON-depth policy (serde_json's parser has its default finite recursion
limit), aggregate document/session-memory accounting, compositor scratch-space accounting,
or command-duration/cancellation budget;
- one thread per accepted TCP connection;
- no structured security audit event stream;
- desktop screenshot capture/encoding and document import/export have no automation-specific
+1 -1
View File
@@ -14,7 +14,7 @@ Parser safety is broader than “does not crash.” A parser must also bound mem
### Native format
`photocraft-format` bounds manifest, blob, and total decompressed bytes; validates ZIP structure and decompressed size; verifies CRCs and content hashes; rejects unsupported versions; and property-tests random bundles/manifests.
`photocraft-format` bounds manifest, blob, and total decompressed bytes; admits the declared canvas (by default at most 300000 pixels per side, the largest canvas `file.new`, Canvas Size and PSB import create, so whatever saves reopens; `LoadOptions::max_canvas_side` / `max_canvas_pixels` let a caller lower it) before decoding anything for it; validates ZIP structure and decompressed size; verifies CRCs and content hashes; rejects unsupported versions; and property-tests random bundles/manifests.
## Review checklist
File diff suppressed because it is too large. Load diff
+59
View File
@@ -17,6 +17,10 @@
# To remove your names, delete your entry (or set fields empty) in a PR. The next
# contributors.py run, and the next build, drop them.
[people.Skyfuller1303]
display_name = "Skyfuller"
sync_github_name = true
[people.AlanRockefeller]
sync_github_name = true
@@ -48,5 +52,60 @@ real_name = "Willy Foo"
display_name = "Willy Foo"
sync_github_name = false
[people.SilentYeti]
sync_github_name = true
[people.Elvis33LE]
sync_github_name = true
[people.stevanmarjanovic]
sync_github_name = true
[people.Hathor875]
real_name = "Krzysztof Cieślik"
sync_github_name = true
[people.maxm11]
sync_github_name = true
[people.skraus2]
sync_github_name = true
[people.excited-raccoon]
sync_github_name = true
[people.hamada147]
real_name = "Ahmed Moussa"
display_name = "Ahmed Moussa"
sync_github_name = false
[people.alexanderalber]
real_name = "Alexander Alber"
display_name = "Alexander Alber"
sync_github_name = false
[people.Erica4fr]
sync_github_name = true
[people.itsF4LCON]
real_name = "Ran Geerts"
display_name = "Ran Geerts"
sync_github_name = false
[people.vangel76]
sync_github_name = true
[people.FinnNk]
sync_github_name = true
[people.TheTeslak]
sync_github_name = true
[people.timothydaly1]
display_name = "SyntaxError"
[people.axlecoffee]
sync_github_name = true
[people.Losminek]
sync_github_name = true
+9 -10
View File
@@ -13,16 +13,16 @@ Affinity files.
| Affinity | PhotoCraft |
|---|---|
| Pages, Publisher spreads | one artboard per spread, spreads side by side 64 px apart |
| Artboards (`ShpN` with `ABEn`), with name, solid background, any transform | artboards (nested ones as groups with a vector mask) |
| Artboards (legacy `ABEn`, or current `.af` `phrp`/`aprp` properties, including converted curves), with name, solid background, any transform | artboards (nested ones as groups with a vector mask; rotated/curved boards use their bounding rectangle) |
| Layers (`Scop`), groups (`Grup`), pass-through or isolated | groups (pass-through or Normal) |
| Curves (`PCrv`): cubic subpaths, closed flags, live corners (`CnrD`) | shape layers (multi-subpath curves fill even-odd) |
| Rectangles with corner radii (relative or absolute), ellipses, polygons (smooth too), stars, square stars, pies, triangles, trapezoids | shape layers |
| Rectangles with corner radii (relative or absolute), ellipses, polygons (smooth too), stars, square stars, pies, triangles, trapezoids, clouds, hearts, cogs, rounded and elliptical callouts, arrows, double stars, tears, crescents, diamonds and circular segments | shape layers |
| Compound shapes (`Comp`, add and subtract) | one even-odd shape |
| A shape or curve with children clips them | group with the outline as vector mask, the shape at its bottom |
| Vector masks (`AdCh` curves and shapes) | vector masks |
| Pixel masks (`MRst`, attached or as a layer in a group) | layer masks |
| Solid fills: RGBA, HSLA, CMYK, grey, Lab (D50) | shape fill (converted to RGB) |
| Linear, elliptical and radial gradients with Affinity's midpoint bias | gradient fills |
| Linear, elliptical, radial and conical gradients with Affinity's midpoint bias | gradient fills |
| Strokes: weight, scale with object, dash pattern, alignment, caps, joins, miter limit | shape strokes |
| Fill layers (`FRst`) | filled rectangles |
| Artistic and frame text: characters, font family/weight/style, size, tracking, fixed leading, colour, paragraph alignment, first baseline | type layers (rendered with the fonts installed) |
@@ -33,13 +33,12 @@ Affinity files.
Everything else is reported in the import warnings, one line per kind with a count, never
dropped silently: layer effects, adjustment layers and live filters, brush and pressure strokes,
transparency gradients, fill opacity, bitmap fills, master pages, conical gradients, special shapes
(cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner types other than
round, stars with rounded points, several fills or strokes on one object (one of each is used),
strokes behind the fill, outlined or scaled text, text fields such as page numbers, frames with
columns or a curved outline, grey/Lab/32-bit pixels, CMYK and Lab colour (converted to RGB without
the document's profile), facing pages and the Average, Negation, Reflect, Glow and Erase blend
modes (as Normal).
transparency gradients, fill opacity, bitmap fills, master pages, unrecognized
parametric shapes (imported as their bounding ellipses), corner types other than round, stars with
rounded points, several fills or strokes on one object (one of each is used), strokes behind the
fill, outlined or scaled text, text fields such as page numbers, frames with columns or a curved
outline, grey/Lab/32-bit pixels, CMYK and Lab colour (converted to RGB without the document's
profile), facing pages and the Average, Negation, Reflect, Glow and Erase blend modes (as Normal).
Opened Affinity documents start without a save path: Save asks for a new copy and never writes
back over the Affinity file. When the native document can't be read at all, `photocraft-io` opens
+1 -1
View File
@@ -44,7 +44,7 @@ pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> O
}
};
let b = s.floats::<4>(box_owner, b"ShpB")?;
crate::shapes::shape(r, shape, b, world).map(|p| (p, false))
crate::shapes::shape(r, shape, b, world)
}
}
}
+7 -1
View File
@@ -431,7 +431,13 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
b"Scop" => Kind::Layer,
b"Grup" => Kind::Group,
b"PCrv" | b"ShpN" | b"Comp" | b"SNEN" | b"SNRR" | b"ShRN" => {
if class == Tag::of(b"ShpN") && s.bool(id, b"ABEn") == Some(true) {
// Current .af boards carry artboard properties (aprp) in phrp; older
// documents use ABEn. Converted curve boards keep those properties too.
// Other property classes also use phrp, so the field alone is not a marker.
if s.bool(id, b"ABEn") == Some(true) || s.obj(id, b"phrp").is_some_and(|p| s.is(p, b"aprp")) {
if class != Tag::of(b"ShpN") {
self.warn("a converted artboard outline (imported at its bounding box)");
}
return Ok(self.artboard(id, world));
}
let Some((local, even_odd)) = crate::geometry::outline(self, id, class, world) else {
+192 -3
View File
@@ -43,7 +43,7 @@ fn polygon(pts: impl IntoIterator<Item = Point>) -> Option<SubPath> {
}
/// Outline of `shape` (a `Shpe` object) in the node box `b` = (x0, y0, x1, y1).
pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) -> Option<Path> {
pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) -> Option<(Path, bool)> {
let [x0, y0, x1, y1] = b;
let (w, h) = (x1 - x0, y1 - y0);
let (cx, cy, rx, ry) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, w / 2.0, h / 2.0);
@@ -131,12 +131,201 @@ pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) ->
let (l, rr) = (num(r, shape, b"PosL").unwrap_or(0.25), num(r, shape, b"PosR").unwrap_or(0.75));
polygon([pt(x0 + l * w, y0), pt(x0 + rr * w, y0), pt(x1, y1), pt(x0, y1)])?
}
b"ShCl" => cloud(cx, cy, rx, ry, sides(r, shape, b"Bubl", 12.0)),
b"ShHt" => heart(b),
b"ShCg" => cog(r, shape, cx, cy, rx, ry),
b"ShCR" => callout_rect(r, shape, b, false),
b"ShCE" => callout_ellipse(r, shape, cx, cy, rx, ry),
b"ShDA" => arrow(r, shape, b),
b"ShDS" => double_star(r, shape, cx, cy, rx, ry),
b"ShTr" => tear(r, shape, b),
b"ShCr" => crescent(cx, cy, rx, ry),
b"ShpD" => polygon([pt(cx, y0), pt(x1, cy), pt(cx, y1), pt(x0, cy)])?,
b"ShSg" => segment(r, shape, cx, cy, rx, ry),
_ => {
r.warn("cloud, heart, cog, callout, arrow, tear and other special shapes (imported as their bounding ellipse)");
r.warn("an unrecognized parametric shape (imported as its bounding ellipse)");
ellipse(cx, cy, rx, ry)
}
};
Some(Path { subpaths: vec![sub] })
let mut path = Path { subpaths: vec![sub] };
if class == Tag::of(b"ShCg") {
let hole = num(r, shape, b"Hole").unwrap_or(0.3).clamp(0.0, 0.9);
if hole > 0.0 {
path.subpaths.push(ellipse(cx, cy, rx * hole, ry * hole));
}
return Some((path, true));
}
Some((path, false))
}
fn cloud(cx: f64, cy: f64, rx: f64, ry: f64, bubbles: usize) -> SubPath {
let n = bubbles.clamp(3, 128) * 4;
let points: Vec<Point> = (0..n)
.map(|i| {
let a = TAU * i as f64 / n as f64 - FRAC_PI_2;
let lobe = (0.5 - 0.5 * (TAU * i as f64 / 4.0).cos()).powi(2);
let radius = 0.78 + 0.22 * lobe;
pt(cx + rx * radius * a.cos(), cy + ry * radius * a.sin())
})
.collect();
let segments = (0..n)
.map(|i| {
let p0 = points[(i + n - 1) % n];
let p1 = points[i];
let p2 = points[(i + 1) % n];
let p3 = points[(i + 2) % n];
[pt(p1.x + (p2.x - p0.x) / 6.0, p1.y + (p2.y - p0.y) / 6.0), pt(p2.x - (p3.x - p1.x) / 6.0, p2.y - (p3.y - p1.y) / 6.0), p2]
})
.collect();
SubPath { start: points[0], segments, closed: true }
}
fn heart([x0, y0, x1, y1]: [f64; 4]) -> SubPath {
let (w, h) = (x1 - x0, y1 - y0);
let p = |x: f64, y: f64| pt(x0 + x * w, y0 + y * h);
let start = p(0.5, 0.92);
let segments = vec![
[p(0.38, 0.85), p(0.04, 0.67), p(0.04, 0.37)],
[p(0.04, 0.02), p(0.39, 0.00), p(0.5, 0.27)],
[p(0.61, 0.00), p(0.96, 0.02), p(0.96, 0.37)],
[p(0.96, 0.67), p(0.62, 0.85), start],
];
SubPath { start, segments, closed: true }
}
fn cog(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
let teeth = sides(r, shape, b"Teth", 12.0);
let tooth = num(r, shape, b"TtSz").unwrap_or(0.3).clamp(0.05, 0.9);
let notch = num(r, shape, b"NtSz").unwrap_or(0.45).clamp(0.05, 0.95);
let tip = 1.0;
let root = (1.0 - 0.2 * tooth - 0.08 * notch).clamp(0.55, 0.95);
let mut pts = Vec::with_capacity(teeth * 4);
for i in 0..teeth {
let base = TAU * i as f64 / teeth as f64 - FRAC_PI_2;
for (offset, radius) in [(-0.5, root), (-0.32, tip), (0.32, tip), (0.5, root)] {
let a = base + offset * TAU / teeth as f64;
pts.push(pt(cx + rx * radius * a.cos(), cy + ry * radius * a.sin()));
}
}
polygon(pts).unwrap_or_else(|| rectangle_sub(cx - rx, cy - ry, cx + rx, cy + ry))
}
fn callout_rect(r: &Reader, shape: ObjId, [x0, y0, x1, y1]: [f64; 4], _ellipse: bool) -> SubPath {
let (w, h) = (x1 - x0, y1 - y0);
let tail_h = num(r, shape, b"TlHg").unwrap_or(0.2).clamp(0.0, 0.8) * h;
let tail_w = num(r, shape, b"TlWd").unwrap_or(0.1).clamp(0.02, 0.8) * w;
let tip_x = x0 + num(r, shape, b"TlRP").unwrap_or(0.5).clamp(0.0, 1.0) * w;
let base_x = x0 + num(r, shape, b"TlEP").unwrap_or(0.4).clamp(0.0, 1.0) * w;
let a = (base_x - tail_w / 2.0).clamp(x0, x1);
let c = (base_x + tail_w / 2.0).clamp(x0, x1);
let body_bottom = y1 - tail_h;
let radius = (w.min(body_bottom - y0) * 0.12).max(0.0);
// The three contours overlap inside the fill; no internal edge is visible in a filled shape.
// Join the tail to the rounded body in one closed outline to avoid a seam in stroked shapes.
let start = pt(x0 + radius, y0);
let segments = vec![
[pt(x1 - radius, y0), pt(x1 - radius, y0), pt(x1 - radius, y0)],
[pt(x1 - (1.0 - KAPPA) * radius, y0), pt(x1, y0 + (1.0 - KAPPA) * radius), pt(x1, y0 + radius)],
[pt(x1, body_bottom - radius), pt(x1, body_bottom - radius), pt(x1, body_bottom - radius)],
[pt(x1, body_bottom), pt(x1, body_bottom), pt(x1 - radius, body_bottom)],
[pt(c + radius * 0.2, body_bottom), pt(tip_x, y1 - tail_h * 0.15), pt(tip_x, y1)],
[pt(tip_x, y1), pt(tip_x, y1), pt(tip_x, y1)],
[pt(tip_x, y1 - tail_h * 0.15), pt(a - radius * 0.2, body_bottom), pt(a, body_bottom)],
[pt(x0 + radius, body_bottom), pt(x0, body_bottom), pt(x0, body_bottom - radius)],
[pt(x0, y0 + radius), pt(x0, y0 + radius), pt(x0, y0 + radius)],
[pt(x0, y0 + (1.0 - KAPPA) * radius), pt(x0 + (1.0 - KAPPA) * radius, y0), start],
];
SubPath { start, segments, closed: true }
}
fn callout_ellipse(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
let tail_h = num(r, shape, b"TlHg").unwrap_or(0.2).clamp(0.0, 0.8);
let pos = num(r, shape, b"TlEP").unwrap_or(0.25).clamp(0.0, 1.0);
let angle = num(r, shape, b"TlAn").unwrap_or(0.0);
let a0 = pos * TAU - angle;
let a1 = a0 + 0.35;
let start = pt(cx + rx * a1.cos(), cy + ry * a1.sin());
let end = pt(cx + rx * a0.cos(), cy + ry * a0.sin());
let tip = pt(cx + rx * (a0 + 0.18).cos() * 1.08, cy + ry * (a0 + 0.18).sin() * (1.0 + tail_h));
// A single ellipse-like outline with a short triangular tail at its lower edge.
let mut segments = Vec::new();
arc(cx, cy, rx, ry, a1, a0 + TAU, &mut segments);
segments.push([end, end, tip]);
segments.push([tip, tip, start]);
SubPath { start, segments, closed: true }
}
fn arrow(r: &Reader, shape: ObjId, [x0, y0, x1, y1]: [f64; 4]) -> SubPath {
let h = y1 - y0;
let thick = num(r, shape, b"Thck").unwrap_or(0.35).clamp(0.05, 0.9) * h;
let shaft = (y0 + y1 - thick) / 2.0;
let lower = shaft + thick;
let head_start = x1 - h * 0.45;
polygon([pt(x0, shaft), pt(head_start, shaft), pt(head_start, y0), pt(x1, (y0 + y1) / 2.0), pt(head_start, y1), pt(head_start, lower), pt(x0, lower)])
.unwrap_or_else(|| rectangle_sub(x0, shaft, x1, lower))
}
fn double_star(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
let n = sides(r, shape, b"Pnts", 6.0).saturating_mul(2).clamp(8, 64);
let inner = num(r, shape, b"IRad").unwrap_or(0.6).clamp(0.05, 0.95);
let outer = num(r, shape, b"PRad").unwrap_or(0.9).clamp(0.2, 1.0);
polygon((0..2 * n).map(|i| {
let a = -FRAC_PI_2 + PI * i as f64 / n as f64;
let radius = if i % 2 == 0 { outer } else { outer * inner };
pt(cx + rx * radius * a.cos(), cy + ry * radius * a.sin())
}))
.unwrap_or_else(|| rectangle_sub(cx - rx, cy - ry, cx + rx, cy + ry))
}
fn tear(r: &Reader, shape: ObjId, [x0, y0, x1, y1]: [f64; 4]) -> SubPath {
let (w, h) = (x1 - x0, y1 - y0);
let bulge = num(r, shape, b"Ball").unwrap_or(0.25).clamp(0.0, 0.5);
let bend = num(r, shape, b"Bend").unwrap_or(0.0).clamp(-0.5, 0.5);
let top = pt((x0 + x1) / 2.0, y0);
let bottom = pt((x0 + x1) / 2.0 + bend * w * 0.25, y1);
let segments = vec![
[pt(x0 + w * 0.25, y0 + h * 0.42), pt(x0 + w * (0.5 - bulge), y1 - h * 0.03), bottom],
[pt(x1 - w * (0.5 - bulge), y1 - h * 0.03), pt(x1 - w * 0.25, y0 + h * 0.42), top],
];
SubPath { start: top, segments, closed: true }
}
fn crescent(cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
let start = pt(cx, cy - ry);
let mut segments = Vec::new();
arc(cx, cy, rx, ry, -FRAC_PI_2, -3.0 * FRAC_PI_2, &mut segments);
// The inner arc returns from the lower tip to the upper tip, leaving a crescent open to the right.
let ix = cx + rx * 0.72;
let irx = rx * 0.86;
let iry = ry * 0.82;
let from = pt(ix, cy + iry);
segments.push([from, from, from]);
let mut inner = Vec::new();
arc(ix, cy, irx, iry, FRAC_PI_2, -FRAC_PI_2, &mut inner);
segments.extend(inner);
SubPath { start, segments, closed: true }
}
fn segment(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
// Keep hostile but finite angles in a small range before constructing arc controls.
let angle = num(r, shape, b"Angl").unwrap_or(0.0).rem_euclid(TAU);
let p0 = num(r, shape, b"Pos0").unwrap_or(0.25).clamp(0.0, 1.0);
let p1 = num(r, shape, b"Pos1").unwrap_or(0.75).clamp(0.0, 1.0);
let a0 = angle + (p0 - 0.5) * TAU;
let mut a1 = angle + (p1 - 0.5) * TAU;
while a1 < a0 {
a1 += TAU;
}
let mut segments = Vec::new();
arc(cx, cy, rx, ry, a0, a1.min(a0 + TAU), &mut segments);
let start = pt(cx + rx * a0.cos(), cy + ry * a0.sin());
let end = pt(cx + rx * a1.cos(), cy + ry * a1.sin());
segments.push([end, end, start]);
SubPath { start, segments, closed: true }
}
fn rectangle_sub(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath {
rectangle(x0, y0, x1, y1)
}
pub(crate) fn rectangle(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath {
+143
View File
@@ -0,0 +1,143 @@
//! Full filter timing, including tile reads, filtering, writeback and pruning.
//! RAYON_NUM_THREADS=16 cargo run --release -p photocraft-algo --example bench_algorithms -- extrude 6000 4000 u8 3 output.bin
//! Optional final argument after output.bin: rgb (default), gray, cmyk or lab.
//! Run the same example at the base commit and the PR commit, then compare output.bin with cmp.
use photocraft_algo::{FilterParams, apply_in};
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
use std::io::Write;
use std::time::Instant;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().skip(1).collect();
let case = args.first().map(String::as_str).unwrap_or("extrude");
let parse = |i: usize, fallback: i32| -> Result<i32, Box<dyn std::error::Error>> {
Ok(match args.get(i) {
Some(s) => s.parse()?,
None => fallback,
})
};
let (w, h, repeats) = (parse(1, 6000)?, parse(2, 4000)?, parse(4, 3)?);
if !(1..=10000).contains(&w) || !(1..=10000).contains(&h) || !(1..=9).contains(&repeats) {
return Err("dimensions must be 1..10000, repeats 1..9".into());
}
let depth = match args.get(3).map(String::as_str).unwrap_or("u8") {
"u8" => SampleType::U8,
"u16" => SampleType::U16,
"f32" => SampleType::F32,
_ => return Err("depth must be u8, u16 or f32".into()),
};
let extrude = |size, depth| FilterParams::Extrude {
kind: photocraft_algo::ExtrudeType::Blocks,
size,
depth,
level_based: false,
solid_front: false,
mask_incomplete: false,
seed: 17,
};
let params = match case {
"extrude" => extrude(30.0, 30.0),
"extrude-dense" => extrude(8.0, 128.0),
"extrude-small" => extrude(8.0, 64.0),
"wind" => FilterParams::Wind { method: photocraft_algo::WindMethod::Wind, from_right: false, seed: 17 },
"blast" => FilterParams::Wind { method: photocraft_algo::WindMethod::Blast, from_right: false, seed: 17 },
"blast-right" => FilterParams::Wind { method: photocraft_algo::WindMethod::Blast, from_right: true, seed: 17 },
"spin" => FilterParams::SpinBlur {
pins: vec![photocraft_algo::SpinPin { radius_x: 1.0, radius_y: 1.0, blur_angle: 30.0, angle: 17.0, ..Default::default() }],
},
"spin-default" => FilterParams::SpinBlur { pins: vec![Default::default()] },
"lens" | "lens-ca" | "trap" | "trap-wide" | "trap-default" => FilterParams::Invert,
_ => return Err("unknown case".into()),
};
let mode = match args.get(6).map(String::as_str).unwrap_or("rgb") {
"rgb" => ColorMode::Rgb,
"gray" => ColorMode::Grayscale,
"cmyk" => ColorMode::Cmyk,
"lab" => ColorMode::Lab,
_ => return Err("mode must be rgb, gray, cmyk or lab".into()),
};
if case.starts_with("trap") && mode != ColorMode::Cmyk {
return Err("Trap needs CMYK samples".into());
}
let format = PixelFormat::new(mode, depth, true);
let n = format.channels();
let bounds = Rect::new(-17, -29, w - 17, h - 29);
let mut source = Surface::new(format);
for tile in bounds.tiles() {
let r = tile.rect().intersect(&bounds);
let mut pixels = Vec::with_capacity(r.width() as usize * r.height() as usize * n);
for y in r.y0..r.y1 {
for x in r.x0..r.x1 {
let seed = (x as u32).wrapping_mul(0x9e37_79b9) ^ (y as u32).wrapping_mul(0x85eb_ca6b);
for c in 0..n {
let v = seed.rotate_left(c as u32 * 7).wrapping_add(c as u32 * 71) % 65536;
pixels.push(if c + 1 == n && seed.is_multiple_of(5) { 0.0 } else { v as f32 / 65535.0 });
}
}
}
source.write_region(r, &pixels);
}
let run_filter = |area: Rect| match case {
"lens" | "lens-ca" => photocraft_algo::lens::correct(
&source,
area,
&photocraft_algo::lens::LensCorrection {
distortion: 12.0,
angle: 2.5,
vignette_amount: 20.0,
red_cyan: if case == "lens-ca" { 12.0 } else { 0.0 },
blue_yellow: if case == "lens-ca" { -8.0 } else { 0.0 },
..Default::default()
},
),
"trap" | "trap-wide" | "trap-default" => {
let mut data = source.read_region(area);
photocraft_algo::trap::trap(
&mut data,
area.width() as usize,
area.height() as usize,
n,
if case == "trap-wide" {
50
} else if case == "trap-default" {
1
} else {
10
},
);
let mut result = source.clone();
result.write_region(area, &data);
result.prune();
result
}
_ => apply_in(&source, &params, area, bounds, None, bounds),
};
let warm = Rect::new(bounds.x0, bounds.y0, bounds.x0 + w.min(128), bounds.y0 + h.min(128));
drop(run_filter(warm));
let mut times = Vec::new();
for run in 0..repeats {
let start = Instant::now();
let result = run_filter(bounds);
let seconds = start.elapsed().as_secs_f64();
println!("{case} {w}x{h} {depth:?} {mode:?} run={} seconds={seconds:.6}", run + 1);
times.push(seconds);
if run + 1 == repeats
&& let Some(path) = args.get(5)
{
let mut file = std::io::BufWriter::new(std::fs::File::create(path)?);
for tile in bounds.tiles() {
for sample in result.read_region(tile.rect().intersect(&bounds)) {
file.write_all(&sample.to_bits().to_le_bytes())?;
}
}
file.flush()?;
}
}
times.sort_by(f64::total_cmp);
if let Some(median) = times.get(times.len() / 2) {
println!("MEDIAN {case} {w}x{h} {depth:?} {mode:?} seconds={median:.6}");
}
Ok(())
}
+67
View File
@@ -0,0 +1,67 @@
//! End-to-end Iris Blur timings; fixture construction and output drop are untimed.
//! `cargo run --release -p photocraft-algo --example bench_iris -- 6000 4000 3`
//! An optional fourth argument models the UI's proxy factor (e.g. 1500 1000 5 4).
use photocraft_algo::{FilterParams, IrisPin, apply_in};
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
fn main() {
let args: Vec<String> = std::env::args().collect();
let number = |i: usize, fallback| args.get(i).and_then(|s| s.parse::<i32>().ok()).unwrap_or(fallback);
let (w, h, reps) = (number(1, 6000).clamp(1, 6000), number(2, 4000).clamp(1, 6000), number(3, 3).clamp(1, 20));
let proxy_factor = number(4, 1).clamp(1, 8) as f32;
let bounds = Rect::new(0, 0, w, h);
for (sample, name) in [(SampleType::U8, "U8"), (SampleType::U16, "U16"), (SampleType::F32, "F32")] {
let mut source = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
// Write rows to avoid a second full-image fixture allocation.
for y in 0..h {
let row: Vec<f32> = (0..w)
.flat_map(|x| {
let a = if (x + y) % 31 == 0 { 0.0 } else { 0.7 + (x % 7) as f32 / 30.0 };
let hdr = if sample == SampleType::F32 { 3.0 } else { 1.0 };
[hdr * (x % 256) as f32 / 255.0, ((x * 3 + y) % 251) as f32 / 250.0, ((x ^ y) % 256) as f32 / 255.0, a]
})
.collect();
source.write_region(Rect::new(0, y, w, y + 1), &row);
}
let mut cases = vec![("medium", vec![IrisPin { blur: 80.0, angle: 27.0, ..IrisPin::default() }])];
if sample == SampleType::U8 {
cases.extend([
("small", vec![IrisPin::default()]),
("large", vec![IrisPin { blur: 300.0, ..IrisPin::default() }]),
(
"multiple",
vec![
IrisPin { x: 0.3, blur: 80.0, roundness: 65.0, ..IrisPin::default() },
IrisPin { x: 0.8, angle: 73.0, blur: 40.0, ..IrisPin::default() },
],
),
("focused", vec![IrisPin { radius_x: 5.0, radius_y: 5.0, blur: 80.0, ..IrisPin::default() }]),
("blurred", vec![IrisPin { x: -5.0, blur: 80.0, ..IrisPin::default() }]),
]);
}
for (label, mut pins) in cases {
// Top-level one-pin blur scales in preview_document_with. Its nested
// JSON pin list retains supplied amounts; model that existing path.
if pins.len() == 1 {
for pin in &mut pins {
pin.blur /= proxy_factor;
}
}
let p = FilterParams::IrisBlur { pins };
let warm = apply_in(&source, &p, bounds, bounds, None, bounds);
std::hint::black_box(&warm);
drop(warm);
let mut times = Vec::new();
for _ in 0..reps {
let start = std::time::Instant::now();
let output = apply_in(&source, &p, bounds, bounds, None, bounds);
times.push(start.elapsed().as_secs_f64() * 1000.0);
std::hint::black_box(&output);
drop(output);
}
println!("{w}x{h} {name} {label}: {times:?} ms");
}
}
}
+89
View File
@@ -0,0 +1,89 @@
//! Full filter timing, including tile reads, filtering, writeback and pruning.
//! RAYON_NUM_THREADS=16 cargo run --release -p photocraft-algo --example bench_pixelate -- facet 6000 4000 u8 3 output.bin
//! Optional final argument after output.bin: rgb (default), gray, cmyk or lab.
//! Run the same example at the base commit and the PR commit, then compare output.bin with cmp.
use photocraft_algo::{FilterParams, apply_in};
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
use std::io::Write;
use std::time::Instant;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().skip(1).collect();
let case = args.first().map(String::as_str).unwrap_or("facet");
let parse = |i: usize, fallback: i32| -> Result<i32, Box<dyn std::error::Error>> {
Ok(match args.get(i) {
Some(s) => s.parse()?,
None => fallback,
})
};
let (w, h, repeats) = (parse(1, 6000)?, parse(2, 4000)?, parse(4, 3)?);
if !(1..=10000).contains(&w) || !(1..=10000).contains(&h) || !(1..=9).contains(&repeats) {
return Err("dimensions must be 1..10000, repeats 1..9".into());
}
let depth = match args.get(3).map(String::as_str).unwrap_or("u8") {
"u8" => SampleType::U8,
"u16" => SampleType::U16,
"f32" => SampleType::F32,
_ => return Err("depth must be u8, u16 or f32".into()),
};
let params = match case {
"facet" => FilterParams::Facet,
"halftone" => FilterParams::ColorHalftone { max_radius: 8.0, angles: [108.0, 162.0, 90.0, 45.0] },
"halftone-small" => FilterParams::ColorHalftone { max_radius: 2.0, angles: [108.0, 162.0, 90.0, 45.0] },
"halftone-large" => FilterParams::ColorHalftone { max_radius: 64.0, angles: [108.0, 162.0, 90.0, 45.0] },
_ => return Err("case must be facet, halftone, halftone-small or halftone-large".into()),
};
let mode = match args.get(6).map(String::as_str).unwrap_or("rgb") {
"rgb" => ColorMode::Rgb,
"gray" => ColorMode::Grayscale,
"cmyk" => ColorMode::Cmyk,
"lab" => ColorMode::Lab,
_ => return Err("mode must be rgb, gray, cmyk or lab".into()),
};
let format = PixelFormat::new(mode, depth, true);
let n = format.channels();
let bounds = Rect::new(-17, -29, w - 17, h - 29);
let mut source = Surface::new(format);
for tile in bounds.tiles() {
let r = tile.rect().intersect(&bounds);
let mut pixels = Vec::with_capacity(r.width() as usize * r.height() as usize * n);
for y in r.y0..r.y1 {
for x in r.x0..r.x1 {
let seed = (x as u32).wrapping_mul(0x9e37_79b9) ^ (y as u32).wrapping_mul(0x85eb_ca6b);
for c in 0..n {
let v = seed.rotate_left(c as u32 * 7).wrapping_add(c as u32 * 71) % 65536;
pixels.push(if c + 1 == n && seed.is_multiple_of(5) { 0.0 } else { v as f32 / 65535.0 });
}
}
}
source.write_region(r, &pixels);
}
let warm = Rect::new(bounds.x0, bounds.y0, bounds.x0 + w.min(128), bounds.y0 + h.min(128));
drop(apply_in(&source, &params, warm, bounds, None, bounds));
let mut times = Vec::new();
for run in 0..repeats {
let start = Instant::now();
let result = apply_in(&source, &params, bounds, bounds, None, bounds);
let seconds = start.elapsed().as_secs_f64();
println!("{case} {w}x{h} {depth:?} {mode:?} run={} seconds={seconds:.6}", run + 1);
times.push(seconds);
if run + 1 == repeats
&& let Some(path) = args.get(5)
{
let mut file = std::io::BufWriter::new(std::fs::File::create(path)?);
for tile in bounds.tiles() {
for sample in result.read_region(tile.rect().intersect(&bounds)) {
file.write_all(&sample.to_bits().to_le_bytes())?;
}
}
file.flush()?;
}
}
times.sort_by(f64::total_cmp);
if let Some(median) = times.get(times.len() / 2) {
println!("MEDIAN {case} {w}x{h} {depth:?} {mode:?} seconds={median:.6}");
}
Ok(())
}
+116
View File
@@ -0,0 +1,116 @@
//! Paired, end-to-end Radial Blur benchmark against the current upstream sampler.
//! cargo run --release -j 12 -p photocraft-algo --example bench_radial
//! Defaults: 6000x4000 RGBA8, Good, amount 100, 12 Rayon workers, three runs.
//! Optional positional arguments: width height amount repeats.
#[cfg(not(target_arch = "wasm32"))]
fn main() -> Result<(), Box<dyn std::error::Error>> {
use photocraft_algo::{Ctx, FilterParams, Image, RadialMethod, RadialQuality, TILE, apply_in, kernel};
use photocraft_color::PixelFormat;
use photocraft_geom::Rect;
use photocraft_raster::Surface;
use rayon::prelude::*;
use std::time::Instant;
// Match apply_tiled_with's current upstream pipeline for this benchmark's
// full-canvas, unselected global filter. kernel retains the upstream sampler.
// Both paths read one normalized source, batch the same 256px tiles within
// the same 256MiB result budget, write the same surface depth, and prune.
fn upstream(source: &Surface, params: &FilterParams, rect: Rect) -> Surface {
let mut output = source.clone();
let image = Image::read(source, rect);
let format = source.format();
let ctx = Ctx { bounds: rect, mode: format.mode, alpha: format.alpha };
let tiles: Vec<Rect> = rect.tiles().map(|tile| tile.rect().intersect(&rect)).collect();
let per_tile = TILE as usize * TILE as usize * format.channels() * size_of::<f32>();
let group = ((256 << 20) / per_tile).max(rayon::current_num_threads());
for chunk in tiles.chunks(group) {
let results: Vec<_> = chunk.par_iter().map(|tile| (*tile, kernel(params, &image, *tile, &ctx))).collect();
for (tile, samples) in results {
output.write_region(tile, &samples);
}
}
output.prune();
output
}
let args: Vec<_> = std::env::args().skip(1).collect();
let parse = |i: usize, default: i32| -> Result<i32, Box<dyn std::error::Error>> {
Ok(match args.get(i) {
Some(value) => value.parse()?,
None => default,
})
};
let width = parse(0, 6000)?;
let height = parse(1, 4000)?;
let amount = parse(2, 100)?;
let repeats = parse(3, 3)?;
if !(1..=10000).contains(&width) || !(1..=10000).contains(&height) || !(0..=100).contains(&amount) || !(1..=7).contains(&repeats) {
return Err("expected dimensions 1..10000, amount 0..100, repeats 1..7".into());
}
let pool = rayon::ThreadPoolBuilder::new().num_threads(12).build()?;
let rect = Rect::new(0, 0, width, height);
let mut source = Surface::new(PixelFormat::RGBA8);
for tile in rect.tiles() {
let area = tile.rect().intersect(&rect);
let mut values = Vec::new();
values.try_reserve_exact(area.width() as usize * area.height() as usize * 4)?;
for y in area.y0..area.y1 {
for x in area.x0..area.x1 {
let seed = (x as u32).wrapping_mul(0x9e37_79b9) ^ (y as u32).wrapping_mul(0x85eb_ca6b);
for channel in 0..4 {
let level = seed.rotate_left(channel * 7).wrapping_add(channel * 71) % 256;
values.push(if channel == 3 && seed.is_multiple_of(5) { 0.0 } else { level as f32 / 255.0 });
}
}
}
source.write_region(area, &values);
}
pool.install(|| -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Small untimed warmup initializes worker/code paths without doubling
// the cost of each 24MP measurement. Full-size runs include page faults.
let warm = Rect::new(0, 0, width.min(128), height.min(128));
for method in [RadialMethod::Spin, RadialMethod::Zoom] {
let params = FilterParams::RadialBlur { amount: amount as f32, method, quality: RadialQuality::Good, center_x: 0.5, center_y: 0.5 };
upstream(&source, &params, warm);
apply_in(&source, &params, warm, warm, None, warm);
let (mut before, mut after) = (Vec::new(), Vec::new());
for run in 0..repeats {
let execute = |original: bool| {
let start = Instant::now();
let output = if original { upstream(&source, &params, rect) } else { apply_in(&source, &params, rect, rect, None, rect) };
(output, start.elapsed().as_secs_f64())
};
let ((original, old_time), (optimized, new_time)) = if run % 2 == 0 {
let first = execute(true);
(first, execute(false))
} else {
let first = execute(false);
(execute(true), first)
};
// Exact comparison after timing, including alpha and native U8
// writeback; benchmark errors never silently publish a speedup.
for tile in rect.tiles() {
let area = tile.rect().intersect(&rect);
if original.read_region(area) != optimized.read_region(area) {
return Err(format!("output mismatch for {method:?} at {area:?}").into());
}
}
before.push(old_time);
after.push(new_time);
println!("{method:?} {width}x{height} Good amount={amount} run={}: upstream={old_time:.6}s optimized={new_time:.6}s exact=true", run + 1);
}
before.sort_by(f64::total_cmp);
after.sort_by(f64::total_cmp);
let i = before.len() / 2;
let old = before.get(i).copied().ok_or("missing upstream timing")?;
let new = after.get(i).copied().ok_or("missing optimized timing")?;
println!("MEDIAN {method:?}: upstream={old:.6}s optimized={new:.6}s speedup={:.3}x exact=true workers=12 repeats={repeats}", old / new);
}
Ok(())
})
.map_err(|error| -> Box<dyn std::error::Error> { error })
}
#[cfg(target_arch = "wasm32")]
fn main() {}
+1 -1
View File
@@ -63,7 +63,7 @@ fn main() {
for size in [30.0f32, 300.0] {
let x = c + rad - size * 2.0;
let t = Instant::now();
let r = quick::quick_select(&sampler, canvas, &[(x, c - size), (x, c + size)], size, quick::WORK_PX).expect("region");
let r = quick::quick_select(&sampler, canvas, &[(x, c - size), (x, c + size)], size).expect("region");
println!("quick selection stroke (brush {size} px): {:.2?} (region {}x{})", t.elapsed(), r.bbox.width(), r.bbox.height());
}
+54
View File
@@ -0,0 +1,54 @@
//! Complete Tilt-Shift filtering, including tiled reads and writes.
//! Run alone in release: `bench_tilt_shift 6000 4000 5 1`.
//! Fourth argument models the existing preview proxy scale (e.g. 1500 1000 7 4).
use photocraft_algo::{FilterParams, apply_in};
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
fn main() {
let args: Vec<String> = std::env::args().collect();
let number = |i: usize, fallback| args.get(i).and_then(|s| s.parse::<i32>().ok()).unwrap_or(fallback);
let (w, h, reps) = (number(1, 6000).clamp(1, 6000), number(2, 4000).clamp(1, 6000), number(3, 5).clamp(1, 20));
let proxy = number(4, 1).clamp(1, 8) as f32;
let bounds = Rect::new(0, 0, w, h);
for (sample, name) in [(SampleType::U8, "U8"), (SampleType::U16, "U16"), (SampleType::F32, "F32")] {
let mut source = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
for y in 0..h {
let row: Vec<f32> = (0..w)
.flat_map(|x| {
let a = if (x + y) % 31 == 0 { 0.0 } else { 0.7 + (x % 7) as f32 / 30.0 };
let hdr = if sample == SampleType::F32 { 3.0 } else { 1.0 };
[hdr * (x % 256) as f32 / 255.0, ((x * 3 + y) % 251) as f32 / 250.0, ((x ^ y) % 256) as f32 / 255.0, a]
})
.collect();
source.write_region(Rect::new(0, y, w, y + 1), &row);
}
let mut cases = vec![("medium", 80.0, 0.5, 0.5, 27.0, 0.1, 0.15)];
if sample == SampleType::U8 {
cases.extend([
("small", 15.0, 0.5, 0.5, 0.0, 0.1, 0.15),
("large", 300.0, 0.5, 0.5, -71.0, 0.03, 0.4),
("wide_focus", 80.0, 0.5, 0.5, 0.0, 0.4, 0.05),
("sharp_transition", 80.0, 0.2, 0.8, 63.0, 0.05, 0.01),
("focused", 80.0, 0.5, 0.5, 0.0, 1.0, 0.15),
("blurred", 80.0, -5.0, -5.0, 27.0, 0.1, 0.15),
]);
}
for (label, blur, center_x, center_y, angle, focus, transition) in cases {
let params = FilterParams::TiltShift { blur: blur / proxy, center_x, center_y, angle, focus, transition };
for _ in 0..2 {
std::hint::black_box(apply_in(&source, &params, bounds, bounds, None, bounds));
}
let mut times = Vec::new();
for _ in 0..reps {
let start = std::time::Instant::now();
let output = apply_in(&source, &params, bounds, bounds, None, bounds);
times.push(start.elapsed().as_secs_f64() * 1000.0);
std::hint::black_box(&output);
drop(output);
}
println!("{}", serde_json::json!({"width": w, "height": h, "depth": name, "case": label, "proxy": proxy, "ms": times}));
}
}
}
+1
View File
@@ -18,6 +18,7 @@ mod motion_fft;
mod motion_fft_tests;
#[cfg(test)]
mod motion_tests;
pub(crate) mod radial;
/// Normalized Gaussian kernel with standard deviation `sigma` (radius 3σ).
pub(crate) fn gaussian_kernel(sigma: f32) -> Vec<f32> {
+355
View File
@@ -0,0 +1,355 @@
//! Direct Radial Blur, with immutable sampling tables shared by every output tile.
//!
//! Pixel positions and the quality-dependent interval ceilings match the upstream
//! sampler. The hot loop keeps channels together, reads each bilinear tap once,
//! and preserves the upstream alpha arithmetic for every sample.
use photocraft_geom::Rect;
use photocraft_raster::Interrupt;
use crate::image::Image;
use crate::{Ctx, RadialMethod, RadialQuality};
/// Position-independent rotations (Spin) or ray scales (Zoom), prepared once.
pub(crate) struct Plan {
center: (f32, f32),
extent: f32,
method: RadialMethod,
// Packed tables for interval counts 1..=max_intervals, each with n+1 samples.
// Best needs at most 8,394,752 pairs (about 64 MiB), reserved fallibly.
tables: Vec<(f32, f32)>,
max_intervals: usize,
valid: bool,
}
impl Plan {
#[cfg(test)]
pub(crate) fn new(bounds: Rect, amount: f32, method: RadialMethod, center: (f32, f32)) -> Self {
Self::with_quality(bounds, amount, method, RadialQuality::Draft, center, &Interrupt::NONE).unwrap_or(Self {
center: (0.0, 0.0),
extent: 0.0,
method,
tables: Vec::new(),
max_intervals: 64,
valid: false,
})
}
#[cfg(test)]
pub(crate) fn with_quality(
bounds: Rect,
amount: f32,
method: RadialMethod,
quality: RadialQuality,
center: (f32, f32),
ctl: &Interrupt<'_>,
) -> Option<Self> {
Self::prepare(bounds, amount, method, quality, center, None, ctl)
}
pub(crate) fn for_area(
bounds: Rect,
amount: f32,
method: RadialMethod,
quality: RadialQuality,
center: (f32, f32),
area: Rect,
ctl: &Interrupt<'_>,
) -> Option<Self> {
Self::prepare(bounds, amount, method, quality, center, Some(area), ctl)
}
#[allow(clippy::too_many_arguments)]
fn prepare(
bounds: Rect,
amount: f32,
method: RadialMethod,
quality: RadialQuality,
center: (f32, f32),
area: Option<Rect>,
ctl: &Interrupt<'_>,
) -> Option<Self> {
if !amount.is_finite() || !center.0.is_finite() || !center.1.is_finite() || ctl.cancelled() {
return None;
}
let amount = amount.clamp(0.0, 100.0);
let center = (bounds.x0 as f32 + bounds.width() as f32 * center.0, bounds.y0 as f32 + bounds.height() as f32 * center.1);
if !center.0.is_finite() || !center.1.is_finite() {
return None;
}
let extent = match method {
RadialMethod::Spin => amount.to_radians(),
RadialMethod::Zoom => amount / 200.0,
};
// Only prepare interval counts reachable in the requested output. This
// avoids preparing all Best tables (64MiB) for a tiny image/selection.
// Distance from a fixed center is greatest at a rectangle's corners.
let path = area.map_or(f32::INFINITY, |area| {
let mut radius = 0.0f32;
for y in [area.y0, area.y1.saturating_sub(1)] {
for x in [area.x0, area.x1.saturating_sub(1)] {
let dx = x as f32 + 0.5 - center.0;
let dy = y as f32 + 0.5 - center.1;
radius = radius.max((dx * dx + dy * dy).sqrt());
}
}
extent * radius
});
let max_intervals = super::radial_intervals(path, quality);
let count = max_intervals.checked_mul(max_intervals.checked_add(3)?)?.checked_div(2)?;
let mut tables = Vec::new();
tables.try_reserve_exact(count).ok()?;
for n in 1..=max_intervals {
if ctl.cancelled() {
return None;
}
for i in 0..=n {
tables.push(match method {
RadialMethod::Spin => ((i as f32 / n as f32 - 0.5) * extent).sin_cos(),
RadialMethod::Zoom => (0.0, 1.0 - extent * i as f32 / n as f32),
});
}
}
Some(Self { center, extent, method, tables, max_intervals, valid: true })
}
/// `None` on cancellation or invalid image storage or allocation failure. Sampling beyond
/// `src.rect` is transparent, including the individual taps at its edges.
pub(crate) fn filter(&self, src: &Image, out: Rect, ctx: &Ctx, ctl: &Interrupt<'_>) -> Option<Vec<f32>> {
if !self.valid || ctl.cancelled() || src.ch == 0 {
return None;
}
let source = Source::new(src)?;
let len = sample_len(out, src.ch)?;
let mut result = Vec::new();
result.try_reserve_exact(len).ok()?;
result.resize(len, 0.0);
if out.is_empty() {
return Some(result);
}
match src.ch {
1 => self.dispatch_fixed::<1>(&source, out, ctx.alpha, ctl, &mut result),
2 => self.dispatch_fixed::<2>(&source, out, ctx.alpha, ctl, &mut result),
3 => self.dispatch_fixed::<3>(&source, out, ctx.alpha, ctl, &mut result),
4 => self.dispatch_fixed::<4>(&source, out, ctx.alpha, ctl, &mut result),
5 => self.dispatch_fixed::<5>(&source, out, ctx.alpha, ctl, &mut result),
_ => self.dispatch_generic(&source, out, ctx.alpha, ctl, &mut result),
}?;
Some(result)
}
fn dispatch_fixed<const N: usize>(&self, src: &Source<'_>, out: Rect, alpha: bool, ctl: &Interrupt<'_>, dst: &mut [f32]) -> Option<()> {
match (alpha, self.method) {
(true, RadialMethod::Spin) => self.fixed::<N, true, true>(src, out, ctl, dst),
(false, RadialMethod::Spin) => self.fixed::<N, false, true>(src, out, ctl, dst),
(true, RadialMethod::Zoom) => self.fixed::<N, true, false>(src, out, ctl, dst),
(false, RadialMethod::Zoom) => self.fixed::<N, false, false>(src, out, ctl, dst),
}
}
fn fixed<const N: usize, const ALPHA: bool, const SPIN: bool>(&self, src: &Source<'_>, out: Rect, ctl: &Interrupt<'_>, dst: &mut [f32]) -> Option<()> {
let row_len = (out.width() as usize).checked_mul(N)?;
for (row_index, row) in dst.chunks_exact_mut(row_len).enumerate() {
if row_index.is_multiple_of(8) && ctl.cancelled() {
return None;
}
let dy = (i64::from(out.y0) + row_index as i64) as f32 + 0.5 - self.center.1;
for (column, pixel) in row.as_chunks_mut::<N>().0.iter_mut().enumerate() {
let dx = (i64::from(out.x0) + column as i64) as f32 + 0.5 - self.center.0;
let table = self.table(dx, dy)?;
let mut acc = [0.0; N];
for &tap in table {
let (x, y) = self.position::<SPIN>(dx, dy, tap);
sample_fixed::<N, ALPHA>(src, x, y, &mut acc);
}
finish(&mut acc, 1.0 / table.len() as f32, ALPHA);
pixel.copy_from_slice(&acc);
}
}
Some(())
}
fn dispatch_generic(&self, src: &Source<'_>, out: Rect, alpha: bool, ctl: &Interrupt<'_>, dst: &mut [f32]) -> Option<()> {
match (alpha, self.method) {
(true, RadialMethod::Spin) => self.generic::<true, true>(src, out, ctl, dst),
(false, RadialMethod::Spin) => self.generic::<false, true>(src, out, ctl, dst),
(true, RadialMethod::Zoom) => self.generic::<true, false>(src, out, ctl, dst),
(false, RadialMethod::Zoom) => self.generic::<false, false>(src, out, ctl, dst),
}
}
fn generic<const ALPHA: bool, const SPIN: bool>(&self, src: &Source<'_>, out: Rect, ctl: &Interrupt<'_>, dst: &mut [f32]) -> Option<()> {
let n = src.image.ch;
let row_len = (out.width() as usize).checked_mul(n)?;
let mut sample = Vec::new();
sample.try_reserve_exact(n).ok()?;
sample.resize(n, 0.0);
for (row_index, row) in dst.chunks_exact_mut(row_len).enumerate() {
if row_index.is_multiple_of(8) && ctl.cancelled() {
return None;
}
let dy = (i64::from(out.y0) + row_index as i64) as f32 + 0.5 - self.center.1;
for (column, pixel) in row.chunks_exact_mut(n).enumerate() {
let dx = (i64::from(out.x0) + column as i64) as f32 + 0.5 - self.center.0;
let table = self.table(dx, dy)?;
for &tap in table {
let (x, y) = self.position::<SPIN>(dx, dy, tap);
sample_generic::<ALPHA>(src, x, y, pixel, &mut sample);
}
finish(pixel, 1.0 / table.len() as f32, ALPHA);
}
}
Some(())
}
#[inline]
fn table(&self, dx: f32, dy: f32) -> Option<&[(f32, f32)]> {
let radius = (dx * dx + dy * dy).sqrt();
let n = ((self.extent * radius).ceil() as usize).clamp(1, self.max_intervals);
let start = (n - 1).checked_mul(n.checked_add(2)?)?.checked_div(2)?;
self.tables.get(start..start.checked_add(n.checked_add(1)?)?)
}
#[inline]
fn position<const SPIN: bool>(&self, dx: f32, dy: f32, (s, c): (f32, f32)) -> (f32, f32) {
if SPIN { (self.center.0 + dx * c - dy * s, self.center.1 + dx * s + dy * c) } else { (self.center.0 + dx * c, self.center.1 + dy * c) }
}
}
fn sample_len(rect: Rect, channels: usize) -> Option<usize> {
(rect.width() as usize).checked_mul(rect.height() as usize)?.checked_mul(channels)
}
/// Storage dimensions are checked once, before coordinate-derived offset arithmetic.
struct Source<'a> {
image: &'a Image,
width: usize,
}
impl<'a> Source<'a> {
fn new(image: &'a Image) -> Option<Self> {
if image.ch == 0 || sample_len(image.rect, image.ch)? != image.data.len() {
return None;
}
Some(Self { image, width: image.rect.width() as usize })
}
#[inline]
fn pixel(&self, x: i64, y: i64) -> Option<&'a [f32]> {
let b = self.image.rect;
if x < i64::from(b.x0) || x >= i64::from(b.x1) || y < i64::from(b.y0) || y >= i64::from(b.y1) {
return None;
}
// The rectangular storage length was checked by Source::new, and the
// coordinates above are inside that rectangle, so these products fit.
let i = ((y - i64::from(b.y0)) as usize * self.width + (x - i64::from(b.x0)) as usize) * self.image.ch;
self.image.data.get(i..i + self.image.ch)
}
}
#[inline]
fn taps(x: f32, y: f32) -> Option<[(i64, i64, f32); 4]> {
if !x.is_finite() || !y.is_finite() {
return None;
}
let (fx, fy) = (x - 0.5, y - 0.5);
let (x0, y0) = (fx.floor(), fy.floor());
let (ax, ay) = (fx - x0, fy - y0);
// f32 casts saturate, and i64 leaves room for the neighbouring tap even
// when an adversarial center places a sample outside the i32 image domain.
let (x0, y0) = (i64::from(x0 as i32), i64::from(y0 as i32));
Some([(x0, y0, (1.0 - ax) * (1.0 - ay)), (x0 + 1, y0, ax * (1.0 - ay)), (x0, y0 + 1, (1.0 - ax) * ay), (x0 + 1, y0 + 1, ax * ay)])
}
#[inline]
fn sample_fixed<const N: usize, const ALPHA: bool>(src: &Source<'_>, x: f32, y: f32, acc: &mut [f32; N]) {
let Some(taps) = taps(x, y) else { return };
let mut sample = [0.0; N];
for (x, y, weight) in taps {
if weight <= 0.0 {
continue;
}
let Some(pixel) = src.pixel(x, y) else { continue };
let Ok(pixel) = <&[f32; N]>::try_from(pixel) else { continue };
if ALPHA {
let alpha = pixel.last().copied().unwrap_or(0.0);
for (sum, &value) in sample.iter_mut().zip(pixel).take(N.saturating_sub(1)) {
*sum += value * alpha * weight;
}
if let Some(sum) = sample.last_mut() {
*sum += alpha * weight;
}
} else {
for (sum, &value) in sample.iter_mut().zip(pixel) {
*sum += value * weight;
}
}
}
accumulate_sample(acc, &sample, ALPHA);
}
#[inline]
fn sample_generic<const ALPHA: bool>(src: &Source<'_>, x: f32, y: f32, acc: &mut [f32], sample: &mut [f32]) {
let Some(taps) = taps(x, y) else { return };
sample.fill(0.0);
for (x, y, weight) in taps {
if weight <= 0.0 {
continue;
}
let Some(pixel) = src.pixel(x, y) else { continue };
if ALPHA {
let alpha = pixel.last().copied().unwrap_or(0.0);
let colours = sample.len().saturating_sub(1);
for (sum, &value) in sample.iter_mut().zip(pixel).take(colours) {
*sum += value * alpha * weight;
}
if let Some(sum) = sample.last_mut() {
*sum += alpha * weight;
}
} else {
for (sum, &value) in sample.iter_mut().zip(pixel) {
*sum += value * weight;
}
}
}
accumulate_sample(acc, sample, ALPHA);
}
#[inline]
fn accumulate_sample(acc: &mut [f32], sample: &[f32], alpha: bool) {
// Retain Image::sample's unpremultiply followed by average_samples'
// premultiply, including its floating-point rounding and unusual alpha.
let a = sample.last().copied().unwrap_or(0.0);
let colours = sample.len().saturating_sub(1);
for (c, (sum, &value)) in acc.iter_mut().zip(sample).enumerate() {
*sum += if alpha && c < colours {
let straight = if a > 0.0 { value / a } else { value };
straight * a
} else {
value
};
}
}
#[inline]
fn finish(pixel: &mut [f32], reciprocal: f32, alpha: bool) {
for value in pixel.iter_mut() {
*value *= reciprocal;
}
if alpha {
let a = pixel.last().copied().unwrap_or(0.0);
let colours = pixel.len().saturating_sub(1);
for value in pixel.iter_mut().take(colours) {
*value = if a > 1e-7 { *value / a } else { 0.0 };
}
}
}
/// Original implementation, retained only as a quality/performance oracle.
#[cfg(test)]
pub(crate) fn reference(src: &Image, out: Rect, ctx: &Ctx, amount: f32, method: RadialMethod, center: (f32, f32)) -> Vec<f32> {
super::radial(src, out, ctx, amount, method, RadialQuality::Draft, center)
}
#[cfg(test)]
mod tests;
+260
View File
@@ -0,0 +1,260 @@
use super::*;
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_raster::Surface;
fn fixture(format: PixelFormat, rect: Rect, hdr: bool) -> Surface {
let mut surface = Surface::new(format);
for tile in rect.tiles() {
let area = tile.rect().intersect(&rect);
let mut values = Vec::with_capacity(area.width() as usize * area.height() as usize * format.channels());
for y in area.y0..area.y1 {
for x in area.x0..area.x1 {
let seed = (x as u32).wrapping_mul(0x9e37_79b9) ^ (y as u32).wrapping_mul(0x85eb_ca6b);
for channel in 0..format.channels() {
let level = seed.rotate_left(channel as u32 * 7).wrapping_add(channel as u32 * 71) % 256;
let alpha = format.alpha && channel + 1 == format.channels();
let value = if alpha && seed.is_multiple_of(5) { 0.0 } else { level as f32 / 255.0 };
values.push(if hdr && !alpha { value * 4.0 - 0.75 } else { value });
}
}
}
surface.write_region(area, &values);
}
surface
}
fn premultiplied_max_error(mut a: Vec<f32>, mut b: Vec<f32>, channels: usize, alpha: bool) -> f32 {
crate::image::premultiply(&mut a, channels, alpha);
crate::image::premultiply(&mut b, channels, alpha);
a.iter().zip(b).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max)
}
#[test]
fn direct_matches_legacy_depth_models_edges_centers_and_hdr() {
let source_rect = Rect::new(-17, -13, 45, 39);
let bounds = Rect::new(-41, -32, 51, 48);
let out = Rect::new(-22, -19, 47, 43);
let mut worst = 0.0f32;
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
for (mode, alpha) in [
(ColorMode::Grayscale, false),
(ColorMode::Grayscale, true),
(ColorMode::Rgb, false),
(ColorMode::Rgb, true),
(ColorMode::Cmyk, false),
(ColorMode::Cmyk, true),
(ColorMode::Lab, true),
] {
let format = PixelFormat::new(mode, sample, alpha);
let src = Image::read(&fixture(format, source_rect, sample == SampleType::F32), source_rect);
let ctx = Ctx { bounds, mode, alpha };
for method in [RadialMethod::Spin, RadialMethod::Zoom] {
for (amount, center) in [(0.0, (0.5, 0.5)), (1.0, (0.5, 0.5)), (20.0, (0.53, -0.17)), (100.0, (0.0, 1.0))] {
let direct = Plan::new(bounds, amount, method, center).filter(&src, out, &ctx, &Interrupt::NONE).expect("valid input");
let legacy = reference(&src, out, &ctx, amount, method, center);
assert_eq!(direct, legacy, "preserve finite upstream samples exactly");
let error = premultiplied_max_error(direct, legacy, src.ch, alpha);
worst = worst.max(error);
assert!(error <= 2e-5, "{format:?}, {method:?}, amount {amount}, center {center:?}: {error}");
}
}
}
}
eprintln!("direct vs legacy: maximum premultiplied float error {worst}");
}
#[test]
fn direct_generic_channels_and_unusual_float_alpha_match_legacy() {
let rect = Rect::new(-4, -3, 21, 16);
for channels in [1, 2, 4, 5, 7, 12] {
let mut src = Image::new(rect, channels);
for (index, pixel) in src.data.chunks_exact_mut(channels).enumerate() {
for (channel, value) in pixel.iter_mut().enumerate() {
*value = ((index * 13 + channel * 3) % 37) as f32 / 9.0 - 0.75;
}
*pixel.last_mut().expect("nonempty pixel") = [-0.7, 0.0, 1e-9, 0.4, 1.7, f32::NAN, f32::INFINITY, f32::NEG_INFINITY][index % 8];
}
for alpha in [false, true] {
let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha };
for method in [RadialMethod::Spin, RadialMethod::Zoom] {
let fast = Plan::new(rect, 53.0, method, (0.51, 0.47)).filter(&src, rect, &ctx, &Interrupt::NONE).expect("valid input");
let slow = reference(&src, rect, &ctx, 53.0, method, (0.51, 0.47));
for (a, b) in fast.iter().zip(&slow) {
if b.is_nan() {
assert!(a.is_nan(), "match legacy NaN classification");
} else if b.is_infinite() {
assert_eq!(a, b, "match legacy infinity sign");
} else {
assert_eq!(a, b, "finite upstream output is preserved exactly");
}
}
let error = fast.iter().zip(&slow).map(|(a, b)| (a - b).abs() / b.abs().max(1.0)).fold(0.0f32, f32::max);
assert!(error < 2e-5, "channels {channels}, alpha {alpha}, {method:?}: relative error {error}");
}
}
}
}
#[test]
fn direct_invalid_storage_extreme_coordinates_and_cancellation_are_bounded() {
let rect = Rect::new(0, 0, 23, 19);
let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };
let plan = Plan::new(rect, 20.0, RadialMethod::Spin, (0.5, 0.5));
let mut src = Image::new(rect, 4);
let cancel = || true;
assert!(plan.filter(&src, rect, &ctx, &Interrupt::cancel_only(&cancel)).is_none());
src.data.pop();
assert!(plan.filter(&src, rect, &ctx, &Interrupt::NONE).is_none());
src.ch = 0;
assert!(plan.filter(&src, rect, &ctx, &Interrupt::NONE).is_none());
let src = Image::new(Rect::EMPTY, 4);
assert!(plan.filter(&src, Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX), &ctx, &Interrupt::NONE).is_none());
assert!(Plan::new(rect, f32::NAN, RadialMethod::Spin, (0.5, 0.5)).filter(&src, rect, &ctx, &Interrupt::NONE).is_none());
assert!(Plan::new(rect, 20.0, RadialMethod::Spin, (f32::INFINITY, 0.5)).filter(&src, rect, &ctx, &Interrupt::NONE).is_none());
assert_eq!(plan.filter(&src, Rect::EMPTY, &ctx, &Interrupt::NONE), Some(Vec::new()));
let edge = Rect::new(i32::MAX - 2, i32::MAX - 2, i32::MAX, i32::MAX);
let src = Image::new(edge, 4);
assert!(Plan::new(edge, 100.0, RadialMethod::Spin, (-100.0, 100.0)).filter(&src, edge, &ctx, &Interrupt::NONE).is_some());
}
#[test]
fn direct_observes_cancellation_inside_an_output_tile() {
use std::sync::atomic::{AtomicUsize, Ordering};
let rect = Rect::new(0, 0, 16, 24);
let src = Image::new(rect, 4);
let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };
let calls = AtomicUsize::new(0);
let cancel = || calls.fetch_add(1, Ordering::Relaxed) >= 2;
assert!(Plan::new(rect, 100.0, RadialMethod::Spin, (0.5, 0.5)).filter(&src, rect, &ctx, &Interrupt::cancel_only(&cancel)).is_none());
assert_eq!(calls.load(Ordering::Relaxed), 3, "entry, first row, eighth row");
}
#[test]
fn direct_apply_preserves_selection_and_canvas_edges_at_all_depths() {
let rect = Rect::new(0, 0, 37, 29);
let bounds = Rect::new(3, 5, 31, 23);
let selection = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false), &[0.37]);
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
let format = PixelFormat::new(ColorMode::Rgb, sample, true);
let src = fixture(format, rect, sample == SampleType::F32);
for method in [RadialMethod::Spin, RadialMethod::Zoom] {
let params = crate::FilterParams::RadialBlur { quality: crate::RadialQuality::Draft, amount: 100.0, method, center_x: 0.2, center_y: 0.8 };
let fast = crate::apply_in_with(&src, &params, rect, bounds, Some(&selection), rect, &Interrupt::NONE).expect("direct input");
let legacy = crate::apply_radial_reference(&src, &params, rect, bounds, Some(&selection), rect, &Interrupt::NONE).expect("valid input");
assert_eq!(fast.read_region(rect), legacy.read_region(rect));
let error = premultiplied_max_error(fast.read_region(rect), legacy.read_region(rect), 4, true);
let tolerance = match sample {
SampleType::U8 => 1.0 / 255.0,
SampleType::U16 => 1.0 / 65535.0,
_ => 0.0,
} + 2e-5;
assert!(error <= tolerance, "{sample:?}, {method:?}: {error}");
}
}
}
#[test]
fn direct_preserves_upstream_quality_ceilings_and_discrete_samples() {
let bounds = Rect::new(0, 0, 1000, 1000);
let out = Rect::new(999, 500, 1000, 501);
let mut source = Image::new(bounds, 1);
for (i, v) in source.data.iter_mut().enumerate() {
*v = ((i * 37 + i / 1000 * 13) % 101) as f32 / 100.0;
}
let ctx = Ctx { bounds, mode: ColorMode::Grayscale, alpha: false };
for (quality, limit) in [(crate::RadialQuality::Draft, 64), (crate::RadialQuality::Good, 256), (crate::RadialQuality::Best, 4096)] {
for method in [RadialMethod::Spin, RadialMethod::Zoom] {
let plan = Plan::with_quality(bounds, 100.0, method, quality, (0.5, 0.5), &Interrupt::NONE).expect("quality plan");
assert_eq!(plan.max_intervals, limit);
assert_eq!(plan.table(10000.0, 0.0).expect("capped table").len(), limit + 1);
let actual = plan.filter(&source, out, &ctx, &Interrupt::NONE).expect("direct output");
let expected = super::super::average_samples(&source, out, &ctx, |x, y, samples| {
let (dx, dy) = (x - 500.0, y - 500.0);
let extent = match method {
RadialMethod::Spin => 100.0f32.to_radians(),
RadialMethod::Zoom => 0.5,
};
let intervals = (extent * (dx * dx + dy * dy).sqrt()).ceil().clamp(1.0, limit as f32) as usize;
for i in 0..=intervals {
samples.push(match method {
RadialMethod::Spin => {
let (sin, cos) = ((i as f32 / intervals as f32 - 0.5) * extent).sin_cos();
(500.0 + dx * cos - dy * sin, 500.0 + dx * sin + dy * cos)
}
RadialMethod::Zoom => {
let k = 1.0 - extent * i as f32 / intervals as f32;
(500.0 + dx * k, 500.0 + dy * k)
}
});
}
});
assert_eq!(actual, expected, "{quality:?}, {method:?}: preserve discrete positions");
}
}
}
#[test]
fn quality_plan_cancellation_stops_table_preparation() {
use std::sync::atomic::{AtomicUsize, Ordering};
let calls = AtomicUsize::new(0);
let cancel = || calls.fetch_add(1, Ordering::Relaxed) >= 2;
assert!(
Plan::with_quality(Rect::new(0, 0, 100, 100), 100.0, RadialMethod::Spin, crate::RadialQuality::Best, (0.5, 0.5), &Interrupt::cancel_only(&cancel))
.is_none()
);
assert_eq!(calls.load(Ordering::Relaxed), 3);
}
#[test]
fn all_qualities_preserve_samples_at_large_radii_across_models_and_depths() {
let bounds = Rect::new(0, 0, 6000, 4000);
let source_rect = Rect::new(5970, 1980, 6000, 2020);
let out = Rect::new(5990, 2000, 5992, 2002);
for quality in [crate::RadialQuality::Draft, crate::RadialQuality::Good, crate::RadialQuality::Best] {
for method in [RadialMethod::Spin, RadialMethod::Zoom] {
let plan = Plan::with_quality(bounds, 100.0, method, quality, (0.5, 0.5), &Interrupt::NONE).unwrap();
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] {
for alpha in [false, true] {
let format = PixelFormat::new(mode, sample, alpha);
let src = Image::read(&fixture(format, source_rect, sample == SampleType::F32), source_rect);
let ctx = Ctx { bounds, mode, alpha };
let actual = plan.filter(&src, out, &ctx, &Interrupt::NONE).unwrap();
let expected = super::super::radial(&src, out, &ctx, 100.0, method, quality, (0.5, 0.5));
assert_eq!(actual, expected, "{quality:?} {method:?} {format:?}");
}
}
}
}
}
}
#[test]
fn unavailable_optional_plan_uses_upstream_instead_of_cancellation() {
let rect = Rect::new(0, 0, 7, 5);
let source = fixture(PixelFormat::RGBA8, rect, false);
// Nonfinite centers decline preparation. The unchanged upstream sampler is
// still used; a declined optimization must not look like engine cancellation.
let params =
crate::FilterParams::RadialBlur { amount: 20.0, method: RadialMethod::Spin, quality: crate::RadialQuality::Good, center_x: f32::NAN, center_y: 0.5 };
let actual = crate::apply_in_with(&source, &params, rect, rect, None, rect, &Interrupt::NONE).unwrap();
let expected = crate::apply_radial_reference(&source, &params, rect, rect, None, rect, &Interrupt::NONE).unwrap();
assert_eq!(actual.read_region(rect), expected.read_region(rect));
}
#[test]
fn small_best_jobs_prepare_only_reachable_tables() {
let rect = Rect::new(-30, -20, 30, 20);
let format = PixelFormat::RGBA32F;
let source = fixture(format, rect, true);
let ctx = Ctx { bounds: rect, mode: format.mode, alpha: true };
let image = Image::read(&source, rect);
for method in [RadialMethod::Spin, RadialMethod::Zoom] {
let plan = Plan::for_area(rect, 100.0, method, crate::RadialQuality::Best, (0.5, 0.5), rect, &Interrupt::NONE).unwrap();
assert!(plan.max_intervals < 64, "small Best image does not need 4096 intervals");
assert!(plan.tables.len() < 2200);
let actual = plan.filter(&image, rect, &ctx, &Interrupt::NONE).unwrap();
let expected = super::super::radial(&image, rect, &ctx, 100.0, method, crate::RadialQuality::Best, (0.5, 0.5));
assert_eq!(actual, expected);
}
}
+236
View File
@@ -0,0 +1,236 @@
//! Filter › Other › Color to Alpha: removes a known colour from the pixels, turning it into
//! transparency while keeping what was mixed with it.
//!
//! A pixel `P` that is a semi-transparent colour `Q` composited over a background colour `C`
//! obeys `P = a·Q + (1 − a)·C`. Knowing only `P` and `C`, the most transparent solution (the
//! smallest `a` that keeps `Q` inside the 0–1 range) is, per channel `i`,
//!
//! * `a_i = (P_i − C_i) / (1 − C_i)` where `P_i > C_i` (`Q_i` would otherwise overshoot 1),
//! * `a_i = (C_i − P_i) / C_i` where `P_i < C_i` (`Q_i` would otherwise drop below 0),
//! * `a_i = 0` where `P_i = C_i`,
//!
//! and `a = max_i a_i`. Then `Q = C + (P − C) / a`, and the layer's alpha is multiplied by `a`.
//! Composited over `C` again with Normal blending, the result reproduces `P`.
//!
//! Two thresholds shape `a`: distances at or below `transparency` become fully transparent, at or
//! above `opacity` fully opaque, linear in between (`0` and `1` leave `a` as computed).
//!
//! The arithmetic runs on the stored channel values of the document (encoded, not linearised, at
//! every depth). That is the space PhotoCraft's Normal blending composites in, so the unmixed
//! layer over a fill of the removed colour gives back the original pixels exactly.
use photocraft_geom::Rect;
use crate::Ctx;
use crate::fxutil::{MAXC, native, ncol};
use crate::image::Image;
/// The opacity `a` (0–1) a pixel needs to be a mix of some in-range colour and `key`, per the
/// module docs. Out-of-range samples (32-bit HDR values beyond what `key` can reach) need full
/// opacity; non-finite samples are ignored.
pub fn opacity(colour: &[f32], key: &[f32]) -> f32 {
let mut a = 0.0f32;
for (&p, &c) in colour.iter().zip(key) {
let ai = if p > c {
// Past a key at the top of the range (`1 − C = 0`) no in-range colour reaches `P`.
if c < 1.0 { (p - c) / (1.0 - c) } else { 1.0 }
} else if p < c {
if c > 0.0 { (c - p) / c } else { 1.0 }
} else {
0.0
};
if ai.is_finite() {
a = a.max(ai);
}
}
a.clamp(0.0, 1.0)
}
/// Applies the thresholds: `a <= transparency` → 0, `a >= opacity` → 1, linear in between.
pub fn remap(a: f32, transparency: f32, opacity: f32) -> f32 {
if a <= transparency {
0.0
} else if a >= opacity {
1.0
} else {
// Here transparency < a < opacity, so the span is positive.
((a - transparency) / (opacity - transparency)).clamp(0.0, 1.0)
}
}
/// Unmixes `key` from one pixel's colour channels in place and returns the factor its alpha is
/// multiplied by. Fully opaque results keep the colour as it was; fully transparent ones take the
/// key colour (any colour would do, this one keeps the result deterministic).
pub fn unmix(colour: &mut [f32], key: &[f32], transparency: f32, opacity_threshold: f32) -> f32 {
let a = remap(opacity(colour, key), transparency, opacity_threshold);
if a >= 1.0 {
return 1.0;
}
for (p, &c) in colour.iter_mut().zip(key) {
*p = if a <= 0.0 { c } else { (c + (*p - c) / a).clamp(0.0, 1.0) };
}
a.max(0.0)
}
/// The filter kernel: `color` is straight sRGB (its alpha is ignored), converted to the document's
/// colour model. Surfaces without an alpha channel (a channel or Quick Mask target) are returned
/// unchanged, since there is nowhere to put the transparency.
pub(crate) fn color_to_alpha(src: &Image, out: Rect, ctx: &Ctx, color: [f32; 4], transparency: f32, opacity_threshold: f32) -> Vec<f32> {
let n = src.ch;
let mut res = src.crop(out);
if !ctx.alpha || n < 2 {
return res;
}
let cc = ncol(ctx, n).min(MAXC);
let key_all = native(ctx, [color[0], color[1], color[2], 1.0]);
let key = key_all.get(..cc).unwrap_or(&[]);
for px in res.chunks_exact_mut(n) {
let Some((alpha, colour)) = px.split_last_mut() else { continue };
let a = unmix(colour, key, transparency, opacity_threshold);
*alpha *= a;
}
res
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{FilterParams, apply, output_area};
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_raster::Surface;
fn close(a: f32, b: f32, tol: f32) -> bool {
(a - b).abs() <= tol
}
fn c2a(color: [f32; 4], t: f32, o: f32) -> FilterParams {
FilterParams::ColorToAlpha { color, transparency_threshold: t, opacity_threshold: o }
}
fn run(s: &Surface, p: &FilterParams, r: Rect) -> Surface {
let area = output_area(p, s.content_bounds(), r, None);
apply(s, p, area, r, None)
}
#[test]
fn the_key_colour_becomes_fully_transparent() {
let mut px = [1.0, 1.0, 1.0];
assert_eq!(unmix(&mut px, &[1.0, 1.0, 1.0], 0.0, 1.0), 0.0);
let mut px = [0.2, 0.4, 0.6];
assert_eq!(unmix(&mut px, &[0.2, 0.4, 0.6], 0.0, 1.0), 0.0);
}
#[test]
fn grey_on_white_is_black_with_partial_alpha() {
// An antialiased black-on-white edge pixel at 30 % coverage.
let mut px = [0.7, 0.7, 0.7];
let a = unmix(&mut px, &[1.0, 1.0, 1.0], 0.0, 1.0);
assert!(close(a, 0.3, 1e-6), "{a}");
assert!(px.iter().all(|v| close(*v, 0.0, 1e-5)), "{px:?}");
// Pure black stays opaque and black.
let mut px = [0.0, 0.0, 0.0];
assert_eq!(unmix(&mut px, &[1.0, 1.0, 1.0], 0.0, 1.0), 1.0);
assert_eq!(px, [0.0, 0.0, 0.0]);
}
#[test]
fn unmixed_colour_composited_over_the_key_gives_back_the_pixel() {
let key = [0.2, 0.6, 0.9];
for p in [[0.5, 0.5, 0.5], [0.1, 0.9, 0.95], [0.25, 0.6, 0.0], [1.0, 0.0, 0.3]] {
let mut q = p;
let a = unmix(&mut q, &key, 0.0, 1.0);
assert!(q.iter().all(|v| (0.0..=1.0).contains(v)), "{q:?}");
for i in 0..3 {
let back = a * q[i] + (1.0 - a) * key[i];
assert!(close(back, p[i], 1e-5), "{p:?} → {q:?} a={a}");
}
}
}
#[test]
fn thresholds_clip_and_stretch_the_opacity() {
assert_eq!(remap(0.1, 0.2, 0.8), 0.0);
assert_eq!(remap(0.2, 0.2, 0.8), 0.0);
assert_eq!(remap(0.8, 0.2, 0.8), 1.0);
assert!(close(remap(0.5, 0.2, 0.8), 0.5, 1e-6));
// Crossed thresholds never divide by zero.
assert_eq!(remap(0.5, 0.6, 0.4), 0.0);
assert_eq!(remap(0.7, 0.6, 0.4), 1.0);
assert_eq!(remap(0.5, 0.5, 0.5), 0.0);
// A near-white pixel under the transparency threshold disappears completely…
let mut px = [0.95, 0.95, 0.95];
assert_eq!(unmix(&mut px, &[1.0; 3], 0.1, 1.0), 0.0);
// …and a mid grey above the opacity threshold is left exactly as it was.
let mut px = [0.4, 0.4, 0.4];
assert_eq!(unmix(&mut px, &[1.0; 3], 0.0, 0.5), 1.0);
assert_eq!(px, [0.4, 0.4, 0.4]);
}
#[test]
fn hdr_and_non_finite_samples_stay_opaque_and_finite() {
let mut px = [1.5, 1.0, 1.0];
assert_eq!(unmix(&mut px, &[1.0; 3], 0.0, 1.0), 1.0);
assert_eq!(px, [1.5, 1.0, 1.0]);
let mut px = [f32::NAN, 0.5, 0.5];
let a = unmix(&mut px, &[1.0; 3], 0.0, 1.0);
assert!(a.is_finite() && close(a, 0.5, 1e-6));
// A black key: everything brighter is a mix of black and a brighter colour.
let mut px = [0.25, 0.5, 0.0];
let a = unmix(&mut px, &[0.0; 3], 0.0, 1.0);
assert!(close(a, 0.5, 1e-6));
assert!(close(px[0], 0.5, 1e-6) && close(px[1], 1.0, 1e-6) && close(px[2], 0.0, 1e-6), "{px:?}");
}
#[test]
fn works_at_every_depth_and_multiplies_existing_alpha() {
let r = Rect::new(0, 0, 4, 1);
for st in [SampleType::U8, SampleType::U16, SampleType::F32] {
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, st, true));
s.write_region(r, &[1.0, 1.0, 1.0, 1.0, 0.6, 0.6, 0.6, 1.0, 0.0, 0.0, 0.0, 1.0, 0.6, 0.6, 0.6, 0.5]);
let out = run(&s, &c2a([1.0, 1.0, 1.0, 1.0], 0.0, 1.0), r);
let tol = if st == SampleType::U8 { 2.0 / 255.0 } else { 1e-3 };
assert!(close(out.pixel(0, 0)[3], 0.0, tol), "{st:?} white gone");
let edge = out.pixel(1, 0);
assert!(close(edge[3], 0.4, tol) && close(edge[0], 0.0, tol), "{st:?} edge {edge:?}");
assert_eq!(out.pixel(2, 0), s.pixel(2, 0), "{st:?} black kept");
assert!(close(out.pixel(3, 0)[3], 0.2, tol), "{st:?} alpha multiplied");
}
}
#[test]
fn grayscale_uses_the_key_converted_to_gray() {
let r = Rect::new(0, 0, 2, 1);
for st in [SampleType::U8, SampleType::U16, SampleType::F32] {
let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, st, true));
s.write_region(r, &[1.0, 1.0, 0.75, 1.0]);
let out = run(&s, &c2a([1.0, 1.0, 1.0, 1.0], 0.0, 1.0), r);
let tol = if st == SampleType::U8 { 2.0 / 255.0 } else { 1e-3 };
assert!(close(out.pixel(0, 0)[1], 0.0, tol), "{st:?}");
let p = out.pixel(1, 0);
assert!(close(p[0], 0.0, tol) && close(p[1], 0.25, tol), "{st:?} {p:?}");
}
}
#[test]
fn coloured_key_on_a_coloured_background() {
// Black text antialiased on a blue background: the blue goes, the ink stays.
let r = Rect::new(0, 0, 2, 1);
let blue = [0.2, 0.4, 0.8, 1.0];
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::F32, true));
// Pixel 1: 50 % black over blue.
s.write_region(r, &[0.2, 0.4, 0.8, 1.0, 0.1, 0.2, 0.4, 1.0]);
let out = run(&s, &c2a(blue, 0.0, 1.0), r);
assert!(out.pixel(0, 0)[3] < 1e-6);
let p = out.pixel(1, 0);
assert!(close(p[3], 0.5, 1e-5) && p[..3].iter().all(|v| close(*v, 0.0, 1e-5)), "{p:?}");
}
#[test]
fn surfaces_without_alpha_are_left_alone() {
let r = Rect::new(0, 0, 2, 2);
let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false));
s.fill_rect(r, &[1.0]);
let out = run(&s, &c2a([1.0; 4], 0.0, 1.0), r);
assert_eq!(out.read_region(r), s.read_region(r));
}
}
+543 -136
View File
@@ -1,30 +1,48 @@
//! Edit › Content-Aware Fill: patch-based completion ([`crate::inpaint::complete`]) with a
//! restricted sampling area, geometric adaptation and colour adaptation.
//! Edit › Content-Aware Fill: patch-based completion ([`crate::inpaint::complete_masked`]) with
//! Photoshop's sampling area, colour adaptation and geometric adaptation.
//!
//! * **Sampling area**: pixels outside the allowed `source` mask may not be copied from. The
//! completion only copies fully-known patches, so excluded pixels are handed to it as
//! unknown and restored afterwards; only the real hole keeps the synthesised values.
//! Photoshop 25.4 was measured as a black box (synthetic and public-domain images, results read
//! back exactly; none of its code or assets were used):
//!
//! * **Sampling window** ([`sampling_window`]): the fill copies only from a square centred on the
//! selection's bounding box, of side `4·√(max(w, 50)·max(h, 50))`: four times a square
//! selection's side, 200 px at least, and for a long thin selection four times the geometric
//! mean of its sides. At the canvas edge the square slides inwards rather than being cut. Pixels
//! outside it never change the result (Edit › Fill and the workspace's Rectangular area alike).
//! * **Auto sampling area** ([`auto_sampling`]): the workspace's default keeps, within that
//! square, only what looks like the selection's surroundings: a region of another brightness or
//! another texture is left out along its edges, wherever it lies (a bright band through the
//! window is excluded, the matching area beyond it is not).
//! * **The fill** copies pieces of the sampling area pixel for pixel (15–40 px across), joined by
//! seams a few pixels wide: see [`crate::inpaint`].
//! * **Colour adaptation** None / Default / High / Very High: with None the copies are exact; the
//! others let each copied patch take a gain and a bias towards its surroundings, more at each
//! level ([`color_level`]). The patch transform is that of S. Darabi et al., *Image Melding*,
//! SIGGRAPH 2012.
//! * **Rotation / scale / mirror adaptation**: the sampling window is extended with rotated,
//! rescaled and mirrored copies of itself, laid out side by side (separated by unknown gaps
//! wider than a patch), so the patch search can pick transformed source patches, as in
//! the generalised PatchMatch of C. Barnes, E. Shechtman, D. B. Goldman, A. Finkelstein,
//! *The Generalized PatchMatch Correspondence Algorithm*, ECCV 2010 (which searches over
//! rotations and scales; we enumerate a small set instead).
//! * **Colour adaptation**: the low frequencies of the fill are pulled towards the smooth
//! membrane interpolation of the hole boundary (P. Pérez, M. Gangnet, A. Blake, *Poisson
//! Image Editing*, SIGGRAPH 2003 uses the same membrane for seamless cloning), which corrects
//! gradual brightness and colour changes across the hole while keeping the copied texture.
//! rescaled and mirrored copies of itself, laid out side by side (separated by gaps that are no
//! image at all), so the patch search can pick transformed source patches, as in the
//! generalised PatchMatch of C. Barnes, E. Shechtman, D. B. Goldman, A. Finkelstein, *The
//! Generalized PatchMatch Correspondence Algorithm*, ECCV 2010 (which searches over rotations
//! and scales; we enumerate a small set instead).
//!
//! Buffers are interleaved `w × h × ch` normalised floats (any model/depth); deterministic.
use crate::inpaint::{CompleteParams, complete_with};
use photocraft_geom::Rect;
use std::borrow::Cow;
use photocraft_raster::{Cancelled, Interrupt};
use crate::inpaint::{Adapt, CompleteParams, Px, complete_masked, complete_masked_owned};
use crate::par;
use crate::poisson::membrane_fill_with;
/// Options for [`fill`].
#[derive(Clone, Debug, PartialEq)]
pub struct FillOptions {
/// Colour adaptation strength `0..=1` (Photoshop: none 0, default ≈0.35, high, very high).
pub color_adaptation: f32,
/// Colour adaptation of the copies ([`color_level`]).
pub color_adaptation: Adapt,
/// Extra source rotations in degrees (Photoshop's rotation adaptation levels).
pub rotations: Vec<f32>,
/// Add downscaled and upscaled source copies.
@@ -36,7 +54,7 @@ pub struct FillOptions {
impl Default for FillOptions {
fn default() -> Self {
Self { color_adaptation: 0.35, rotations: Vec::new(), scale: false, mirror: false, seed: 1 }
Self { color_adaptation: color_level("default"), rotations: Vec::new(), scale: false, mirror: false, seed: 1 }
}
}
@@ -51,16 +69,43 @@ pub fn rotation_level(level: &str) -> Vec<f32> {
}
}
/// Colour adaptation strength for Photoshop's levels: none, default, high, veryHigh.
pub fn color_level(level: &str) -> f32 {
/// Colour adaptation for Photoshop's levels: none, default, high, veryHigh. Measured on a texture
/// under a brightness ramp: with None the copies are exact; Default shifts them by up to about
/// 10/255, High about 20, Very High about 35, scaling their contrast a little more at each level.
pub fn color_level(level: &str) -> Adapt {
match level {
"none" => 0.0,
"high" => 0.65,
"veryHigh" => 0.9,
_ => 0.35,
"none" => Adapt::NONE,
"high" => Adapt { gain: (0.8, 1.25), bias: 0.08 },
"veryHigh" => Adapt { gain: (0.67, 1.5), bias: 0.14 },
_ => Adapt { gain: (0.9, 1.1), bias: 0.04 },
}
}
/// Photoshop's sampling window for a selection with bounding box `hole`: the square of side
/// `4·√(max(w, 50)·max(h, 50))` centred on it, slid inside `canvas` (and clipped to it only where
/// the canvas is smaller than the square). A selection longer than that square (more than 16
/// times as long as it is wide, which was not measured) keeps its whole length.
pub fn sampling_window(hole: Rect, canvas: Rect) -> Rect {
if hole.is_empty() || canvas.is_empty() {
return Rect::EMPTY;
}
let (w, h) = (f64::from(hole.width().max(50)), f64::from(hole.height().max(50)));
let side = (4.0 * (w * h).sqrt()).round().min(i32::MAX as f64) as i64;
// Twice the centre, so that odd sizes stay exact.
let span = |c2: i64, extent: u32, lo: i32, hi: i32| -> (i32, i32) {
let (lo, hi) = (i64::from(lo), i64::from(hi));
let side = side.max(i64::from(extent));
if side >= hi - lo {
return (lo as i32, hi as i32);
}
let a = ((c2 - side) / 2).clamp(lo, hi - side);
(a as i32, (a + side) as i32)
};
let (x0, x1) = span(i64::from(hole.x0) + i64::from(hole.x1), hole.width(), canvas.x0, canvas.x1);
let (y0, y1) = span(i64::from(hole.y0) + i64::from(hole.y1), hole.height(), canvas.y0, canvas.y1);
Rect::new(x0, y0, x1, y1)
}
/// One source variant: pixels and which of them are usable.
struct Variant {
w: usize,
@@ -103,7 +148,8 @@ fn sample(src: Src, x: f32, y: f32, out: &mut [f32]) -> bool {
}
/// Transformed copy of the source: rotation (degrees) and scale about the centre, optional mirror.
fn variant(src: Src, deg: f32, scale: f32, mirror: bool) -> Variant {
/// `Err` when cancelled.
fn variant(src: Src, deg: f32, scale: f32, mirror: bool, ctl: &Interrupt) -> Result<Variant, Cancelled> {
let Src { w, h, ch, .. } = src;
let (s, c) = (-deg.to_radians()).sin_cos();
// Output size: the rotated, scaled bounding box.
@@ -113,8 +159,12 @@ fn variant(src: Src, deg: f32, scale: f32, mirror: bool) -> Variant {
let (icx, icy) = ((w as f32 - 1.0) / 2.0, (h as f32 - 1.0) / 2.0);
let (ocx, ocy) = ((ow as f32 - 1.0) / 2.0, (oh as f32 - 1.0) / 2.0);
let mut out = Variant { w: ow, h: oh, img: vec![0.0; ow * oh * ch], ok: vec![false; ow * oh] };
let mut px = vec![0.0f32; ch];
for y in 0..oh {
// Every pixel is sampled on its own, so the rows can be done in any order.
let row = |y: usize, irow: &mut [f32], orow: &mut [bool]| {
if ctl.cancelled() {
return;
}
let mut px = vec![0.0f32; ch];
for x in 0..ow {
let (dx, dy) = ((x as f32 - ocx) / scale, (y as f32 - ocy) / scale);
let mut sx = icx + dx * c - dy * s;
@@ -123,38 +173,14 @@ fn variant(src: Src, deg: f32, scale: f32, mirror: bool) -> Variant {
sx = (w as f32 - 1.0) - sx;
}
if sample(src, sx, sy, &mut px) {
let i = y * ow + x;
out.ok[i] = true;
out.img[i * ch..(i + 1) * ch].copy_from_slice(&px);
orow[x] = true;
irow[x * ch..(x + 1) * ch].copy_from_slice(&px);
}
}
}
out
}
/// Separable box blur of radius `r` (edge-clamped).
fn box_blur(w: usize, h: usize, ch: usize, v: &[f32], r: usize) -> Vec<f32> {
if r == 0 {
return v.to_vec();
}
let pass = |src: &[f32], horizontal: bool| -> Vec<f32> {
let mut dst = vec![0.0f32; src.len()];
let (n, m) = if horizontal { (h, w) } else { (w, h) };
let idx = |line: usize, k: usize| if horizontal { line * w + k } else { k * w + line };
let norm = 1.0 / (2 * r + 1) as f32;
for line in 0..n {
for c in 0..ch {
let at = |k: i64| src[idx(line, k.clamp(0, m as i64 - 1) as usize) * ch + c];
let mut acc: f32 = (-(r as i64)..=r as i64).map(at).sum();
for k in 0..m {
dst[idx(line, k) * ch + c] = acc * norm;
acc += at(k as i64 + r as i64 + 1) - at(k as i64 - r as i64);
}
}
}
dst
};
pass(&pass(v, true), false)
par::chunks2_mut(&mut out.img, ow * ch, &mut out.ok, ow, true, row);
ctl.check()?;
Ok(out)
}
/// Fill `hole` in `img`, copying only from pixels where `source` is true (and not in the hole).
@@ -176,115 +202,350 @@ pub fn fill_with(
source: &[bool],
opts: &FillOptions,
ctl: &photocraft_raster::Interrupt,
) -> Result<Vec<f32>, photocraft_raster::Cancelled> {
fill_cow(w, h, ch, Cow::Borrowed(img), hole, source, opts, ctl)
}
/// [`fill_with`] that fills `img` itself rather than a copy of it (a big window need not be held
/// twice). The result differs from `img` only in the hole.
#[allow(clippy::too_many_arguments)]
pub fn fill_owned(
w: usize,
h: usize,
ch: usize,
img: Vec<f32>,
hole: &[bool],
source: &[bool],
opts: &FillOptions,
ctl: &photocraft_raster::Interrupt,
) -> Result<Vec<f32>, photocraft_raster::Cancelled> {
fill_cow(w, h, ch, Cow::Owned(img), hole, source, opts, ctl)
}
#[allow(clippy::too_many_arguments)]
fn fill_cow(
w: usize,
h: usize,
ch: usize,
img: Cow<[f32]>,
hole: &[bool],
source: &[bool],
opts: &FillOptions,
ctl: &photocraft_raster::Interrupt,
) -> Result<Vec<f32>, photocraft_raster::Cancelled> {
assert_eq!(img.len(), w * h * ch);
assert_eq!(hole.len(), w * h);
assert_eq!(source.len(), w * h);
if !hole.iter().any(|h| *h) {
return Ok(img.to_vec());
return Ok(img.into_owned());
}
let params = CompleteParams { seed: opts.seed, ..Default::default() };
let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() };
let gap = 2 * params.patch_radius + 2;
let ok: Vec<bool> = hole.iter().zip(source).map(|(h, s)| !h && *s).collect();
let src = Src { w, h, ch, img, ok: &ok };
let ok: Vec<bool> = par::map(w * h, true, |i| !hole[i] && source[i]);
let src = Src { w, h, ch, img: &img, ok: &ok };
// Variants: the identity (which holds the hole) first, then the adaptations.
let mut extra: Vec<Variant> = Vec::new();
if opts.mirror {
extra.push(variant(src, 0.0, 1.0, true));
extra.push(variant(src, 0.0, 1.0, true, ctl)?);
}
for &deg in &opts.rotations {
extra.push(variant(src, deg, 1.0, false));
extra.push(variant(src, deg, 1.0, false, ctl)?);
}
if opts.scale {
extra.push(variant(src, 0.0, 0.8, false));
extra.push(variant(src, 0.0, 1.25, false));
extra.push(variant(src, 0.0, 0.8, false, ctl)?);
extra.push(variant(src, 0.0, 1.25, false, ctl)?);
}
// Mosaic: identity at the left, variants in a column to its right.
let col_w = extra.iter().map(|v| v.w).max().unwrap_or(0);
let col_h: usize = extra.iter().map(|v| v.h + gap).sum();
let mw = if extra.is_empty() { w } else { w + gap + col_w };
let mh = h.max(col_h);
let mut mimg = vec![0.0f32; mw * mh * ch];
let mut unknown = vec![true; mw * mh];
for y in 0..h {
for x in 0..w {
let (s, d) = (y * w + x, y * mw + x);
mimg[d * ch..(d + 1) * ch].copy_from_slice(&img[s * ch..(s + 1) * ch]);
unknown[d] = !ok[s];
let role = |s: usize| {
if hole[s] {
Px::Hole
} else if ok[s] {
Px::Source
} else {
Px::Known
}
}
let mut oy = 0;
for v in &extra {
for y in 0..v.h {
for x in 0..v.w {
let (s, d) = (y * v.w + x, (oy + y) * mw + w + gap + x);
mimg[d * ch..(d + 1) * ch].copy_from_slice(&v.img[s * ch..(s + 1) * ch]);
unknown[d] = !v.ok[s];
};
// Mosaic: identity at the left, variants in a column to its right, gaps that are no image.
// Without variants it is the image itself.
let (mw, mh, mosaic, roles): (usize, usize, Option<Vec<f32>>, Vec<Px>) = if extra.is_empty() {
(w, h, None, par::map(w * h, true, role))
} else {
let col_w = extra.iter().map(|v| v.w).max().unwrap_or(0);
let col_h: usize = extra.iter().map(|v| v.h + gap).sum();
let mw = w + gap + col_w;
let mh = h.max(col_h);
let mut mimg = vec![0.0f32; mw * mh * ch];
let mut roles = vec![Px::Void; mw * mh];
for y in 0..h {
for x in 0..w {
let (s, d) = (y * w + x, y * mw + x);
mimg[d * ch..(d + 1) * ch].copy_from_slice(&img[s * ch..(s + 1) * ch]);
roles[d] = role(s);
}
}
oy += v.h + gap;
}
ctl.check()?;
// The completion is nearly all the work: it reports 0–90 %.
let cancel = || ctl.cancelled();
let progress = |f: f32| ctl.progress(f * 0.9);
let filled = complete_with(mw, mh, ch, &mimg, &unknown, &params, &photocraft_raster::Interrupt::new(&cancel, &progress))?;
let mut out = img.to_vec();
match filled {
Some(f) => {
for y in 0..h {
for x in 0..w {
if hole[y * w + x] {
let (s, d) = ((y * mw + x) * ch, (y * w + x) * ch);
out[d..d + ch].copy_from_slice(&f[s..s + ch]);
let mut oy = 0;
for v in &extra {
ctl.check()?;
for y in 0..v.h {
for x in 0..v.w {
let (s, d) = (y * v.w + x, (oy + y) * mw + w + gap + x);
mimg[d * ch..(d + 1) * ch].copy_from_slice(&v.img[s * ch..(s + 1) * ch]);
if v.ok[s] {
roles[d] = Px::Source;
}
}
}
oy += v.h + gap;
}
None => out = membrane_fill_with(w, h, ch, img, hole, ctl)?,
}
(mw, mh, Some(mimg), roles)
};
drop((extra, ok));
ctl.check()?;
// The completion is nearly all the work.
let cancel = || ctl.cancelled();
let progress = |f: f32| ctl.progress(f * 0.99);
let inner = photocraft_raster::Interrupt::new(&cancel, &progress);
let out = match mosaic {
// Without variants the image itself is completed (it changes only in the hole).
None => {
let filled: Result<Vec<f32>, Cow<[f32]>> = match img {
Cow::Owned(v) => complete_masked_owned(w, h, ch, v, &roles, &params, &inner)?.map_err(Cow::Owned),
Cow::Borrowed(b) => complete_masked(w, h, ch, b, &roles, &params, &inner)?.ok_or(Cow::Borrowed(b)),
};
match filled {
Ok(f) => f,
Err(img) => membrane_fill_with(w, h, ch, &img, hole, ctl)?,
}
}
Some(mimg) => match complete_masked(mw, mh, ch, &mimg, &roles, &params, &inner)? {
Some(f) => {
let mut out = img.into_owned();
for y in 0..h {
for x in 0..w {
if hole[y * w + x] {
let (s, d) = ((y * mw + x) * ch, (y * w + x) * ch);
out[d..d + ch].copy_from_slice(&f[s..s + ch]);
}
}
}
out
}
None => membrane_fill_with(w, h, ch, &img, hole, ctl)?,
},
};
ctl.check()?;
if opts.color_adaptation > 0.0 {
adapt_colors(w, h, ch, img, hole, &mut out, opts.color_adaptation, ctl)?;
}
ctl.progress(1.0);
Ok(out)
}
/// Pull the fill's low frequencies towards the membrane interpolation of the hole boundary.
#[allow(clippy::too_many_arguments)]
fn adapt_colors(
w: usize,
h: usize,
ch: usize,
img: &[f32],
hole: &[bool],
out: &mut [f32],
k: f32,
ctl: &photocraft_raster::Interrupt,
) -> Result<(), photocraft_raster::Cancelled> {
let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
/// Box mean of radius `r` over a `w × h` plane (edge-clamped), by summed areas.
fn box_mean(w: usize, h: usize, v: &[f32], r: usize) -> Vec<f32> {
let w1 = w + 1;
let mut s = vec![0.0f64; w1 * (h + 1)];
for y in 0..h {
let mut row = 0.0f64;
for x in 0..w {
if hole[y * w + x] {
(x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1));
}
row += f64::from(v[y * w + x]);
s[(y + 1) * w1 + x + 1] = s[y * w1 + x + 1] + row;
}
}
let r = ((x1 - x0).max(y1 - y0) / 6).clamp(1, 32);
let membrane = membrane_fill_with(w, h, ch, img, hole, ctl)?;
ctl.progress(0.97);
let mut out = vec![0.0f32; w * h];
for y in 0..h {
let (y0, y1) = (y.saturating_sub(r), (y + r + 1).min(h));
for x in 0..w {
let (x0, x1) = (x.saturating_sub(r), (x + r + 1).min(w));
let sum = s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0];
out[y * w + x] = (sum / ((x1 - x0) * (y1 - y0)) as f64) as f32;
}
}
out
}
/// Largest side [`auto_sampling`] works at: bigger windows are segmented at a reduced scale.
const AUTO_SIDE: usize = 384;
/// Content-Aware Fill's Auto sampling area within a window (the whole `w × h` buffer): the pixels
/// that look like the hole's surroundings. Each pixel is described by its local mean colour and
/// local contrast (7 × 7); the ring around the hole is summarised by a few clusters of those; a
/// pixel near a cluster prefers to be sampled, one far from all of them not, and one min cut
/// (contrast-sensitive, so the boundary follows edges) settles the area. Returns the mask of
/// pixels that may be copied from (never the hole). Falls back to everything outside the hole
/// when the area would be too small to copy from.
pub fn auto_sampling(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool]) -> Vec<bool> {
// Never cancelled; the fallback (everything outside the hole) is unreachable.
auto_sampling_with(w, h, ch, img, hole, &Interrupt::NONE).unwrap_or_else(|_| hole.iter().map(|h| !h).collect())
}
/// [`auto_sampling`] that can be cancelled. `Err(Cancelled)` when `ctl` was cancelled.
pub fn auto_sampling_with(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], ctl: &Interrupt) -> Result<Vec<bool>, Cancelled> {
use crate::segment::{FREE, HARD_FG, RgbImage, grid_cut_cancellable};
assert_eq!(img.len(), w * h * ch);
assert_eq!(hole.len(), w * h);
let everything = || -> Vec<bool> { par::map(hole.len(), true, |i| !hole[i]) };
if w == 0 || h == 0 || ch == 0 || !hole.iter().any(|h| *h) {
return Ok(everything());
}
// Work at a reduced scale for big windows (the area is smooth at this scale).
let k = w.max(h).div_ceil(AUTO_SIDE).max(1);
let (sw, sh) = (w.div_ceil(k), h.div_ceil(k));
let nc = ch.min(3);
// Each cell sums its k × k pixels, a row of cells at a time (in the same order as one pass
// over the image would).
// Per cell: the sums of its colour planes, its pixel count and whether it holds the hole.
let mut sums = vec![0.0f32; sw * sh * (nc + 2)];
par::chunks_mut(&mut sums, sw * (nc + 2), true, |sy, row| {
if ctl.cancelled() {
return;
}
for y in sy * k..((sy + 1) * k).min(h) {
for x in 0..w {
let cell = &mut row[(x / k) * (nc + 2)..(x / k + 1) * (nc + 2)];
let p = y * w + x;
if hole[p] {
cell[nc + 1] = 1.0;
}
for c in 0..nc {
cell[c] += img[p * ch + c];
}
cell[nc] += 1.0;
}
}
});
ctl.check()?;
let low = box_blur(w, h, ch, out, r);
for (i, &hl) in hole.iter().enumerate() {
if hl {
for c in 0..ch {
let j = i * ch + c;
out[j] = (out[j] + k * (membrane[j] - low[j])).clamp(0.0, 1.0);
let cell = |i: usize| &sums[i * (nc + 2)..(i + 1) * (nc + 2)];
let planes: Vec<Vec<f32>> = (0..nc).map(|c| (0..sw * sh).map(|i| cell(i)[c] / cell(i)[nc].max(1.0)).collect()).collect();
let shole: Vec<bool> = (0..sw * sh).map(|i| cell(i)[nc + 1] > 0.0).collect();
drop(sums);
// Features: local means and local contrast (of the luma-ish average of the colour planes).
let r = 3;
let means: Vec<Vec<f32>> = planes.iter().map(|p| box_mean(sw, sh, p, r)).collect();
let luma: Vec<f32> = (0..sw * sh).map(|i| planes.iter().map(|p| p[i]).sum::<f32>() / nc as f32).collect();
let luma2: Vec<f32> = luma.iter().map(|v| v * v).collect();
let (lm, lm2) = (box_mean(sw, sh, &luma, r), box_mean(sw, sh, &luma2, r));
let contrast: Vec<f32> = lm.iter().zip(&lm2).map(|(m, m2)| (m2 - m * m).max(0.0).sqrt()).collect();
let nf = nc + 1;
let feat = |i: usize, out: &mut [f32]| {
for (c, m) in means.iter().enumerate() {
out[c] = m[i];
}
out[nc] = 2.0 * contrast[i];
};
// The ring: outside the hole, within a few pixels of it.
let dist = crate::selection::edt(&shole, sw, sh);
let ring_w = 6.0f32 / k as f32 + 1.0;
let ring: Vec<usize> = (0..sw * sh).filter(|&i| !shole[i] && dist[i] <= ring_w).collect();
if ring.is_empty() {
return Ok(everything());
}
ctl.check()?;
// A few cluster centres of the ring's features (k-means, deterministic start).
let kc = 6.min(ring.len());
let mut f = vec![0.0f32; nf];
let mut centres: Vec<Vec<f32>> = (0..kc)
.map(|j| {
feat(ring[j * ring.len() / kc], &mut f);
f.clone()
})
.collect();
let d2 = |a: &[f32], b: &[f32]| a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum::<f32>();
for _ in 0..8 {
let mut acc = vec![vec![0.0f32; nf]; kc];
let mut n = vec![0usize; kc];
for &i in &ring {
feat(i, &mut f);
let j = (0..kc).min_by(|&a, &b| d2(&f, &centres[a]).total_cmp(&d2(&f, &centres[b]))).unwrap_or(0);
acc[j].iter_mut().zip(&f).for_each(|(a, v)| *a += v);
n[j] += 1;
}
for j in 0..kc {
if n[j] > 0 {
centres[j] = acc[j].iter().map(|v| v / n[j] as f32).collect();
}
}
}
Ok(())
let nearest = |i: usize, f: &mut [f32]| -> f32 {
feat(i, f);
centres.iter().map(|c| d2(f, c)).fold(f32::INFINITY, f32::min).sqrt()
};
// How much the ring itself varies around its clusters sets the scale of "similar".
let mut spread: Vec<f32> = ring.iter().map(|&i| nearest(i, &mut f)).collect();
let q = (spread.len() * 9 / 10).min(spread.len() - 1);
let (_, s90, _) = spread.select_nth_unstable_by(q, |a, b| a.total_cmp(b));
let tau = (*s90 * 1.6).max(0.03);
let mut cost_fg = vec![0.0f32; sw * sh];
let mut cost_bg = vec![0.0f32; sw * sh];
let mut fixed = vec![FREE; sw * sh];
for i in 0..sw * sh {
if shole[i] || dist[i] <= 1.5 {
fixed[i] = HARD_FG;
continue;
}
let d = nearest(i, &mut f) / tau;
cost_fg[i] = d * d;
cost_bg[i] = 1.0;
}
let rgb = RgbImage::from_fn(sw, sh, |x, y| {
let i = y * sw + x;
let c = |j: usize| means[j.min(nc - 1)][i];
[c(0), c(1), c(2)]
});
// Contrast-sensitive smoothness (the weight of a squared colour difference). The scale of
// "similar" and this weight were fitted to Photoshop's Auto overlays (mean IoU 0.92 on ten
// synthetic and public-domain cases).
ctl.check()?;
let area =
grid_cut_cancellable(&rgb, &cost_fg, &cost_bg, &fixed, |d2| 8.0 * (-d2 / (2.0 * 0.05 * 0.05)).exp() + 0.05, &|| ctl.cancelled()).ok_or(Cancelled)?;
let mut out = vec![false; w * h];
par::chunks_mut(&mut out, w, true, |y, row| {
for (x, o) in row.iter_mut().enumerate() {
*o = !hole[y * w + x] && area[(y / k) * sw + x / k];
}
});
// Too little to copy from (fewer source pixels than twice the hole): sample everything.
let n_hole = par::count(hole.len(), |i| hole[i]);
if par::count(out.len(), |i| out[i]) < 2 * n_hole.max(64) {
return Ok(everything());
}
Ok(out)
}
/// The Patch Tool's and the Content-Aware Move Tool's Color option (0–10) as the colour adaptation
/// of the copied content. Measured on Photoshop 25.4 with content brighter than its new place: 0
/// keeps it as it is; 3 moves it about 0.12 (32 of 42 levels, and 31 of 102: a limit, not a
/// fraction), 6 about 80 % of 42 levels, 10 most of the way (35 of 42, 95 of 102). So the shift is
/// limited to about `0.04 · color`, the contrast change likewise widening.
pub fn color_amount(color: u8) -> Adapt {
if color == 0 {
return Adapt::NONE;
}
let c = f32::from(color.min(10));
Adapt { gain: (1.0 - 0.033 * c, 1.0 + 0.05 * c), bias: 0.04 * c }
}
/// Gain and bias per channel taking the samples `from` to the level and contrast of the samples
/// `to` (both interleaved, `ch` per sample), within `a`: how copied content is fitted to its new
/// surroundings.
pub fn level_transform(ch: usize, from: &[f32], to: &[f32], a: Adapt) -> Vec<(f32, f32)> {
let moments = |v: &[f32], c: usize| {
let (mut s, mut s2, mut n) = (0.0f64, 0.0f64, 0.0f64);
for x in v.chunks_exact(ch.max(1)) {
s += f64::from(x[c]);
s2 += f64::from(x[c]) * f64::from(x[c]);
n += 1.0;
}
(s, s2, n)
};
(0..ch)
.map(|c| {
let (fs, fs2, fnn) = moments(from, c);
let (ts, ts2, tn) = moments(to, c);
if a.is_none() || fnn == 0.0 || tn == 0.0 {
return (1.0, 0.0);
}
// Both sets scaled to the same count for the fit.
let k = fnn / tn;
crate::inpaint::fit(a, fnn as f32, (ts * k) as f32, (ts2 * k) as f32, fs as f32, fs2 as f32)
})
.collect()
}
#[cfg(test)]
@@ -318,12 +579,42 @@ mod tests {
assert_eq!(out, fill(w, h, 1, &img, &hole, &source, &FillOptions::default()), "same result as the plain fill");
}
#[test]
fn filling_in_place_is_filling_a_copy() {
let (w, h) = (90, 70);
let rgb: Vec<f32> = noise(w, h, 4).iter().enumerate().map(|(i, v)| v * 0.5 + 0.3 * ((i / 3 % w) % 11 < 5) as u8 as f32).collect();
let hole: Vec<bool> = (0..w * h).map(|i| (30..52).contains(&(i % w)) && (25..44).contains(&(i / w))).collect();
let source: Vec<bool> = (0..w * h).map(|i| i % w < 75).collect();
let none = Interrupt::NONE;
for opts in [FillOptions::default(), FillOptions { color_adaptation: Adapt::NONE, mirror: true, ..Default::default() }] {
let copy = fill_with(w, h, 3, &rgb, &hole, &source, &opts, &none).unwrap();
let owned = fill_owned(w, h, 3, rgb.clone(), &hole, &source, &opts, &none).unwrap();
assert_eq!(copy.iter().map(|v| v.to_bits()).collect::<Vec<_>>(), owned.iter().map(|v| v.to_bits()).collect::<Vec<_>>());
// Only the hole changes.
assert!((0..w * h).all(|i| hole[i] || (0..3).all(|c| owned[i * 3 + c].to_bits() == rgb[i * 3 + c].to_bits())));
}
// Nothing to copy from: the membrane, either way.
let nowhere = vec![false; w * h];
let copy = fill_with(w, h, 3, &rgb, &hole, &nowhere, &FillOptions::default(), &none).unwrap();
assert_eq!(copy, fill_owned(w, h, 3, rgb.clone(), &hole, &nowhere, &FillOptions::default(), &none).unwrap());
}
#[test]
fn auto_sampling_can_be_cancelled() {
let (w, h) = (200, 160);
let img: Vec<f32> = noise(w, h, 5).iter().enumerate().map(|(i, v)| v * 0.1 + if (i / 3) % w < 120 { 0.3 } else { 0.6 }).collect();
let hole: Vec<bool> = (0..w * h).map(|i| (80..110).contains(&(i % w)) && (60..90).contains(&(i / w))).collect();
let yes = || true;
assert!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::cancel_only(&yes)).is_err());
assert_eq!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::NONE).unwrap(), auto_sampling(w, h, 3, &img, &hole));
}
#[test]
fn fills_only_the_hole_with_known_texture() {
let (w, h) = (48, 32);
let (img, hole) = stripes(w, h);
let src = vec![true; w * h];
let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: 0.0, ..Default::default() });
let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() });
for i in 0..w * h {
if !hole[i] {
assert_eq!(out[i], img[i]);
@@ -341,7 +632,7 @@ mod tests {
let img: Vec<f32> = (0..w * h).map(|i| if i % w < 20 { 0.1 } else { 0.9 }).collect();
let hole: Vec<bool> = (0..w * h).map(|i| (16..24).contains(&(i % w)) && (6..14).contains(&(i / w))).collect();
let right: Vec<bool> = (0..w * h).map(|i| i % w >= 24).collect();
let out = fill(w, h, 1, &img, &hole, &right, &FillOptions { color_adaptation: 0.0, ..Default::default() });
let out = fill(w, h, 1, &img, &hole, &right, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() });
let mean: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).sum::<f32>() / 64.0;
assert!(mean > 0.8, "mean {mean}");
}
@@ -352,7 +643,7 @@ mod tests {
let (img, hole) = stripes(w, h);
let rgb: Vec<f32> = img.iter().flat_map(|v| [*v, *v * 0.5, 1.0 - *v]).collect();
let src = vec![true; w * h];
let opts = FillOptions { color_adaptation: 0.65, rotations: rotation_level("low"), scale: true, mirror: true, seed: 7 };
let opts = FillOptions { color_adaptation: color_level("high"), rotations: rotation_level("low"), scale: true, mirror: true, seed: 7 };
let a = fill(w, h, 3, &rgb, &hole, &src, &opts);
let b = fill(w, h, 3, &rgb, &hole, &src, &opts);
assert_eq!(a, b);
@@ -366,19 +657,135 @@ mod tests {
let img: Vec<f32> = (0..w * h).map(|i| (i % w) as f32 / w as f32).collect();
let hole: Vec<bool> = (0..w * h).map(|i| (14..26).contains(&(i % w)) && (5..15).contains(&(i / w))).collect();
let src = vec![true; w * h];
let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: 0.9, ..Default::default() });
let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: color_level("veryHigh"), ..Default::default() });
let err: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| (out[i] - img[i]).abs()).sum::<f32>() / 120.0;
assert!(err < 0.12, "mean error {err}");
}
/// I.i.d. noise: every value occurs once, so a filled pixel equal to an image pixel was copied.
fn noise(w: usize, h: usize, seed: u64) -> Vec<f32> {
let mut z = seed;
(0..w * h * 3)
.map(|_| {
z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
0.2 + 0.6 * ((z >> 40) as f32 / (1u64 << 24) as f32)
})
.collect()
}
#[test]
fn sampling_window_is_photoshops() {
let canvas = Rect::new(0, 0, 800, 800);
let sq = |x0: i32, y0: i32, w: i32, h: i32| Rect::new(x0, y0, x0 + w, y0 + h);
// Photoshop 25.4's sampling overlay: a square of side 4·√(max(w,50)·max(h,50)) centred on
// the selection's bounds.
assert_eq!(sampling_window(sq(375, 375, 50, 50), canvas), sq(300, 300, 200, 200));
assert_eq!(sampling_window(sq(350, 350, 100, 100), canvas), sq(200, 200, 400, 400));
assert_eq!(sampling_window(sq(395, 395, 10, 10), canvas), sq(300, 300, 200, 200));
assert_eq!(sampling_window(sq(370, 370, 60, 60), canvas), sq(280, 280, 240, 240));
// Long selections (Photoshop's overlay, read off the screen to a pixel: 281, 399, 691).
assert_eq!(sampling_window(sq(350, 385, 100, 30), canvas), sq(258, 258, 283, 283));
assert_eq!(sampling_window(sq(300, 375, 200, 50), canvas), sq(200, 200, 400, 400));
assert_eq!(sampling_window(sq(250, 350, 300, 100), canvas), sq(53, 53, 693, 693));
// At the canvas edge the square slides inwards rather than being cut.
assert_eq!(sampling_window(sq(10, 375, 50, 50), canvas), sq(0, 300, 200, 200));
assert_eq!(sampling_window(sq(5, 5, 60, 60), canvas), sq(0, 0, 240, 240));
// A canvas smaller than the square clips it; a very long selection keeps its length.
assert_eq!(sampling_window(sq(40, 40, 50, 50), Rect::new(0, 0, 150, 120)), Rect::new(0, 0, 150, 120));
assert_eq!(sampling_window(sq(100, 995, 1800, 10), Rect::new(0, 0, 2000, 2000)), sq(100, 400, 1800, 1200));
assert_eq!(sampling_window(Rect::EMPTY, canvas), Rect::EMPTY);
}
#[test]
fn auto_sampling_keeps_what_looks_like_the_surroundings() {
// Grey texture, dark on the left, 50 levels brighter on the right; the hole is in the dark
// part near the boundary (Photoshop's Auto leaves the bright part out).
let (w, h) = (200, 200);
let tex = noise(w, h, 3);
let shade = |x: usize, band: bool| {
if band {
if (130..150).contains(&x) { 0.55 } else { 0.35 }
} else if x < 135 {
0.35
} else {
0.55
}
};
for band in [false, true] {
let img: Vec<f32> = (0..w * h * 3).map(|i| shade((i / 3) % w, band) + (tex[i] - 0.5) * 0.1).collect();
let hole: Vec<bool> = (0..w * h).map(|i| (75..125).contains(&(i % w)) && (75..125).contains(&(i / w))).collect();
let area = auto_sampling(w, h, 3, &img, &hole);
let frac = |x0: usize, x1: usize| {
let n = (0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && !hole[*i]).count();
(0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && area[*i]).count() as f32 / n as f32
};
assert!(hole.iter().zip(&area).all(|(hl, a)| !(*hl && *a)), "never the hole");
assert!(frac(0, 125) > 0.95, "the dark side is sampled ({})", frac(0, 125));
if band {
// A bright band through the window is left out; the dark area beyond it is not.
assert!(frac(133, 147) < 0.05, "the band is excluded ({})", frac(133, 147));
assert!(frac(155, 200) > 0.9, "beyond the band is sampled ({})", frac(155, 200));
} else {
assert!(frac(140, 200) < 0.05, "the bright side is excluded ({})", frac(140, 200));
}
}
}
#[test]
fn without_colour_adaptation_the_fill_copies_pixels_exactly() {
// A smooth texture with fine noise, so that every value is unique: a filled pixel equal to
// an image pixel was copied from it. Photoshop's fill (colour adaptation None) is such
// copies, joined by narrow seams.
let (w, h) = (120, 120);
let fine = noise(w, h, 9);
let img: Vec<f32> = (0..w * h * 3)
.map(|i| {
let (x, y, c) = (((i / 3) % w) as f32, ((i / 3) / w) as f32, i % 3);
0.5 + 0.2 * (x * 0.21 + c as f32).sin() * (y * 0.17).cos() + 0.1 * (x * 0.05 - y * 0.08).sin() + (fine[i] - 0.5) * 0.08
})
.collect();
let hole: Vec<bool> = (0..w * h).map(|i| (40..80).contains(&(i % w)) && (40..80).contains(&(i / w))).collect();
// Votes of identical copies average to the copy up to float rounding.
let key = |v: &[f32], i: usize| [0, 1, 2].map(|c| (v[i * 3 + c] * 1e5).round() as i64);
let known: std::collections::HashSet<[i64; 3]> = (0..w * h).filter(|i| !hole[*i]).map(|i| key(&img, i)).collect();
let out = fill(w, h, 3, &img, &hole, &vec![true; w * h], &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() });
let exact = (0..w * h).filter(|i| hole[*i] && known.contains(&key(&out, *i))).count();
assert!(exact as f32 > 0.2 * 1600.0, "{exact} of 1600 filled pixels are exact copies");
// And the fill is as busy as the noise around it, not a blur of it.
let lap = |v: &[f32], x: usize, y: usize| {
let p = |x: usize, y: usize| v[(y * w + x) * 3];
(4.0 * p(x, y) - p(x - 1, y) - p(x + 1, y) - p(x, y - 1) - p(x, y + 1)).abs()
};
let mean = |inside: bool| {
let pts: Vec<(usize, usize)> = (1..h - 1).flat_map(|y| (1..w - 1).map(move |x| (x, y))).filter(|&(x, y)| hole[y * w + x] == inside).collect();
pts.iter().map(|&(x, y)| lap(&out, x, y)).sum::<f32>() / pts.len() as f32
};
assert!(mean(true) > 0.6 * mean(false), "fill detail {} against {}", mean(true), mean(false));
}
#[test]
fn patch_color_shifts_up_to_about_four_hundredths_per_step() {
// Content 0.4 brighter than where it lands (Photoshop's Patch, Color 3 and 10).
let from: Vec<f32> = (0..300).map(|i| 0.7 + 0.05 * ((i % 7) as f32 / 7.0)).collect();
let to: Vec<f32> = from.iter().map(|v| v - 0.4).collect();
let level = from.iter().sum::<f32>() / 300.0;
let shift = |c: u8| {
let gb = level_transform(1, &from, &to, color_amount(c));
level - from.iter().map(|v| gb[0].0 * v + gb[0].1).sum::<f32>() / 300.0
};
assert_eq!(shift(0), 0.0);
assert!((shift(3) - 0.12).abs() < 0.01, "{}", shift(3));
assert!((shift(10) - 0.4).abs() < 0.01, "{}", shift(10));
}
#[test]
fn variant_geometry() {
let img = vec![0.5f32; 10 * 6];
let ok = vec![true; 60];
let src = Src { w: 10, h: 6, ch: 1, img: &img, ok: &ok };
let v = variant(src, 90.0, 1.0, false);
let v = variant(src, 90.0, 1.0, false, &Interrupt::NONE).unwrap();
assert_eq!((v.w, v.h), (6, 10));
let v = variant(src, 0.0, 0.8, true);
let v = variant(src, 0.0, 0.8, true, &Interrupt::NONE).unwrap();
assert_eq!((v.w, v.h), (8, 5));
assert!(v.ok.iter().filter(|o| **o).count() > 20);
}
+596
View File
@@ -0,0 +1,596 @@
//! Direct (intensity-based) registration for Edit › Auto-Align Layers, for layers that nearly
//! coincide: a focus bracket, an exposure bracket, a burst. Feature matching
//! ([`crate::panorama`]) wants distinctive corners seen from two places; such layers are the same
//! view with a sub-pixel shift, a little scale (focus breathing) and rotation, and much of each
//! layer defocused, so there is often nothing to match and nothing to verify. Here the whole
//! overlap is the evidence: the pose that makes the warped target look like the reference.
//!
//! The target is registered to the reference coarse-to-fine on a Gaussian pyramid of the
//! luminance. The cost of a pose is the RMS of the difference between the reference and the
//! target warped by it, the mean difference removed (so exposure and tone changes don't count),
//! over the pixels both cover. Each level runs a bounded Nelder-Mead search whose simplex starts
//! one pixel of that level wide and stops at a tenth of one, so the coarse levels only hand the
//! next one a start within its pixel and the finest level searched settles sub-pixel. The pose
//! is resolution independent (shifts as fractions of the size, a scale, an angle), so a fit that
//! stops a few levels short of full resolution still applies at full resolution, and the cost
//! at full resolution, the dominant expense, is never paid.
//!
//! [`Pose`] is the transform searched: a similarity (shift, scale, rotation) about the layer's
//! centre, with aspect and shear for an affine fit and two perspective terms for a projective
//! one; [`Motion`] says which of them move. Everything is deterministic.
use crate::panorama::Motion;
use crate::photo_util::{par_map, par_rows2};
use crate::transform::Homography;
/// A layer's transform onto the reference, about the layer's centre: a similarity (shift, scale,
/// rotation); with `aspect` and `shear` an affine transform; with `px` and `py` a projective one.
/// The reference sits at [`Pose::IDENTITY`]; [`Pose::matrix`] gives it as a 3×3 homography.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Pose {
/// Shift, as a fraction of the width.
pub dx: f64,
/// Shift, as a fraction of the height.
pub dy: f64,
pub scale: f64,
/// Rotation in radians.
pub rot: f64,
/// Vertical over horizontal scale (1 = isotropic).
pub aspect: f64,
/// Horizontal shear per unit of height (0 = none).
pub shear: f64,
/// Perspective: the divisor `1 + px·u/w + py·v/h` over the centred pixel `(u, v)`.
pub px: f64,
pub py: f64,
}
impl Pose {
/// The number of parameters (the length of [`Pose::to_vec`]).
pub const N: usize = 8;
pub const IDENTITY: Pose = Pose { dx: 0.0, dy: 0.0, scale: 1.0, rot: 0.0, aspect: 1.0, shear: 0.0, px: 0.0, py: 0.0 };
/// The search box's half-width around the start, per parameter: 10 % of the layer in shift,
/// 10 % in scale, 5° in rotation, 5 % in aspect and shear, 5 % in each perspective term.
const SPAN: [f64; Pose::N] = [0.10, 0.10, 0.10, 0.087_266_462_599_716_47, 0.05, 0.05, 0.05, 0.05];
pub fn to_vec(self) -> [f64; Pose::N] {
[self.dx, self.dy, self.scale, self.rot, self.aspect, self.shear, self.px, self.py]
}
pub fn from_vec(v: &[f64; Pose::N]) -> Pose {
Pose { dx: v[0], dy: v[1], scale: v[2], rot: v[3], aspect: v[4], shear: v[5], px: v[6], py: v[7] }
}
/// Which parameters a search over `motion` may move: shifts, then scale and rotation, then
/// aspect and shear, then the perspective terms.
pub fn free(motion: Motion) -> [bool; Pose::N] {
match motion {
Motion::Translation => [true, true, false, false, false, false, false, false],
Motion::Euclidean => [true, true, false, true, false, false, false, false],
Motion::Similarity => [true, true, true, true, false, false, false, false],
Motion::Homography => [true; Pose::N],
}
}
/// The homography mapping the layer's pixels onto the reference's: the linear part is
/// `scale · R(rot) · [[1, shear], [0, aspect]]` about the centre, the perspective terms act on
/// the centred pixel; without them the last row is exactly `[0, 0, 1]`.
pub fn matrix(&self, w: usize, h: usize) -> Homography {
let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0);
let (c, s) = (self.rot.cos(), self.rot.sin());
let sc = self.scale;
let (a, b, d, e) = (sc * c, sc * (c * self.shear - s * self.aspect), sc * s, sc * (s * self.shear + c * self.aspect));
let (gx, gy) = (self.px / w as f64, self.py / h as f64);
// T(c) · [[a, b, t], [d, e, t'], [gx, gy, 1]] · T(−c), written out.
let (a2, b2, d2, e2) = (a + cx * gx, b + cx * gy, d + cy * gx, e + cy * gy);
let tx = cx + self.dx * w as f64 - (a2 * cx + b2 * cy);
let ty = cy + self.dy * h as f64 - (d2 * cx + e2 * cy);
Homography([a2, b2, tx, d2, e2, ty, gx, gy, 1.0 - gx * cx - gy * cy])
}
}
/// A luminance plane with, where the layer does not cover its whole area, its coverage.
pub struct Plane<'a> {
pub w: usize,
pub h: usize,
pub luma: &'a [f32],
pub valid: Option<&'a [bool]>,
}
/// The outcome of [`register`].
#[derive(Clone, Debug, PartialEq)]
pub struct Registration {
pub pose: Pose,
/// The pose as a homography of the target's pixels onto the reference's.
pub h: Homography,
/// The cost at the pose: the RMS of the mean-removed difference, at the finest level searched.
pub rms: f64,
/// Pixels of the finest level searched that both layers cover at the pose.
pub overlap: usize,
/// The correlation of the reference with the warped target over those pixels (Pearson, −1
/// to 1): how much of the reference the pose explains, whatever the exposure. Near 1 for a
/// bracket of one scene, near 0 for unrelated pictures; 0 without overlap or texture.
pub correlation: f64,
}
/// One pyramid level: the plane, its coverage and its size.
struct Lvl {
luma: Vec<f32>,
valid: Option<Vec<bool>>,
w: usize,
h: usize,
}
const K: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0];
/// Gaussian REDUCE of a plane and its coverage (5-tap binomial, clamped borders, phase-0
/// subsample); a reduced pixel is covered when more than half its support is.
fn reduce(l: &Lvl) -> Lvl {
let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2));
let cover: Vec<f32> = l.valid.as_ref().map(|v| v.iter().map(|b| *b as u8 as f32).collect()).unwrap_or_default();
let pass = |src: &[f32]| -> Vec<f32> {
let mut tmp = vec![0.0f32; w * l.h];
for (y, row) in tmp.chunks_mut(w).enumerate() {
let s = &src[y * l.w..(y + 1) * l.w];
for (x, o) in row.iter_mut().enumerate() {
*o = K.iter().enumerate().map(|(k, wt)| wt * s[(2 * x + k).saturating_sub(2).min(l.w - 1)]).sum();
}
}
let mut out = vec![0.0f32; w * h];
for (y, row) in out.chunks_mut(w).enumerate() {
for (k, wt) in K.iter().enumerate() {
let sy = (2 * y + k).saturating_sub(2).min(l.h - 1);
for (o, v) in row.iter_mut().zip(&tmp[sy * w..(sy + 1) * w]) {
*o += wt * v;
}
}
}
out
};
let luma = pass(&l.luma);
let valid = (!cover.is_empty()).then(|| pass(&cover).iter().map(|c| *c > 0.5).collect());
Lvl { luma, valid, w, h }
}
/// The search pyramid of a plane: level 0 is the plane, each next level half its size, while
/// the height exceeds 64 and the width 8.
fn levels(p: &Plane) -> Vec<Lvl> {
let mut out = vec![Lvl { luma: p.luma.to_vec(), valid: p.valid.map(<[bool]>::to_vec), w: p.w, h: p.h }];
while let Some(last) = out.last() {
if last.h <= 64 || last.w <= 8 {
break;
}
let next = reduce(last);
out.push(next);
}
out
}
/// The cubic B-spline (4 taps) at fraction `t`.
#[inline]
fn spline4(t: f64) -> [f64; 4] {
[
((-1.0 / 3.0 * t + 0.8) * t - 0.466_666_67) * t,
((t - 1.8) * t - 0.2) * t + 1.0,
((1.2 - t) * t + 0.8) * t,
((1.0 / 3.0 * t - 0.2) * t - 0.133_333_34) * t,
]
}
/// The source points along output row `y` under `inv`: `(x0, y0, dx, dy)` such that pixel `x`
/// reads `(x0 + dx·x, y0 + dy·x)`; `None` for a projective `inv`, handled pixel by pixel.
#[inline]
fn affine_row(inv: &Homography, y: f64) -> Option<(f64, f64, f64, f64)> {
let m = &inv.0;
(m[6] == 0.0 && m[7] == 0.0 && m[8] == 1.0).then(|| (m[1] * y + m[2], m[4] * y + m[5], m[0], m[3]))
}
/// `src` sampled at `(sx, sy)` with the cubic B-spline, edge-clamped.
#[inline]
fn sample(src: &[f32], w: usize, h: usize, sx: f64, sy: f64) -> f32 {
let (x0, y0) = (sx.floor(), sy.floor());
let wx = spline4(sx - x0);
let wy = spline4(sy - y0);
let (x0, y0) = (x0 as i64, y0 as i64);
let mut acc = 0.0f64;
for (j, wyj) in wy.iter().enumerate() {
let yy = (y0 + j as i64 - 1).clamp(0, h as i64 - 1) as usize;
let mut r = 0.0f64;
for (i, wxi) in wx.iter().enumerate() {
let xx = (x0 + i as i64 - 1).clamp(0, w as i64 - 1) as usize;
r += wxi * f64::from(src[yy * w + xx]);
}
acc += wyj * r;
}
acc as f32
}
/// Whether the target covers the source point (nearest pixel of its coverage).
#[inline]
fn covered(valid: Option<&[bool]>, w: usize, sx: f64, sy: f64) -> bool {
valid.is_none_or(|v| v[(sy + 0.5) as usize * w + (sx + 0.5) as usize])
}
/// The cost of `pose`: the RMS of `reference − target ∘ pose`, the mean removed, over the pixels
/// of the reference that both cover; 1e9 when fewer than 16 do. One row-parallel pass folds Σr,
/// Σt, Σr², Σt², Σrt and the count: rms = √((Σd² − (Σd)²/n) / n) with d = r − t, and the
/// correlation of r and t over the same pixels, also returned (0 when either has no spread).
fn cost(reference: &Lvl, target: &Lvl, pose: &Pose) -> (f64, usize, f64) {
let Some(inv) = pose.matrix(target.w, target.h).inverse() else { return (1e9, 0, 0.0) };
let (xmax, ymax) = ((target.w - 1) as f64, (target.h - 1) as f64);
let rows = par_map(reference.h, |y| {
let (mut sr, mut st, mut sr2, mut st2, mut srt, mut cnt) = (0.0f64, 0.0f64, 0.0f64, 0.0f64, 0.0f64, 0usize);
let yf = y as f64;
let aff = affine_row(&inv, yf);
let row = &reference.luma[y * reference.w..(y + 1) * reference.w];
for (x, &r) in row.iter().enumerate() {
if reference.valid.as_ref().is_some_and(|v| !v[y * reference.w + x]) {
continue;
}
let (sx, sy) = match aff {
Some((x0, y0, dx, dy)) => (x0 + dx * x as f64, y0 + dy * x as f64),
None => inv.apply(x as f64, yf),
};
let inside = sx >= 0.0 && sx <= xmax && sy >= 0.0 && sy <= ymax;
if !inside || !covered(target.valid.as_deref(), target.w, sx, sy) {
continue;
}
let (r, t) = (f64::from(r), f64::from(sample(&target.luma, target.w, target.h, sx, sy)));
sr += r;
st += t;
sr2 += r * r;
st2 += t * t;
srt += r * t;
cnt += 1;
}
(sr, st, sr2, st2, srt, cnt)
});
let (sr, st, sr2, st2, srt, cnt) =
rows.iter().fold((0.0, 0.0, 0.0, 0.0, 0.0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2, a.3 + b.3, a.4 + b.4, a.5 + b.5));
if cnt < 16 {
return (1e9, cnt, 0.0);
}
let n = cnt as f64;
// Central moments: Σ(r−r̄)², Σ(t−t̄)², Σ(r−r̄)(t−t̄).
let (vr, vt, cov) = ((sr2 - sr * sr / n).max(0.0), (st2 - st * st / n).max(0.0), srt - sr * st / n);
let rms = ((vr + vt - 2.0 * cov) / n).max(0.0).sqrt();
let correlation = if vr > 0.0 && vt > 0.0 { (cov / (vr * vt).sqrt()).clamp(-1.0, 1.0) } else { 0.0 };
(rms, cnt, correlation)
}
/// Full-resolution pixels a point at the layer's edge moves per unit of each parameter (the
/// worst case over the layer): the width and height for the shifts, the half-layer for scale
/// and rotation, the half-height for aspect and shear, a quarter-layer for the perspective terms.
fn param_gain(w: usize, h: usize) -> [f64; Pose::N] {
let (w, h) = (w as f64, h as f64);
let r = w.max(h) / 2.0;
[w, h, r, r, h / 2.0, h / 2.0, w / 4.0, h / 4.0]
}
/// The simplex's first step at a level: one pixel of that level.
const STEP_PX: f64 = 1.0;
/// The simplex's stopping size at a level: a tenth of a pixel of that level.
const TOL_PX: f64 = 0.1;
/// The search's schedule at pyramid level `lvl` (a pixel there is `2^lvl` full-resolution
/// pixels) over the parameters `free`: the first step and the stopping size of the simplex, per
/// parameter, in the parameter's units.
fn level_steps(free: &[usize], lvl: usize, w: usize, h: usize) -> (Vec<f64>, Vec<f64>) {
let gain = param_gain(w, h);
let px = (1u64 << lvl.min(60)) as f64;
(free.iter().map(|&k| STEP_PX * px / gain[k]).collect(), free.iter().map(|&k| TOL_PX * px / gain[k]).collect())
}
/// Nelder-Mead's stopping rule on a simplex sorted by `fv`: the values agree to 1e-4 relative
/// and every vertex lies within `tol[k]` of the best along each axis.
fn converged(simplex: &[Vec<f64>], fv: &[f64], tol: &[f64]) -> bool {
let n = tol.len();
let (Some(first), Some(last), Some(best)) = (fv.first(), fv.get(n), simplex.first()) else { return true };
if (last - first).abs() > 1e-4 * (1.0 + first.abs()) {
return false;
}
simplex[1..].iter().all(|v| (0..n).all(|k| (v[k] - best[k]).abs() <= tol[k]))
}
/// Bounded Nelder-Mead: minimises `f` over the box `[lo, hi]` from `x0`, the first simplex `x0`
/// moved by `step[k]` along each axis, until the vertices agree to 1e-4 relative in `f` and lie
/// within `tol[k]` of the best along every axis, or 200 iterations.
fn nelder_mead<F: Fn(&[f64]) -> f64>(f: &F, x0: &[f64], lo: &[f64], hi: &[f64], step: &[f64], tol: &[f64]) -> Vec<f64> {
let n = x0.len();
if n == 0 {
return Vec::new();
}
let clamp = |v: &mut [f64]| {
for k in 0..n {
v[k] = v[k].clamp(lo[k], hi[k]);
}
};
let mut simplex: Vec<Vec<f64>> = vec![x0.to_vec()];
for k in 0..n {
let mut v = x0.to_vec();
v[k] += step[k];
clamp(&mut v);
simplex.push(v);
}
let mut fv: Vec<f64> = simplex.iter().map(|v| f(v)).collect();
let (alpha, gamma, rho, sigma) = (1.0, 2.0, 0.5, 0.5);
for _ in 0..200 {
let mut idx: Vec<usize> = (0..=n).collect();
idx.sort_by(|&a, &b| fv[a].total_cmp(&fv[b]));
simplex = idx.iter().map(|&i| simplex[i].clone()).collect();
fv = idx.iter().map(|&i| fv[i]).collect();
if converged(&simplex, &fv, tol) {
break;
}
let mut c = vec![0.0; n];
for v in &simplex[..n] {
for k in 0..n {
c[k] += v[k] / n as f64;
}
}
let mut xr: Vec<f64> = (0..n).map(|k| c[k] + alpha * (c[k] - simplex[n][k])).collect();
clamp(&mut xr);
let fr = f(&xr);
if fr < fv[0] {
let mut xe: Vec<f64> = (0..n).map(|k| c[k] + gamma * (xr[k] - c[k])).collect();
clamp(&mut xe);
let fe = f(&xe);
if fe < fr {
(simplex[n], fv[n]) = (xe, fe);
} else {
(simplex[n], fv[n]) = (xr, fr);
}
} else if fr < fv[n - 1] {
(simplex[n], fv[n]) = (xr, fr);
} else {
let mut xc: Vec<f64> = (0..n).map(|k| c[k] + rho * (simplex[n][k] - c[k])).collect();
clamp(&mut xc);
let fc = f(&xc);
if fc < fv[n] {
(simplex[n], fv[n]) = (xc, fc);
} else {
let best = simplex[0].clone();
for (v, fvi) in simplex[1..].iter_mut().zip(&mut fv[1..]) {
for k in 0..n {
v[k] = best[k] + sigma * (v[k] - best[k]);
}
clamp(v);
*fvi = f(v);
}
}
}
}
let best = (0..=n).min_by(|&a, &b| fv[a].total_cmp(&fv[b])).unwrap_or(0);
simplex[best].clone()
}
/// Registers `target` to `reference` (planes of the same size) with the parameters `motion`
/// moves, from `init` (the previous layer's pose, or the identity), stopping `coarsen` levels
/// short of full resolution (at least one level is searched).
pub fn register(reference: &Plane, target: &Plane, motion: Motion, init: Pose, coarsen: usize) -> Registration {
let (w, h) = (target.w, target.h);
let pref = levels(reference);
let ptgt = levels(target);
let n = pref.len().min(ptgt.len());
let free: Vec<usize> = (0..Pose::N).filter(|&k| Pose::free(motion)[k]).collect();
let iv = init.to_vec();
let mut cur = iv;
let lo: Vec<f64> = free.iter().map(|&k| iv[k] - Pose::SPAN[k]).collect();
let hi: Vec<f64> = free.iter().map(|&k| iv[k] + Pose::SPAN[k]).collect();
let finest = coarsen.min(n.saturating_sub(1));
let (mut rms, mut overlap, mut correlation) = (1e9, 0, 0.0);
for lvl in (finest..n).rev() {
let (rl, tl) = (&pref[lvl], &ptgt[lvl]);
let snap = cur;
let f = |xf: &[f64]| -> f64 {
let mut v = snap;
for (k, &idx) in free.iter().enumerate() {
v[idx] = xf[k];
}
cost(rl, tl, &Pose::from_vec(&v)).0
};
let x0: Vec<f64> = free.iter().map(|&k| cur[k]).collect();
let (step, tol) = level_steps(&free, lvl, w, h);
let best = nelder_mead(&f, &x0, &lo, &hi, &step, &tol);
for (k, &idx) in free.iter().enumerate() {
cur[idx] = best[k];
}
(rms, overlap, correlation) = cost(rl, tl, &Pose::from_vec(&cur));
}
let pose = Pose::from_vec(&cur);
Registration { pose, h: pose.matrix(w, h), rms, overlap, correlation }
}
/// `src` (with its coverage) warped by `pose` into a plane of the same size with the cubic
/// B-spline, and the coverage of the result: the points that land inside the source, on pixels
/// it covers.
pub fn warp(src: &Plane, pose: &Pose) -> (Vec<f32>, Vec<bool>) {
let (w, h) = (src.w, src.h);
let mut out = vec![0.0f32; w * h];
let mut valid = vec![false; w * h];
let Some(inv) = pose.matrix(w, h).inverse() else { return (out, valid) };
let (xmax, ymax) = ((w - 1) as f64, (h - 1) as f64);
par_rows2(&mut out, &mut valid, w, |y, orow, vrow| {
let yf = y as f64;
let aff = affine_row(&inv, yf);
for (x, (o, v)) in orow.iter_mut().zip(vrow.iter_mut()).enumerate() {
let (sx, sy) = match aff {
Some((x0, y0, dx, dy)) => (x0 + dx * x as f64, y0 + dy * x as f64),
None => inv.apply(x as f64, yf),
};
let inside = sx >= 0.0 && sx <= xmax && sy >= 0.0 && sy <= ymax;
*v = inside && covered(src.valid, w, sx, sy);
if inside {
*o = sample(src.luma, w, h, sx, sy);
}
}
});
(out, valid)
}
#[cfg(test)]
mod tests {
use super::*;
/// A smooth random texture: a sum of a few sinusoids, so sub-pixel resampling is faithful.
fn texture(w: usize, h: usize, seed: u32) -> Vec<f32> {
let s = seed as f32;
(0..w * h)
.map(|i| {
let (x, y) = ((i % w) as f32, (i / w) as f32);
let v =
(x * 0.21 + s).sin() * (y * 0.17 - s).cos() + (x * 0.071 + y * 0.093 + s * 0.5).sin() * 0.7 + ((x * 0.33 - y * 0.29) * 1.3 + s).cos() * 0.4;
0.5 + 0.2 * v
})
.collect()
}
fn plane(w: usize, h: usize, luma: &[f32]) -> Plane<'_> {
Plane { w, h, luma, valid: None }
}
#[test]
fn pose_matrix_is_the_identity_at_the_identity_and_shifts_in_pixels() {
assert_eq!(Pose::IDENTITY.matrix(640, 480), Homography::IDENTITY);
let p = Pose { dx: 0.1, dy: -0.05, ..Pose::IDENTITY };
let (x, y) = p.matrix(200, 100).apply(50.0, 20.0);
assert!((x - 70.0).abs() < 1e-9 && (y - 15.0).abs() < 1e-9);
// Scale and rotation are about the centre.
let p = Pose { scale: 1.5, rot: 0.3, ..Pose::IDENTITY };
let (x, y) = p.matrix(200, 100).apply(100.0, 50.0);
assert!((x - 100.0).abs() < 1e-9 && (y - 50.0).abs() < 1e-9);
assert_eq!(Pose::from_vec(&p.to_vec()), p);
assert_eq!(Pose::free(Motion::Translation).iter().filter(|f| **f).count(), 2);
assert_eq!(Pose::free(Motion::Homography), [true; Pose::N]);
}
#[test]
fn warp_by_the_identity_is_exact_and_marks_coverage() {
let (w, h) = (40, 30);
let src = texture(w, h, 1);
let (o, v) = warp(&plane(w, h, &src), &Pose::IDENTITY);
assert!(o.iter().zip(&src).all(|(a, b)| (a - b).abs() < 1e-6));
assert!(v.iter().all(|b| *b));
// A shift of 10 px to the right leaves the left 10 columns uncovered.
let (_, v) = warp(&plane(w, h, &src), &Pose { dx: 10.0 / w as f64, ..Pose::IDENTITY });
assert!((0..h).all(|y| !v[y * w] && !v[y * w + 9] && v[y * w + 10]));
// The source's own coverage carries over.
let valid: Vec<bool> = (0..w * h).map(|i| i % w < 20).collect();
let (_, v) = warp(&Plane { w, h, luma: &src, valid: Some(&valid) }, &Pose::IDENTITY);
assert!(v[5 * w + 10] && !v[5 * w + 30]);
}
#[test]
fn cost_is_zero_at_the_truth_and_the_sentinel_without_overlap() {
let (w, h) = (96, 72);
let src = texture(w, h, 2);
let l = levels(&plane(w, h, &src));
assert!(cost(&l[0], &l[0], &Pose::IDENTITY).0 < 1e-9);
assert_eq!(cost(&l[0], &l[0], &Pose { dx: 2.0, ..Pose::IDENTITY }).0, 1e9);
// The mean is removed: a brighter copy costs nothing.
let bright: Vec<f32> = src.iter().map(|v| v + 0.2).collect();
let lb = levels(&plane(w, h, &bright));
assert!(cost(&l[0], &lb[0], &Pose::IDENTITY).0 < 1e-6);
assert!(cost(&l[0], &lb[0], &Pose { dx: 0.02, ..Pose::IDENTITY }).0 > 1e-3);
}
/// The correlation tells a fit from a non-fit whatever the exposure: a stop brighter copy of
/// the texture correlates fully at the truth (where the mean-removed RMS does not vanish),
/// another texture hardly at all, and a flat plane not at all.
#[test]
fn correlation_is_exposure_independent_and_low_for_unrelated_pictures() {
let (w, h) = (96, 72);
let src = texture(w, h, 2);
let l = levels(&plane(w, h, &src));
let doubled: Vec<f32> = src.iter().map(|v| v * 2.0).collect();
let ld = levels(&plane(w, h, &doubled));
let (rms, _, corr) = cost(&l[0], &ld[0], &Pose::IDENTITY);
assert!(rms > 0.05 && corr > 0.9999, "rms {rms} correlation {corr}");
let other = levels(&plane(w, h, &texture(w, h, 7)));
let (_, _, corr) = cost(&l[0], &other[0], &Pose::IDENTITY);
assert!(corr.abs() < 0.3, "unrelated textures correlate at {corr}");
let flat = levels(&plane(w, h, &vec![0.5; w * h]));
assert_eq!(cost(&l[0], &flat[0], &Pose::IDENTITY).2, 0.0);
let r = register(&plane(w, h, &src), &plane(w, h, &doubled), Motion::Similarity, Pose::IDENTITY, 0);
assert!(r.correlation > 0.999, "{r:?}");
}
#[test]
fn pyramid_stops_above_64_rows() {
let l = levels(&plane(40, 300, &vec![0.25; 40 * 300]));
assert_eq!(l.iter().map(|l| (l.w, l.h)).collect::<Vec<_>>(), vec![(40, 300), (20, 150), (10, 75), (5, 38)]);
assert!(l.iter().all(|l| l.luma.iter().all(|v| (v - 0.25).abs() < 1e-6)));
let valid: Vec<bool> = (0..40 * 300).map(|i| i % 40 < 20).collect();
let l = levels(&Plane { w: 40, h: 300, luma: &vec![0.25; 40 * 300], valid: Some(&valid) });
let v = l[2].valid.as_ref().unwrap();
assert!(v[10 * 10 + 2] && !v[10 * 10 + 8]);
}
#[test]
fn nelder_mead_finds_the_minimum_of_a_bowl() {
let f = |x: &[f64]| (x[0] - 0.3).powi(2) + 2.0 * (x[1] + 0.2).powi(2);
let r = nelder_mead(&f, &[0.0, 0.0], &[-1.0, -1.0], &[1.0, 1.0], &[0.1, 0.1], &[1e-6, 1e-6]);
assert!((r[0] - 0.3).abs() < 1e-4 && (r[1] + 0.2).abs() < 1e-4, "{r:?}");
// The box binds.
let r = nelder_mead(&f, &[0.0, 0.0], &[-1.0, -1.0], &[0.1, 1.0], &[0.1, 0.1], &[1e-6, 1e-6]);
assert!((r[0] - 0.1).abs() < 1e-6, "{r:?}");
assert!(nelder_mead(&f, &[], &[], &[], &[], &[]).is_empty());
let (step, tol) = level_steps(&[0, 2], 3, 8000, 6000);
assert!((step[0] * 8000.0 - 8.0).abs() < 1e-9 && (tol[1] * 4000.0 - 0.8).abs() < 1e-9);
}
/// A layer shifted, scaled and rotated a little registers back to within a tenth of a pixel
/// at every motion model that contains the truth, with or without coarsening.
#[test]
fn registers_a_similarity_to_a_tenth_of_a_pixel() {
let (w, h) = (320, 240);
let reference = texture(w, h, 3);
let truth = Pose { dx: 3.3 / w as f64, dy: -2.1 / h as f64, scale: 1.012, rot: 0.6f64.to_radians(), ..Pose::IDENTITY };
// The pose maps the target's pixels onto the reference's: target(u) = reference(M u).
let m = truth.matrix(w, h);
let target: Vec<f32> = (0..w * h)
.map(|i| {
let (x, y) = m.apply((i % w) as f64, (i / w) as f64);
sample(&reference, w, h, x.clamp(0.0, (w - 1) as f64), y.clamp(0.0, (h - 1) as f64))
})
.collect();
for (motion, coarsen) in [(Motion::Similarity, 0), (Motion::Similarity, 1), (Motion::Homography, 0)] {
let r = register(&plane(w, h, &reference), &plane(w, h, &target), motion, Pose::IDENTITY, coarsen);
let (tx, ty) = truth.matrix(w, h).apply(0.0, 0.0);
let (rx, ry) = r.h.apply(0.0, 0.0);
let corner = ((tx - rx).hypot(ty - ry)).max({
let (tx, ty) = truth.matrix(w, h).apply(w as f64, h as f64);
let (rx, ry) = r.h.apply(w as f64, h as f64);
(tx - rx).hypot(ty - ry)
});
assert!(corner < 0.1 * (1 << coarsen) as f64 + 0.05, "{motion:?} coarsen {coarsen}: corners off by {corner} px, {:?}", r.pose);
let searched = (w >> coarsen) * (h >> coarsen);
assert!(r.rms < 0.01 && r.overlap > searched / 2, "{motion:?}: rms {} overlap {} of {searched}", r.rms, r.overlap);
}
// Translation only: the shift is found, the rest stays put.
let t = Pose { dx: 4.0 / w as f64, dy: 3.0 / h as f64, ..Pose::IDENTITY };
let target: Vec<f32> = (0..w * h)
.map(|i| sample(&reference, w, h, ((i % w) as f64 + 4.0).clamp(0.0, (w - 1) as f64), ((i / w) as f64 + 3.0).clamp(0.0, (h - 1) as f64)))
.collect();
let r = register(&plane(w, h, &reference), &plane(w, h, &target), Motion::Translation, Pose::IDENTITY, 0);
assert!(((r.pose.dx - t.dx) * w as f64).abs() < 0.1 && ((r.pose.dy - t.dy) * h as f64).abs() < 0.1, "{:?}", r.pose);
assert_eq!((r.pose.scale, r.pose.rot), (1.0, 0.0));
}
/// Only the covered part counts: a target whose right half is garbage still registers on
/// its left half when its coverage says so.
#[test]
fn coverage_keeps_uncovered_pixels_out_of_the_fit() {
let (w, h) = (320, 240);
let reference = texture(w, h, 4);
let mut target: Vec<f32> = (0..w * h).map(|i| sample(&reference, w, h, ((i % w) as f64 + 2.5).clamp(0.0, (w - 1) as f64), (i / w) as f64)).collect();
let valid: Vec<bool> = (0..w * h).map(|i| i % w < w / 2).collect();
for (i, v) in target.iter_mut().enumerate() {
if !valid[i] {
*v = ((i * 7919) % 1000) as f32 / 1000.0;
}
}
let r = register(&plane(w, h, &reference), &Plane { w, h, luma: &target, valid: Some(&valid) }, Motion::Translation, Pose::IDENTITY, 0);
assert!((r.pose.dx * w as f64 - 2.5).abs() < 0.1, "{:?}", r.pose);
assert!(r.overlap < w * h / 2 + w && r.overlap > w * h / 3);
}
}
+71 -10
View File
@@ -17,6 +17,8 @@ pub struct CameraInfo {
pub focal_length: Option<f64>,
/// 35 mm-equivalent focal length in millimetres.
pub focal_length_35mm: Option<f64>,
/// DateTimeOriginal as stored (`YYYY:MM:DD HH:MM:SS`).
pub date_taken: Option<String>,
}
impl CameraInfo {
@@ -35,11 +37,11 @@ struct Tiff<'a> {
impl Tiff<'_> {
fn u16(&self, o: usize) -> Option<u16> {
let s = self.b.get(o..o + 2)?;
let s = self.b.get(o..o.checked_add(2)?)?;
Some(if self.le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) })
}
fn u32(&self, o: usize) -> Option<u32> {
let s = self.b.get(o..o + 4)?;
let s = self.b.get(o..o.checked_add(4)?)?;
let a = [s[0], s[1], s[2], s[3]];
Some(if self.le { u32::from_le_bytes(a) } else { u32::from_be_bytes(a) })
}
@@ -48,20 +50,25 @@ impl Tiff<'_> {
let Some(n) = self.u16(off) else { return Vec::new() };
(0..n as usize)
.filter_map(|k| {
let e = off + 2 + k * 12;
Some((self.u16(e)?, self.u16(e + 2)?, self.u32(e + 4)?, e + 8))
// Checked: offsets come from the file, and usize is 32 bits on wasm.
let e = off.checked_add(2)?.checked_add(k * 12)?;
Some((self.u16(e)?, self.u16(e.checked_add(2)?)?, self.u32(e.checked_add(4)?)?, e.checked_add(8)?))
})
.collect()
}
fn data_at(&self, typ: u16, count: u32, field: usize) -> Option<usize> {
let size = match typ {
1 | 2 | 6 | 7 => 1,
1 | 2 | 6 | 7 => 1usize,
3 | 8 => 2,
4 | 9 | 11 => 4,
5 | 10 | 12 => 8,
_ => return None,
} * count as usize;
if size <= 4 { Some(field) } else { self.u32(field).map(|v| v as usize) }
}
.checked_mul(usize::try_from(count).ok()?)?;
let at = if size <= 4 { field } else { usize::try_from(self.u32(field)?).ok()? };
// The whole value must lie inside the payload, not just its first element.
self.b.get(at..at.checked_add(size)?)?;
Some(at)
}
fn number(&self, typ: u16, count: u32, field: usize) -> Option<f64> {
let at = self.data_at(typ, count, field)?;
@@ -69,11 +76,11 @@ impl Tiff<'_> {
3 => self.u16(at).map(f64::from),
4 => self.u32(at).map(f64::from),
5 => {
let (n, d) = (self.u32(at)?, self.u32(at + 4)?);
let (n, d) = (self.u32(at)?, self.u32(at.checked_add(4)?)?);
(d != 0).then(|| n as f64 / d as f64)
}
10 => {
let (n, d) = (self.u32(at)? as i32, self.u32(at + 4)? as i32);
let (n, d) = (self.u32(at)? as i32, self.u32(at.checked_add(4)?)? as i32);
(d != 0).then(|| n as f64 / d as f64)
}
_ => None,
@@ -84,7 +91,7 @@ impl Tiff<'_> {
return None;
}
let at = self.data_at(typ, count, field)?;
let s = self.b.get(at..at + count as usize)?;
let s = self.b.get(at..at.checked_add(usize::try_from(count).ok()?)?)?;
let s = String::from_utf8_lossy(s).trim_end_matches('\0').trim().to_string();
(!s.is_empty()).then_some(s)
}
@@ -118,6 +125,7 @@ pub fn read(exif: &[u8]) -> CameraInfo {
0x920A => info.focal_length = t.number(typ, count, field),
0xA405 => info.focal_length_35mm = t.number(typ, count, field).filter(|v| *v > 0.0),
0xA434 => info.lens = t.text(typ, count, field),
0x9003 => info.date_taken = t.text(typ, count, field),
0x8769 => {
if let Some(p) = t.u32(field) {
queue.push(p as usize);
@@ -161,6 +169,9 @@ pub fn build(info: &CameraInfo) -> Vec<u8> {
if let Some(v) = info.iso {
exif.push((0x8827, 3, 1, (v as u16).to_le_bytes().to_vec()));
}
if let Some(s) = &info.date_taken {
exif.push((0x9003, 2, s.len() as u32 + 1, text(s)));
}
if let Some(v) = info.focal_length {
exif.push((0x920A, 5, 1, rational(v)));
}
@@ -224,6 +235,7 @@ mod tests {
iso: Some(200.0),
focal_length: Some(35.0),
focal_length_35mm: Some(52.0),
date_taken: Some("2024:02:17 12:40:19".into()),
};
let b = build(&info);
let r = read(&b);
@@ -237,4 +249,53 @@ mod tests {
let _ = read(&b[..cut]);
}
}
/// Hostile payloads: huge counts, offsets near `u32::MAX`, self-referencing IFDs and random
/// bytes read as `None` fields instead of panicking or overflowing (usize is 32 bits on wasm).
#[test]
fn hostile_payloads_never_panic() {
let entry = |tag: u16, typ: u16, count: u32, value: u32| {
let mut e = tag.to_le_bytes().to_vec();
e.extend_from_slice(&typ.to_le_bytes());
e.extend_from_slice(&count.to_le_bytes());
e.extend_from_slice(&value.to_le_bytes());
e
};
let mut b = b"II*\0".to_vec();
b.extend_from_slice(&8u32.to_le_bytes());
let entries = [
entry(0x010F, 2, u32::MAX, 8), // Make: count far past the end
entry(0x0110, 2, 16, u32::MAX - 1), // Model: offset at the top of the range
entry(0x829A, 5, u32::MAX, 20), // ExposureTime: count overflows the size
entry(0x829D, 5, 1, u32::MAX - 3), // FNumber: rational straddles u32::MAX
entry(0x9003, 2, 0x4000_0000, 8), // DateTimeOriginal: size overflow on 32 bits
entry(0x8769, 4, 1, 8), // Exif IFD pointing back at IFD0
entry(0x8769, 4, 1, u32::MAX), // ... and past the end
];
b.extend_from_slice(&(entries.len() as u16 + 3).to_le_bytes()); // claims more entries than exist
for e in entries {
b.extend_from_slice(&e);
}
assert_eq!(read(&b), CameraInfo::default());
let mut be = b"MM\0*".to_vec();
be.extend_from_slice(&u32::MAX.to_be_bytes());
assert_eq!(read(&be), CameraInfo::default());
// Deterministic noise behind a valid header, and every truncation of a real payload.
let mut x = 0x2545_F491u32;
for _ in 0..200 {
let mut n = b"II*\0\x08\0\0\0".to_vec();
for _ in 0..96 {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
n.push(x as u8);
}
let _ = read(&n);
}
let good =
build(&CameraInfo { make: Some("Make".into()), date_taken: Some("2024:02:17 12:40:19".into()), exposure_time: Some(0.004), ..Default::default() });
for cut in 0..good.len() {
let _ = read(&good[..cut]);
}
}
}
+156 -30
View File
@@ -8,10 +8,20 @@
use photocraft_geom::Rect;
use crate::fxutil::{MAXC, add_sample_premul, gauss_blur_n, premul_window, smoothstep, unpremul_px, xy};
use crate::image::Image;
mod spin_plan;
use crate::fxutil::{MAXC, add_sample_premul, gauss_blur_n, gauss_box_radii, premul_window, smoothstep, unpremul_px, xy};
use crate::image::{Image, premultiply};
use crate::{BlurPath, Ctx, FieldPin, IrisPin, SpinPin};
#[cfg(test)]
#[path = "tests_iris.rs"]
mod tests;
#[cfg(test)]
#[path = "tests_tilt_shift.rs"]
mod tilt_shift_tests;
/// Gaussian σ for a gallery blur amount in px.
fn sigma_of(blur: f32) -> f32 {
blur.clamp(0.0, 500.0) * 0.6
@@ -25,17 +35,27 @@ pub(crate) fn reach(blur: f32) -> f32 {
const LEVELS: usize = 6;
/// Blurs `src` over `out` with a per-pixel σ (`sigma(x, y)`, ≤ `smax`).
fn variable_blur(src: &Image, out: Rect, ctx: &Ctx, smax: f32, sigma: impl Fn(f32, f32) -> f32) -> Vec<f32> {
fn variable_blur(src: &Image, out: Rect, ctx: &Ctx, smax: f32, trim_levels: bool, sigma: impl Fn(f32, f32) -> f32) -> Vec<f32> {
let n = src.ch;
if n == 0 || out.is_empty() {
return Vec::new();
}
if smax < 0.3 {
return src.crop(out);
}
let win = src.rect;
let (ww, wh) = (win.width() as usize, win.height() as usize);
let (ow, oh) = (out.width() as usize, out.height() as usize);
let Some(row_len) = ww.checked_mul(n).filter(|&len| len > 0) else { return Vec::new() };
let Some(source_len) = row_len.checked_mul(wh) else { return Vec::new() };
let Some(pixels) = ow.checked_mul(oh) else { return Vec::new() };
let Some(samples) = pixels.checked_mul(n) else { return Vec::new() };
if trim_levels && src.data.len() != source_len {
return Vec::new();
}
// Level σs: 0, then smax / 2^(LEVELS-1) … smax.
let lv: Vec<f32> = std::iter::once(0.0).chain((0..LEVELS).map(|k| smax / 2f32.powi((LEVELS - 1 - k) as i32))).collect();
let sig: Vec<f32> = (0..ow * oh)
let sig: Vec<f32> = (0..pixels)
.map(|i| {
let (x, y) = xy(out, i);
sigma(x as f32 + 0.5, y as f32 + 0.5).clamp(0.0, smax)
@@ -54,20 +74,49 @@ fn variable_blur(src: &Image, out: Rect, ctx: &Ctx, smax: f32, sigma: impl Fn(f3
0.0
}
};
let p = premul_window(src, win, ctx.alpha);
let mut acc = vec![0.0f32; ow * oh * n];
let p = if trim_levels {
// The window is exactly src.rect: read interleaved channels together,
// retaining the same multiplication and alpha order as premul_window.
let mut p = src.data.clone();
premultiply(&mut p, n, ctx.alpha);
p
} else {
premul_window(src, win, ctx.alpha)
};
let mut acc = vec![0.0f32; samples];
let mut buf = Vec::new();
for (k, &lvk) in lv.iter().enumerate() {
if !sig.iter().any(|&s| weight(k, s) > 0.0) {
continue;
}
let level: &[f32] = if k == 0 {
&p
let (level, lw): (&[f32], usize) = if k == 0 {
(&p, ww)
} else {
// Iris and Tilt-Shift opt in. Each level needs its own box-cascade reach,
// not the maximum blur's trailing halo. Keep the original top/left:
// moving the running sums' start changes floating-point cancellation.
let trim = trim_levels && win.intersect(&out) == out;
let reach = if !trim || lvk < 0.3 { 0 } else { gauss_box_radii(lvk).iter().sum::<usize>() };
let reach = i32::try_from(reach).unwrap_or(i32::MAX);
let lw = if trim { (i64::from(out.x1.saturating_add(reach).min(win.x1)) - i64::from(win.x0)) as usize } else { ww };
let lh = if trim { (i64::from(out.y1.saturating_add(reach).min(win.y1)) - i64::from(win.y0)) as usize } else { wh };
buf.clear();
buf.extend_from_slice(&p);
gauss_blur_n(&mut buf, ww, wh, n, lvk);
&buf
if buf.capacity() == 0 {
// Match the old single full-window allocation. Row appends must
// not geometrically grow the capacity beyond that window.
buf.reserve_exact(p.len());
}
if trim {
for row in p.chunks_exact(row_len).take(lh) {
if let Some(row) = row.get(..lw * n) {
buf.extend_from_slice(row);
}
}
} else {
buf.extend_from_slice(&p);
}
gauss_blur_n(&mut buf, lw, lh, n, lvk);
(&buf, lw)
};
for (i, &s) in sig.iter().enumerate() {
let wk = weight(k, s);
@@ -75,9 +124,11 @@ fn variable_blur(src: &Image, out: Rect, ctx: &Ctx, smax: f32, sigma: impl Fn(f3
continue;
}
let (x, y) = xy(out, i);
let o = (((y - win.y0) as usize) * ww + (x - win.x0) as usize) * n;
for c in 0..n {
acc[i * n + c] += level[o + c] * wk;
let o = (((y - win.y0) as usize) * lw + (x - win.x0) as usize) * n;
if let (Some(dst), Some(px)) = (acc.get_mut(i * n..(i + 1) * n), level.get(o..o + n)) {
for (dst, px) in dst.iter_mut().zip(px) {
*dst += px * wk;
}
}
}
}
@@ -101,9 +152,10 @@ pub(crate) fn tilt_shift(src: &Image, out: Rect, ctx: &Ctx, blur: f32, centre: (
// Band normal (the band runs along `angle`).
let (s, c) = angle.to_radians().sin_cos();
let (nx, ny) = (s, c);
let smax = sigma_of(blur);
// A NaN amount must not become the upper bound of f32::clamp below.
let smax = sigma_of(blur).max(0.0);
let (f0, f1) = (focus.max(0.0), focus.max(0.0) + transition.max(1e-3));
variable_blur(src, out, ctx, smax, |x, y| {
variable_blur(src, out, ctx, smax, true, |x, y| {
let d = ((x - cx) * nx + (y - cy) * ny).abs() / ss;
smax * smoothstep(f0, f1, d)
})
@@ -128,20 +180,74 @@ fn pin_distance(x: f32, y: f32, b: Rect, px: f32, py: f32, rx: f32, ry: f32, ang
pub(crate) fn iris(src: &Image, out: Rect, ctx: &Ctx, pins: &[IrisPin]) -> Vec<f32> {
let b = ctx.bounds;
let smax = pins.iter().map(|p| sigma_of(p.blur)).fold(0.0, f32::max);
if pins.is_empty() {
if pins.is_empty() || smax < 0.3 {
return src.crop(out);
}
variable_blur(src, out, ctx, smax, |x, y| {
pins.iter()
.map(|p| {
let m = 2.0 + p.roundness.clamp(0.0, 100.0) / 100.0 * 6.0;
let (e, _, _) = pin_distance(x, y, b, p.x, p.y, p.radius_x, p.radius_y, p.angle, m);
sigma_of(p.blur) * smoothstep(p.feather.clamp(0.0, 0.999), 1.0, e)
})
.fold(f32::MAX, f32::min)
// Small immutable per-tile preparation; allocation failure retains the
// same arithmetic without the table. No additional image-sized cache.
let mut prepared = Vec::new();
let prepared = if prepared.try_reserve_exact(pins.len()).is_ok() {
prepared.extend(pins.iter().map(|p| PreparedIris::new(p, b)));
Some(prepared)
} else {
None
};
variable_blur(src, out, ctx, smax, true, |x, y| {
if let Some(prepared) = &prepared {
prepared.iter().map(|p| p.sigma(x, y)).fold(f32::MAX, f32::min)
} else {
pins.iter().map(|p| PreparedIris::new(p, b).sigma(x, y)).fold(f32::MAX, f32::min)
}
})
}
struct PreparedIris {
cx: f32,
cy: f32,
rx: f32,
ry: f32,
sin: f32,
cos: f32,
exponent: f32,
feather: f32,
blur: f32,
}
impl PreparedIris {
fn new(p: &IrisPin, b: Rect) -> Self {
let ss = short_side(b);
let angle = if p.angle.is_finite() { p.angle } else { 0.0 };
let (sin, cos) = angle.to_radians().sin_cos();
Self {
cx: b.x0 as f32 + p.x * b.width() as f32,
cy: b.y0 as f32 + p.y * b.height() as f32,
rx: p.radius_x.max(1e-3) * ss,
ry: p.radius_y.max(1e-3) * ss,
sin,
cos,
exponent: 2.0 + p.roundness.clamp(0.0, 100.0) / 100.0 * 6.0,
feather: p.feather.clamp(0.0, 0.999),
blur: sigma_of(p.blur),
}
}
fn sigma(&self, x: f32, y: f32) -> f32 {
let (dx, dy) = (x - self.cx, y - self.cy);
let (u, v) = ((dx * self.cos + dy * self.sin) / self.rx, (-dx * self.sin + dy * self.cos) / self.ry);
// Outside the normalized bounding square, the superellipse distance
// is at least one. The falloff is saturated: no sqrt/powf is needed.
let e = if u.abs() >= 1.0 || v.abs() >= 1.0 {
f32::INFINITY
} else if (self.exponent - 2.0).abs() < 1e-3 {
(u * u + v * v).sqrt()
} else {
(u.abs().powf(self.exponent) + v.abs().powf(self.exponent)).powf(1.0 / self.exponent)
};
let e = if e.is_finite() { e } else { f32::INFINITY };
self.blur * smoothstep(self.feather, 1.0, e)
}
}
/// Field Blur: blur amounts at pins, interpolated by inverse squared distance.
pub(crate) fn field(src: &Image, out: Rect, ctx: &Ctx, pins: &[FieldPin]) -> Vec<f32> {
let b = ctx.bounds;
@@ -151,7 +257,7 @@ pub(crate) fn field(src: &Image, out: Rect, ctx: &Ctx, pins: &[FieldPin]) -> Vec
let smax = pins.iter().map(|p| sigma_of(p.blur)).fold(0.0, f32::max);
let pts: Vec<(f32, f32, f32)> =
pins.iter().map(|p| (b.x0 as f32 + p.x * b.width() as f32, b.y0 as f32 + p.y * b.height() as f32, sigma_of(p.blur))).collect();
variable_blur(src, out, ctx, smax, |x, y| {
variable_blur(src, out, ctx, smax, false, |x, y| {
let (mut ws, mut s) = (0.0f32, 0.0f32);
for &(px, py, sg) in &pts {
let w = 1.0 / ((x - px).powi(2) + (y - py).powi(2) + 1.0);
@@ -165,7 +271,18 @@ pub(crate) fn field(src: &Image, out: Rect, ctx: &Ctx, pins: &[FieldPin]) -> Vec
/// Spin Blur: content inside each ellipse is blurred along arcs about its
/// centre (`blur_angle` degrees of rotation), feathered at the rim.
pub(crate) fn spin(src: &Image, out: Rect, ctx: &Ctx, pins: &[SpinPin]) -> Vec<f32> {
let n = src.ch;
match src.ch {
1 => spin_impl::<1>(src, out, ctx, pins, true),
2 => spin_impl::<2>(src, out, ctx, pins, true),
3 => spin_impl::<3>(src, out, ctx, pins, true),
4 => spin_impl::<4>(src, out, ctx, pins, true),
5 => spin_impl::<5>(src, out, ctx, pins, true),
_ => spin_impl::<0>(src, out, ctx, pins, true),
}
}
fn spin_impl<const N: usize>(src: &Image, out: Rect, ctx: &Ctx, pins: &[SpinPin], prepare: bool) -> Vec<f32> {
let n = if N == 0 { src.ch } else { N };
let b = ctx.bounds;
let ss = short_side(b);
let mut res = src.crop(out);
@@ -173,11 +290,12 @@ pub(crate) fn spin(src: &Image, out: Rect, ctx: &Ctx, pins: &[SpinPin]) -> Vec<f
if clip.is_empty() {
return res;
}
let plans = prepare.then(|| spin_plan::prepare(pins)).flatten();
let mut acc = [0.0f32; MAXC];
for (i, px) in res.chunks_exact_mut(n).enumerate() {
let (x, y) = xy(out, i);
let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
for p in pins {
for (pi, p) in pins.iter().enumerate() {
let (e, u, v) = pin_distance(fx, fy, b, p.x, p.y, p.radius_x, p.radius_y, p.angle, 2.0);
if !e.is_finite() || e >= 1.0 {
continue;
@@ -189,15 +307,20 @@ pub(crate) fn spin(src: &Image, out: Rect, ctx: &Ctx, pins: &[SpinPin]) -> Vec<f
let (cx, cy) = (b.x0 as f32 + p.x * b.width() as f32, b.y0 as f32 + p.y * b.height() as f32);
let angle_deg = if p.angle.is_finite() { p.angle } else { 0.0 };
let (sa, ca) = angle_deg.to_radians().sin_cos();
let rotations = plans.as_ref().and_then(|plans| plans.get(pi)).and_then(|plan| plan.rotations(m));
acc[..n].fill(0.0);
for j in 0..m {
let phi = theta * (j as f32 / (m - 1) as f32 - 0.5);
let (sp, cp) = phi.sin_cos();
let (sp, cp) = rotations.and_then(|table| table.get(j)).copied().unwrap_or_else(|| phi.sin_cos());
// Rotate in the ellipse's normalized space, then map back.
let (ru, rv) = (u * cp - v * sp, u * sp + v * cp);
let (lu, lv) = (ru * p.radius_x * ss, rv * p.radius_y * ss);
let (sx, sy) = (cx + lu * ca - lv * sa, cy + lu * sa + lv * ca);
add_sample_premul(src, sx, sy, clip, ctx.alpha, &mut acc[..n]);
if N == 0 {
add_sample_premul(src, sx, sy, clip, ctx.alpha, &mut acc[..n]);
} else {
spin_plan::sample::<N>(src, sx, sy, clip, ctx.alpha, &mut acc);
}
}
for v in acc.iter_mut().take(n) {
*v /= m as f32;
@@ -277,3 +400,6 @@ pub(crate) fn path(src: &Image, out: Rect, ctx: &Ctx, paths: &[BlurPath]) -> Vec
}
res
}
#[cfg(test)]
mod prepared_spin_tests;
@@ -0,0 +1,59 @@
use super::*;
use photocraft_color::{ColorMode, PixelFormat, SampleType};
#[test]
fn all_rotation_tables_keep_the_direct_bits() {
for angle in [0.0, 0.1, 15.0, 73.7, 180.0, 360.0, f32::NAN, f32::INFINITY] {
let p = SpinPin { blur_angle: angle, ..Default::default() };
let plans = spin_plan::prepare(&[p]).unwrap();
let theta = angle.clamp(0.0, 360.0).to_radians();
for count in 2..=64 {
for j in 0..count {
let phi = theta * (j as f32 / (count - 1) as f32 - 0.5);
let (a, b) = phi.sin_cos();
let (c, d) = plans[0].rotation(count, j).unwrap();
assert_eq!((a.to_bits(), b.to_bits()), (c.to_bits(), d.to_bits()));
}
}
}
assert!(spin_plan::prepare(&vec![SpinPin::default(); 121]).is_none());
}
#[test]
fn prepared_spin_matches_the_original_kernel() {
let bounds = Rect::new(-17, -11, 58, 45);
for mode in [
ColorMode::Rgb,
ColorMode::Grayscale,
ColorMode::Cmyk,
ColorMode::Lab,
ColorMode::Bitmap,
ColorMode::Duotone,
ColorMode::Indexed,
ColorMode::Multichannel,
] {
for alpha in [false, true] {
let n = PixelFormat::new(mode, SampleType::F32, alpha).channels();
let ctx = Ctx { bounds, mode, alpha };
let mut src = Image::new(bounds, n);
for (i, v) in src.data.iter_mut().enumerate() {
*v = ((i * 71 + i / n * 107) % 65536) as f32 / 65535.0;
}
for (i, px) in src.data.chunks_exact_mut(n).enumerate() {
if i % 11 == 0 {
px[n - 1] = 0.0;
}
}
for angle in [0.0, 0.1, 15.0, 91.0, 360.0, f32::NAN] {
let pins = [
SpinPin { x: 0.2, y: 0.3, radius_x: 0.25, radius_y: 0.5, angle: 31.0, blur_angle: angle },
SpinPin { x: 0.7, y: 0.6, radius_x: 0.8, radius_y: 0.6, angle: -15.0, blur_angle: angle },
];
let out = Rect::new(-19, -8, 55, 49);
let a = spin(&src, out, &ctx, &pins);
let b = spin_impl::<0>(&src, out, &ctx, &pins, false);
let first = a.iter().zip(&b).position(|(a, b)| a.to_bits() != b.to_bits());
assert_eq!(first, None, "{mode:?} alpha {alpha} angle {angle}");
}
}
}
}
+76
View File
@@ -0,0 +1,76 @@
//! All possible sample counts share a bounded rotation table per pin.
use crate::SpinPin;
pub(super) struct Plan {
rotations: Vec<(f32, f32)>,
}
impl Plan {
#[cfg(test)]
pub(super) fn rotation(&self, count: usize, sample: usize) -> Option<(f32, f32)> {
self.rotations(count)?.get(sample).copied()
}
pub(super) fn rotations(&self, count: usize) -> Option<&[(f32, f32)]> {
if !(2..=64).contains(&count) {
return None;
}
let start = count.checked_mul(count - 1)?.checked_div(2)?.checked_sub(1)?;
self.rotations.get(start..start.checked_add(count)?)
}
}
pub(super) fn prepare(pins: &[SpinPin]) -> Option<Vec<Plan>> {
// Under 2 MiB, even for 120 overlapping pins. Larger lists keep direct sampling.
if pins.len() > 120 {
return None;
}
let mut plans = Vec::new();
plans.try_reserve_exact(pins.len()).ok()?;
for p in pins {
let theta = p.blur_angle.clamp(0.0, 360.0).to_radians();
let mut rotations = Vec::new();
rotations.try_reserve_exact(2079).ok()?;
for count in 2..=64 {
for j in 0..count {
let phi = theta * (j as f32 / (count - 1) as f32 - 0.5);
rotations.push(phi.sin_cos());
}
}
plans.push(Plan { rotations });
}
Some(plans)
}
/// Fixed channels keep the bilinear accumulators in registers. Tap and multiply order
/// stay identical to add_sample_premul; alpha is still multiplied by the tap weight first.
pub(super) fn sample<const N: usize>(src: &crate::image::Image, x: f32, y: f32, clip: photocraft_geom::Rect, alpha: bool, acc: &mut [f32; 8]) {
if !x.is_finite() || !y.is_finite() || clip.is_empty() {
return;
}
let fx = (x - 0.5).clamp(clip.x0 as f32, (clip.x1 - 1) as f32);
let fy = (y - 0.5).clamp(clip.y0 as f32, (clip.y1 - 1) as f32);
let (x0, y0) = (fx.floor() as i32, fy.floor() as i32);
let (x1, y1) = ((x0 + 1).min(clip.x1 - 1), (y0 + 1).min(clip.y1 - 1));
let (ax, ay) = (fx - x0 as f32, fy - y0 as f32);
let w = src.rect.width() as usize;
let idx = |xx: i32, yy: i32| ((yy - src.rect.y0) as usize * w + (xx - src.rect.x0) as usize) * N;
for (i, k) in [(idx(x0, y0), (1.0 - ax) * (1.0 - ay)), (idx(x1, y0), ax * (1.0 - ay)), (idx(x0, y1), (1.0 - ax) * ay), (idx(x1, y1), ax * ay)] {
if k <= 0.0 {
continue;
}
let Some(px) = src.data.get(i..i + N).and_then(|s| s.first_chunk::<N>()) else {
return;
};
let a = if alpha { px.get(N - 1).copied().unwrap_or(0.0) * k } else { k };
if alpha {
for (sum, value) in acc.iter_mut().zip(px).take(N - 1) {
*sum += value * a;
}
if let Some(sum) = acc.get_mut(N - 1) {
*sum += a;
}
} else {
for (sum, value) in acc.iter_mut().zip(px).take(N) {
*sum += value * a;
}
}
}
}
+1871 -256
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,46 @@
//! Summed-area table restricted to the nonzero bounds of a healing hole.
pub(super) struct HoleIntegral {
x0: i32,
y0: i32,
w: usize,
h: usize,
data: Vec<u32>,
}
impl HoleIntegral {
pub(super) fn new(stride: usize, hole: &[bool], (x0, y0, x1, y1): (usize, usize, usize, usize)) -> Option<Self> {
let (w, h) = (x1.checked_sub(x0)?, y1.checked_sub(y0)?);
let row_stride = w.checked_add(1)?;
let len = row_stride.checked_mul(h.checked_add(1)?)?;
let mut data = Vec::new();
data.try_reserve_exact(len).ok()?;
data.resize(len, 0u32);
for (y, sy) in (y0..y1).enumerate() {
let base = sy.checked_mul(stride)?;
let row = hole.get(base.checked_add(x0)?..base.checked_add(x1)?)?;
let mut count = 0u32;
for (x, &set) in row.iter().enumerate() {
count = count.checked_add(u32::from(set))?;
let above = *data.get(y * row_stride + x + 1)?;
*data.get_mut((y + 1) * row_stride + x + 1)? = above.checked_add(count)?;
}
}
Some(Self { x0: i32::try_from(x0).ok()?, y0: i32::try_from(y0).ok()?, w, h, data })
}
pub(super) fn count(&self, x0: i32, y0: i32, x1: i32, y1: i32) -> u32 {
super::window_count(
&self.data,
self.w,
self.h,
x0.saturating_sub(self.x0),
y0.saturating_sub(self.y0),
x1.saturating_sub(self.x0),
y1.saturating_sub(self.y0),
)
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,238 @@
use super::*;
use crate::inpaint::{best_offset, hole_bbox, integral, window_count};
#[test]
fn cropped_counts_match_full_image_for_clipped_and_disjoint_windows() {
let (w, h) = (37, 29);
for kind in 0..5 {
let hole: Vec<_> = (0..w * h)
.map(|i| {
let (x, y) = (i % w, i / w);
match kind {
0 => (11..16).contains(&x) && (8..14).contains(&y),
1 => x < 3 && y < 4,
2 => x >= w - 3 && y >= h - 4,
3 => (x == 3 && y == 8) || (x == 31 && y == 25),
_ => (x * 37 + y * 71) % 17 == 0,
}
})
.collect();
let cropped = HoleIntegral::new(w, &hole, hole_bbox(w, h, &hole).unwrap()).unwrap();
let full = integral(w, h, &hole);
for x0 in [-50, -1, 0, 3, 11, 15, 36, 40] {
for x1 in [-2, 0, 3, 13, 16, 37, 50] {
for y0 in [-30, -1, 0, 8, 13, 28, 35] {
for y1 in [-1, 0, 10, 14, 29, 40] {
assert_eq!(cropped.count(x0, y0, x1, y1), window_count(&full, w, h, x0, y0, x1, y1), "kind {kind}: {x0},{y0}..{x1},{y1}");
}
}
}
}
}
}
#[test]
fn table_size_depends_on_the_hole_bounds() {
let (w, h) = (1000, 700);
let hole: Vec<_> = (0..w * h).map(|i| (503..514).contains(&(i % w)) && (307..320).contains(&(i / w))).collect();
let table = HoleIntegral::new(w, &hole, hole_bbox(w, h, &hole).unwrap()).unwrap();
assert_eq!((table.w, table.h, table.data.len()), (11, 13, 12 * 14));
assert_eq!(table.count(0, 0, 1000, 700), 143);
assert_eq!(table.count(i32::MIN, i32::MIN, i32::MAX, i32::MAX), 143);
assert!(HoleIntegral::new(w, &hole, (10, 5, 9, 6)).is_none());
assert!(HoleIntegral::new(w, &[], (3, 4, 5, 6)).is_none());
assert!(HoleIntegral::new(w, &[], (0, 0, usize::MAX, 2)).is_none());
}
#[test]
fn proximity_offsets_match_full_tables_at_several_depths_and_channels() {
let (w, h) = (61, 49);
for ch in [1, 3, 4, 5] {
for depth in [8, 16, 32] {
let img: Vec<_> = (0..w * h * ch)
.map(|i| {
let value = ((i * 101 + i / (w * ch) * 37) % 251) as f32 / 250.0;
match depth {
8 => (value * 255.0).round() / 255.0,
16 => (value * 65535.0).round() / 65535.0,
_ => value * 2.0 - 0.5,
}
})
.collect();
for kind in 0..5 {
let hole: Vec<_> = (0..w * h)
.map(|i| {
let (x, y) = (i % w, i / w);
match kind {
0 => (27..32).contains(&x) && (20..25).contains(&y),
1 => x < 2 && y < 3,
2 => (x == 11 && y == 12) || (x == 38 && y == 30),
3 => x == 30 && y == 24,
_ => false,
}
})
.collect();
for (ring, radius) in [(1, 5), (3, 17), (5, 30), (1, 49)] {
assert_eq!(
best_offset(w, h, ch, &img, &hole, ring, radius),
old_best_offset(w, h, ch, &img, &hole, ring, radius),
"ch {ch} depth {depth} hole {kind} ring {ring} radius {radius}"
);
}
}
}
}
}
#[test]
fn ties_nonfinite_samples_and_full_holes_keep_the_previous_result() {
let (w, h, ch) = (40, 35, 3);
let hole: Vec<_> = (0..w * h).map(|i| (18..22).contains(&(i % w)) && (16..20).contains(&(i / w))).collect();
for value in [0.5, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
let img = vec![value; w * h * ch];
assert_eq!(best_offset(w, h, ch, &img, &hole, 3, 20), old_best_offset(w, h, ch, &img, &hole, 3, 20));
}
let full = vec![true; w * h];
assert_eq!(best_offset(w, h, ch, &vec![0.5; w * h * ch], &full, 3, 20), None);
}
#[test]
#[ignore = "release comparison on 24 and 36 MP images"]
#[allow(clippy::assertions_on_constants)]
fn proximity_integral_release_comparison() {
use std::{hint::black_box, time::Instant};
assert!(!cfg!(debug_assertions), "run with --release");
for (w, h, diameters, radius) in [
(182usize, 182usize, vec![50usize], 66i32),
(332, 332, vec![100], 116),
(632, 632, vec![200], 216),
(932, 932, vec![300], 316),
(6000, 4000, vec![32, 256], 512),
(7200, 5000, vec![32, 256], 512),
] {
for diameter in diameters {
let ch = 3;
let img: Vec<_> = (0..w * h * ch)
.map(|i| {
let (x, y, c) = ((i / ch) % w, (i / ch) / w, i % ch);
((x % 53 * 7 + y % 47 * 11 + c * 19) % 251) as f32 / 250.0
})
.collect();
let hole: Vec<_> = (0..w * h)
.map(|i| {
let dx = (i % w) as f64 - (w / 2) as f64;
let dy = (i / w) as f64 - (h / 2) as f64;
dx * dx + dy * dy < (diameter as f64 * 0.5).powi(2)
})
.collect();
let bbox = hole_bbox(w, h, &hole).unwrap();
let cropped = HoleIntegral::new(w, &hole, bbox).unwrap();
let old = old_best_offset(w, h, ch, &img, &hole, (diameter / 8).clamp(3, 16), radius);
assert_eq!(best_offset(w, h, ch, &img, &hole, (diameter / 8).clamp(3, 16), radius), old);
let mut old_ms = Vec::new();
let mut new_ms = Vec::new();
for run in 0..5 {
let mut measure = |fast: bool| {
let start = Instant::now();
let result = if fast {
best_offset(w, h, ch, black_box(&img), &hole, (diameter / 8).clamp(3, 16), radius)
} else {
old_best_offset(w, h, ch, black_box(&img), &hole, (diameter / 8).clamp(3, 16), radius)
};
let ms = start.elapsed().as_secs_f64() * 1000.0;
assert_eq!(result, old);
if fast {
new_ms.push(ms);
} else {
old_ms.push(ms);
}
};
measure(run % 2 == 0);
measure(run % 2 != 0);
}
old_ms.sort_by(f64::total_cmp);
new_ms.sort_by(f64::total_cmp);
println!(
"PROXIMITY {w}x{h} hole_diameter={diameter} old_ms={old_ms:?} new_ms={new_ms:?} speedup={:.2} full_table_bytes={} cropped_table_bytes={} offset={old:?}",
old_ms[2] / new_ms[2],
(w + 1) * (h + 1) * 4,
cropped.data.len() * 4
);
}
}
}
fn old_best_offset(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], ring: usize, max_radius: i32) -> Option<(i32, i32)> {
let (bx0, by0, bx1, by1) = hole_bbox(w, h, hole)?;
// No valid translation can move farther than the source image's extent.
// Bound arbitrary public API inputs before constructing i32 search ranges:
// usize -> i32 truncation and signed increments otherwise overflow or hang.
let extent = w.max(h).min((i32::MAX / 4) as usize) as i32;
let max_radius = max_radius.max(0).min(extent);
if max_radius == 0 {
return None;
}
let ring = ring.max(1).min(extent as usize) as i32;
let hs = integral(w, h, hole);
// Sample points: the hole's ring (dilated minus hole), subsampled for speed.
let mut pts = Vec::new();
let (x0, y0) = (bx0 as i32 - ring, by0 as i32 - ring);
let (x1, y1) = (bx1 as i32 + ring, by1 as i32 + ring);
for y in y0.max(0)..y1.min(h as i32) {
for x in x0.max(0)..x1.min(w as i32) {
if hole[y as usize * w + x as usize] {
continue;
}
if window_count(&hs, w, h, x - ring, y - ring, x + ring + 1, y + ring + 1) > 0 {
pts.push((x, y));
}
}
}
let stride = (pts.len() / 2000).max(1);
let pts: Vec<(i32, i32)> = pts.into_iter().step_by(stride).collect();
let eval = |dx: i32, dy: i32| -> Option<f32> {
let (hx0, hy0, hx1, hy1) = (x0 + dx, y0 + dy, x1 + dx, y1 + dy);
let inside = hx0 >= 0 && hy0 >= 0 && hx1 <= w as i32 && hy1 <= h as i32;
if (dx, dy) == (0, 0) || !inside || window_count(&hs, w, h, hx0, hy0, hx1, hy1) != 0 {
return None;
}
let mut e = 0.0f32;
for &(x, y) in &pts {
let (a, b) = ((y as usize * w + x as usize) * ch, ((y + dy) as usize * w + (x + dx) as usize) * ch);
for c in 0..ch {
let d = img[a + c] - img[b + c];
e += d * d;
}
}
// Mild preference for nearer sources on ties.
Some(e / pts.len().max(1) as f32 * (1.0 + 1e-3 * ((dx as f32).hypot(dy as f32) / max_radius as f32)))
};
// Coarse grid over the search window, then a full-resolution refinement around the winner.
let step = (max_radius / 24).max(1);
let mut best: Option<((i32, i32), f32)> = None;
let consider = |dx: i32, dy: i32, best: &mut Option<((i32, i32), f32)>| {
if let Some(e) = eval(dx, dy)
&& best.is_none_or(|(_, be)| e < be)
{
*best = Some(((dx, dy), e));
}
};
let mut dy = -max_radius;
while dy <= max_radius {
let mut dx = -max_radius;
while dx <= max_radius {
consider(dx, dy, &mut best);
dx += step;
}
dy += step;
}
if step > 1
&& let Some(((bx, by), _)) = best
{
for dy in (by - step)..=(by + step) {
for dx in (bx - step)..=(bx + step) {
consider(dx, dy, &mut best);
}
}
}
best.map(|b| b.0)
}
+51 -2
View File
@@ -269,6 +269,10 @@ const TILE: i32 = 128;
/// to: samples clamp to it, and pixels mapping outside it take the edge mode. `map` returns where
/// each output pixel centre samples (`None` = outside).
pub fn remap(src: &Surface, frame: Rect, out_area: Rect, edge: EdgeMode, map: &(dyn Fn(f64, f64) -> Option<Sample> + Sync)) -> Surface {
remap_impl(src, frame, out_area, edge, map, true)
}
fn remap_impl(src: &Surface, frame: Rect, out_area: Rect, edge: EdgeMode, map: &(dyn Fn(f64, f64) -> Option<Sample> + Sync), shared: bool) -> Surface {
let sfmt = src.format();
let needs_alpha = matches!(edge, EdgeMode::Transparency) && !sfmt.alpha;
let ofmt = if needs_alpha { PixelFormat::new(sfmt.mode, sfmt.sample, true) } else { sfmt };
@@ -363,7 +367,14 @@ pub fn remap(src: &Surface, frame: Rect, out_area: Rect, edge: EdgeMode, map: &(
let fy = ((s.p[1] - fy0).min(fy1 - s.p[1]) + 0.5).clamp(0.0, 1.0);
(fx * fy) as f32
};
let alpha = if sfmt.alpha { bicubic(n_in - 1, s.p).clamp(0.0, 1.0) } else { 1.0 };
// Color channels and coverage usually sample the same location. Prepare the 16
// tap addresses and weights once; each channel keeps its original summation order.
let center = if shared && (!rgb || (s.pr == s.p && s.pb == s.p)) { sample_channels(&buf, win, frame, n_in, s.p) } else { None };
let sample = |c: usize, p: [f64; 2]| {
let cached = if p == s.p { center.as_ref() } else { None };
cached.and_then(|v| v.get(c)).copied().unwrap_or_else(|| bicubic(c, p))
};
let alpha = if sfmt.alpha { sample(n_in - 1, s.p).clamp(0.0, 1.0) } else { 1.0 };
let mut col = [0.0f32; 8];
for (c, v) in col.iter_mut().enumerate().take(cc) {
let p = if rgb && c == 0 {
@@ -373,7 +384,7 @@ pub fn remap(src: &Surface, frame: Rect, out_area: Rect, edge: EdgeMode, map: &(
} else {
s.p
};
let pm = bicubic(c, p);
let pm = sample(c, p);
let straight = if sfmt.alpha { if alpha > 1e-6 { pm / alpha } else { 0.0 } } else { pm };
let g = s.gain;
*v = if subtractive {
@@ -418,6 +429,41 @@ pub fn remap(src: &Surface, frame: Rect, out_area: Rect, edge: EdgeMode, map: &(
out
}
fn sample_channels(buf: &[f32], win: Rect, frame: Rect, n: usize, p: [f64; 2]) -> Option<[f32; 8]> {
match n {
1 => sample_channels_impl::<1>(buf, win, frame, p),
2 => sample_channels_impl::<2>(buf, win, frame, p),
3 => sample_channels_impl::<3>(buf, win, frame, p),
4 => sample_channels_impl::<4>(buf, win, frame, p),
5 => sample_channels_impl::<5>(buf, win, frame, p),
8 => sample_channels_impl::<8>(buf, win, frame, p),
_ => None,
}
}
fn sample_channels_impl<const N: usize>(buf: &[f32], win: Rect, frame: Rect, p: [f64; 2]) -> Option<[f32; 8]> {
if N == 0 || N > 8 || win.is_empty() || frame.is_empty() || !p.iter().all(|v| v.is_finite()) {
return None;
}
let x = (p[0] - 0.5).clamp(frame.x0 as f64, frame.x1 as f64 - 1.0);
let y = (p[1] - 0.5).clamp(frame.y0 as f64, frame.y1 as f64 - 1.0);
let (xi, yi) = (x.floor(), y.floor());
let (wx, wy) = (catmull_rom((x - xi) as f32), catmull_rom((y - yi) as f32));
let mut acc = [0.0f32; 8];
for (j, wyv) in wy.iter().enumerate() {
let yy = ((yi as i32 + j as i32 - 1).clamp(win.y0, win.y1 - 1) - win.y0) as usize;
for (i, wxv) in wx.iter().enumerate() {
let xx = ((xi as i32 + i as i32 - 1).clamp(win.x0, win.x1 - 1) - win.x0) as usize;
let start = yy.checked_mul(win.width() as usize)?.checked_add(xx)?.checked_mul(N)?;
let px = buf.get(start..start.checked_add(N)?)?.first_chunk::<N>()?;
let weight = wxv * wyv;
for (a, v) in acc.iter_mut().zip(px) {
*a += weight * *v;
}
}
}
Some(acc)
}
/// Applies a lens correction to `src` over `frame` (normally the canvas).
pub fn correct(src: &Surface, frame: Rect, lc: &LensCorrection) -> Surface {
let map = LensMap::new(lc, frame);
@@ -522,3 +568,6 @@ mod tests {
assert!(out.pixel(0, 0)[0] < 0.4 && (out.pixel(20, 20)[0] - 0.5).abs() < 0.02, "{:?}", out.pixel(0, 0));
}
}
#[cfg(test)]
mod shared_sample_tests;
@@ -0,0 +1,54 @@
use super::*;
use photocraft_color::{ColorMode, PixelFormat, SampleType};
#[test]
fn shared_interpolation_matches_original_at_all_depths_and_edges() {
let bounds = Rect::new(-13, -9, 39, 26);
for mode in [
ColorMode::Rgb,
ColorMode::Grayscale,
ColorMode::Cmyk,
ColorMode::Lab,
ColorMode::Bitmap,
ColorMode::Duotone,
ColorMode::Indexed,
ColorMode::Multichannel,
] {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
for alpha in [false, true] {
let fmt = PixelFormat::new(mode, sample, alpha);
let n = fmt.channels();
let mut s = Surface::new(fmt);
let data: Vec<f32> = (0..bounds.width() as usize * bounds.height() as usize * n)
.map(|i| if i % 17 == 0 { 0.0 } else { ((i * 103 + i / n * 71) % 65536) as f32 / 65535.0 })
.collect();
s.write_region(bounds, &data);
for edge in [EdgeMode::Transparency, EdgeMode::Extension, EdgeMode::Color([0.2, 0.5, 0.7, 0.4])] {
for ca in [false, true] {
let map = |x: f64, y: f64| {
if (x as i32 + y as i32) % 13 == 0 {
return None;
}
let p = [x * 0.83 - 3.7, y * 1.14 + 1.3];
Some(Sample { p, pr: if ca { [p[0] - 0.9, p[1] + 0.3] } else { p }, pb: if ca { [p[0] + 0.7, p[1] - 0.4] } else { p }, gain: 1.17 })
};
let out = bounds.inflate(3);
let a = remap_impl(&s, bounds, out, edge, &map, true).read_region(out);
let b = remap_impl(&s, bounds, out, edge, &map, false).read_region(out);
assert_eq!(
a.iter().zip(&b).position(|(a, b)| a.to_bits() != b.to_bits()),
None,
"{mode:?} {sample:?} alpha {alpha} edge {edge:?} ca {ca}"
);
}
}
}
}
}
}
#[test]
fn shared_sampler_rejects_bad_windows_and_nonfinite_points() {
let win = Rect::new(0, 0, 3, 3);
assert!(sample_channels(&[], win, win, 4, [1.0, 1.0]).is_none());
assert!(sample_channels(&[0.0; 36], win, win, 4, [f64::NAN, 1.0]).is_none());
assert!(sample_channels(&[], Rect::EMPTY, win, 4, [1.0, 1.0]).is_none());
}
+78 -4
View File
@@ -23,8 +23,10 @@ mod artistic_fx;
mod blur;
mod blur2;
pub mod camera_raw;
pub mod color_to_alpha;
pub mod content_aware;
mod denoise;
pub mod direct;
mod distort;
mod distort2;
pub mod erase;
@@ -41,11 +43,13 @@ pub mod liquify;
pub mod magnetic;
pub mod matting;
mod noise;
pub mod nonlocal;
mod oil;
mod other;
mod other2;
pub mod paint;
pub mod panorama;
mod par;
pub mod perspective;
mod photo_util;
mod pixelate;
@@ -55,6 +59,7 @@ pub mod pyramid;
pub mod quantize;
pub mod redeye;
mod relight;
pub mod remove;
mod render;
pub mod render2;
pub mod resample;
@@ -519,6 +524,14 @@ pub enum FilterParams {
input: HsbModel,
output: HsbModel,
},
/// Removes `color` (straight sRGB RGBA, alpha ignored) by unmixing it from every pixel into
/// transparency (see [`color_to_alpha`]). Thresholds 0–1: opacities at or below
/// `transparency_threshold` become 0, at or above `opacity_threshold` 1, linear in between.
ColorToAlpha {
color: [f32; 4],
transparency_threshold: f32,
opacity_threshold: f32,
},
// ---- Video ----
/// Removes the even (or odd) lines and rebuilds them by interpolation (or duplication).
@@ -572,6 +585,13 @@ impl FilterParams {
}
}
/// Whether the filter's job is to make pixels transparent (Color to Alpha): it needs a layer
/// that can hold transparency, so callers turn the Background into a normal layer first and
/// refuse a layer whose transparency is locked instead of putting the old alpha back.
pub fn makes_transparency(&self) -> bool {
matches!(self, FilterParams::ColorToAlpha { .. })
}
/// Whether the filter moves pixels around the reference bounds (its
/// output area is the bounds, not the layer's content grown by the halo).
pub fn is_global(&self) -> bool {
@@ -637,6 +657,7 @@ impl FilterParams {
FilterParams::PathBlur { .. } => "Path Blur",
FilterParams::Custom { .. } => "Custom",
FilterParams::HsbHsl { .. } => "HSB/HSL",
FilterParams::ColorToAlpha { .. } => "Color to Alpha",
FilterParams::DeInterlace { .. } => "De-Interlace",
FilterParams::NtscColors => "NTSC Colors",
FilterParams::FilterGallery { effects } => match effects.as_slice() {
@@ -656,7 +677,7 @@ fn halo_ext(p: &FilterParams) -> Halo {
FilterParams::Pointillize { cell_size, .. } => r(cell_size.max(1.0) * 2.0),
FilterParams::Facet => r(3.0),
FilterParams::Fragment => r(4.0),
FilterParams::Mezzotint { .. } | FilterParams::HsbHsl { .. } | FilterParams::NtscColors => Halo::Radius(0),
FilterParams::Mezzotint { .. } | FilterParams::HsbHsl { .. } | FilterParams::ColorToAlpha { .. } | FilterParams::NtscColors => Halo::Radius(0),
FilterParams::Diffuse { .. } => r(1.0),
FilterParams::Extrude { size, depth, .. } => r(stylize2::extrude_reach(*depth) + size.clamp(2.0, 255.0) * 3.0 + 1.0),
FilterParams::OilPaint { stylization, scale, .. } => r(oil::reach(*stylization, *scale)),
@@ -869,6 +890,9 @@ pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec<f
FilterParams::PathBlur { paths } => gallery::path(src, out, ctx, paths),
FilterParams::Custom { kernel, scale, offset } => other2::custom(src, out, ctx, kernel, *scale, *offset),
FilterParams::HsbHsl { input, output } => other2::hsb_hsl(src, out, ctx, *input, *output),
FilterParams::ColorToAlpha { color, transparency_threshold, opacity_threshold } => {
color_to_alpha::color_to_alpha(src, out, ctx, *color, *transparency_threshold, *opacity_threshold)
}
FilterParams::DeInterlace { eliminate_even, interpolate } => video::deinterlace(src, out, ctx, *eliminate_even, *interpolate),
FilterParams::NtscColors => video::ntsc(src, out, ctx),
FilterParams::FilterGallery { effects } => artistic_fx::run(effects, src, out, ctx),
@@ -963,6 +987,24 @@ pub fn apply_tiled_with(
extent: Option<Rect>,
ctl: &photocraft_raster::Interrupt,
) -> Option<Surface> {
apply_tiled_with_impl(surface, params, area, bounds, selection, tile, extent, ctl, true)
}
#[allow(clippy::too_many_arguments)]
fn apply_tiled_with_impl(
surface: &Surface,
params: &FilterParams,
area: Rect,
bounds: Rect,
selection: Option<&Surface>,
tile: i32,
extent: Option<Rect>,
ctl: &photocraft_raster::Interrupt,
prepare_radial: bool,
) -> Option<Surface> {
if ctl.cancelled() {
return None;
}
let mut out = surface.clone();
if area.is_empty() {
return Some(out);
@@ -978,6 +1020,18 @@ pub fn apply_tiled_with(
let tile = if matches!(params, FilterParams::ShapeBlur { .. }) { tile.clamp(1, 2048) } else { tile };
let fmt = surface.format();
let ctx = Ctx { bounds, mode: fmt.mode, alpha: fmt.alpha };
// Prepare the immutable sample transforms once for all output tiles. If the
// optional table allocation fails, use the existing sampler; only a real
// cancellation returns None. Source reads keep their upstream semantics.
let radial = match params {
FilterParams::RadialBlur { amount, method, quality, center_x, center_y } if prepare_radial => {
blur::radial::Plan::for_area(bounds, *amount, *method, *quality, (*center_x, *center_y), area, ctl)
}
_ => None,
};
if ctl.cancelled() {
return None;
}
let halo = params.halo_for(bounds);
let shared = (halo == Halo::Bounds).then(|| Image::read(surface, bounds.union(&area)));
// Shape rasterization depends only on params, not on a tile's pixels.
@@ -1029,9 +1083,14 @@ pub fn apply_tiled_with(
&owned
}
};
let Some(mut data) = (match &shape {
Some(shape) => shape.checked_run(src, *t, &ctx),
None => Some(kernel(params, src, *t, &ctx)),
let Some(mut data) = (match (&shape, &radial) {
(Some(shape), _) => shape.checked_run(src, *t, &ctx),
(None, Some(plan)) => match plan.filter(src, *t, &ctx, ctl) {
Some(data) => Some(data),
None if ctl.cancelled() => None,
None => Some(kernel(params, src, *t, &ctx)),
},
(None, None) => Some(kernel(params, src, *t, &ctx)),
}) else {
return (*t, Vec::new());
};
@@ -1169,3 +1228,18 @@ mod tests_ext;
#[cfg(test)]
mod tests_mosaic;
/// The current upstream sampler through the identical source/selection/tile pipeline.
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
fn apply_radial_reference(
surface: &Surface,
params: &FilterParams,
area: Rect,
bounds: Rect,
selection: Option<&Surface>,
extent: Rect,
ctl: &photocraft_raster::Interrupt,
) -> Option<Surface> {
apply_tiled_with_impl(surface, params, area.intersect(&extent), bounds, selection, auto_tile(params, bounds), Some(extent), ctl, false)
}
Loaded 100 of 940 files, more files were not shown because too many files have changed in this diff. Show more