31 Commits

Author SHA1 Message Date
bhursey d42727618e Add the film gallery generator and brand logo
scripts/film-samples.mjs renders the sample frames and B&W filter strip for the
film-looks page, and logo.png is the asset the app, bundles and site deploy all
expect at the repo root.
2026-11-29 01:15:52 +00:00
bhursey 335cb3c757 Ship Windows as a per-user NSIS installer
Replaces the Inno Setup script, which could not be built off Windows, with an
NSIS installer that cross-compiles on Linux, installs under LOCALAPPDATA with
no UAC prompt, and keeps the catalog on uninstall. build.mjs gains --installer
and --no-installer, and --publish now ships the setup exe beside the portable
zip.
2026-11-29 01:15:52 +00:00
bhursey 7ecc4474c5 Add the Ubuntu packaging pipeline and smoke test
Builds the tar.gz and .deb under linux/, with a launcher, install script and
SMOKE-LINUX.sh so a packaged build can be checked before publishing.
2026-11-29 01:15:49 +00:00
bhursey 726a5b922b Fix direct window launch when VBScript is disabled
The window now starts Luminary.ps1 through a hidden PowerShell process instead of relying on the VBS entry point, and the installer defaults to Luminary.cmd. Bump the beta to 0.5.1.
2026-11-28 23:03:51 +00:00
bhursey fe1da03f66 Add direct native-window launch and publish 0.5 beta
Forward a direct LuminaryWindow launch through the bundle launcher so it starts desktop mode instead of showing a signed-out page. Refresh the guide screenshots and version the release as 0.5.0 Beta.
2026-11-28 22:40:16 +00:00
bhursey edfc6cdc80 Cover raw and TIFF import in tests and show decode details
The new tests pin the CR2/NEF/CR3/DNG and TIFF routing, container
signatures and TIFF proxy decoding, with an opt-in fixture run for real
raw files. The Info panel now reports the decoder and the proxy size, so
a file that fell back to a camera preview is visible at a glance.
2026-11-28 20:57:53 +00:00
bhursey 27360ffae7 Import TIFF through the server and survive a wedged raw decoder
Browsers have no TIFF decoder, so TIFF import failed at createImageBitmap
and the develop canvas asked for the undecodable original. TIFF now takes
the raw proxy path (original stored, sharp writes the JPEG proxy) and the
editor reads that proxy. LibRaw demosaic and preview calls are bounded so
one bad file falls back to the embedded preview instead of hanging.
2026-11-28 20:49:25 +00:00
bhursey 8aafdcfb16 Add an About panel with the guide version and date
Clicking the brand opens it, so the guide version and publication date
are visible in the app rather than only on the PDF cover.
2026-11-28 20:32:37 +00:00
bhursey d0e0e8926c Rebuild the user guide from live catalog screenshots
The guide now covers every screen, panel and setting with 21 figures
captured from the production catalog, plus server, Docker and Windows
install chapters, a full settings reference and a printable quick-start
card. The PDF is regenerated and refreshed in public/ and docs/.
2026-11-28 20:30:27 +00:00
bhursey 4beaaacf0e Hide account and team admin UI in single-user mode
The desktop bundle has one local admin and nothing to manage, so the
account pill, the account panel and the team administration panel are
left out when the server reports local mode.
2026-11-28 18:39:06 +00:00
bhursey b79f6c9a4e Give the Windows bundle a single-user mode without sign-in
LUMINARY_LOCAL=1 creates one local admin and treats an unauthenticated
request as that account, so the packaged desktop app opens signed in. It
is off unless the launcher sets it, leaving the shared server and Docker
deploy unchanged.
2026-11-28 18:33:08 +00:00
bhursey fb43ca8e99 Make the mask tint a view toggle and mask local detail in source space
The mask overlay was always painted while the mask tool was open, at a fixed
strength; it is now a persisted view toggle (O or the Mask button) with its own
strength slider, so the photo underneath stays readable. The mask HUD also
gains + and - so a brush can erase and a shape can subtract without leaving the
canvas.

Local texture, clarity, dehaze and sharpen sampled the baked masks at the view
coordinate in the finish pass, so their coverage slid off the subject under a
crop or zoom. The grade pass now writes each pixel's source coordinate to a
second render target and the finish pass reads the masks through it, which also
follows straightening and lens correction.

The render gate checks the tint and a local dehaze amount through a quarter
frame crop and a synthetic lens warp, plus the tint strength and toggle.
2026-11-28 17:39:31 +00:00
bhursey 46dcc231a7 Show the baked local mask in the develop view instead of a drawn band.
The overlay redrew every stroke as a flat translucent band, so the feather
never appeared and the guide did not match the shape it stood for. The
develop view now tints the selected layer's baked mask, sampled with the
same source uv the adjustments use: the preview follows crops,
straightening, zoom, lens correction, subtract shapes and the feather
exactly as the mask stores it. Only the stroke still under the pointer is
drawn, as a preview of what will be baked, and the histogram is left
alone while a tint is showing.

The render gate now checks the overlay ranks its tint from the dab core
through the feathered rim to untouched pixels outside the brush circle.
2026-11-28 17:14:00 +00:00
bhursey c05dbce580 Keep the brush guide round and show the feather in it.
The local brush cursor took its height from the canvas aspect and its width
from the frame window, so a cropped or zoomed photo drew an oval cursor
over a round mask, and the stroke preview was scaled the same wrong way.
Both now convert the brush radius through the visible frame on each axis,
which matches the baked mask at any crop or zoom.

The feather band was also invisible in the guide: the preview painted one
flat band and the cursor was a single ring. Painted strokes now show the
soft band under the solid core, and the cursor adds an inner ring at
1 - feather of the radius.

Masks shrink their width instead of clamping their height, so tall or wide
frames keep square mask pixels and round dabs.
2026-11-28 17:09:02 +00:00
bhursey 69a327cd45 Draw brush masks with a soft dab inside the brush circle.
Feathering blurred a copy of the stroke and unioned it with the hard
stroke, so coverage stayed at full strength across the whole stroke and
then continued as a halo past the brush outline. The adjustment visibly
spilled outside the brush circle and its rim read as a step rather than a
falloff.

Each stroke is now stamped with a dab that is solid out to 1 - feather of
its radius and fades to nothing at the rim, so the mask follows the brush
circle and softens smoothly at any size. The render gate measures the
dab's core, its rim and the area just outside the circle.
2026-11-28 16:47:49 +00:00
bhursey 5c2903eeef Apply the lens vignetting gain in linear light.
Lensfun's vignetting coefficients describe linear transmission, so
multiplying them into the sRGB-encoded proxy brightened the corners far
more than the lens had lost and over-exposed the edges. The gain now runs
after the decode, in both the grade and the eyedropper.

Existing records that stored the old auto-enabled flag are cleared once,
on the server catalogue at boot and in the browser cache on its next
IndexedDB upgrade, and the Optics panel says when the correction is off.
2026-11-28 16:34:31 +00:00
bhursey be8cf3c88a Make lens-profile vignetting correction opt-in.
Applying a profile used to enable distortion, CA and vignetting together,
and the flat-field gain lifts the already tone-mapped corners above the
frame centre, over-exposing the edges. Vignetting now defaults off when a
profile is applied or restored from a camera default, and only turns on
when a profile explicitly stored vignetting: true.
2026-11-28 16:21:19 +00:00
bhursey b884616889 Group local mask shapes into editable components.
A local adjustment is now a list of shapes composited in order (add, subtract,
intersect) instead of a single shape, so dodging and burning can be built from
several brushes, gradients and auto masks without spending layer channels.
Existing edits migrate on load: the flat layer fields become components[0],
keeping geometry, invert, feather and the layer's blend mode unchanged. The
panel gains a shape list with active-shape editing, and the render gate now
asserts a subtract shape clears the group while an intersect keeps it.
2026-11-28 16:09:14 +00:00
bhursey acf582251f Give every mask its own tone curve.
Local masks could only shift tone globally, so a burnt sky or a backlit face had
to fight the frame-wide sliders. Each mask now carries an RGB point curve,
applied to the masked pixels before the mask blend. All eight curves ride in one
256×8 LUT texture, so the grade shader needs a single extra sampler rather than
eight. Masks saved before this exist migrate to an identity curve, so old edits
keep their look; the render check fails if the curve stops reaching the grade,
and a unit test pins the LUT's identity, per-row isolation and monotonicity.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 15:42:24 +00:00
bhursey 00e6fee9bd Pin the mask cases a model benchmark exposed.
A cluster-based rewrite of the model-free estimator was measured against u2netp
on seven real 60D frames and came out worse than the border-histogram version
(0.214 vs 0.305 mean IoU against the model, best blend weight 0.298), so it was
not shipped. The two cases that mattered are now regression tests: a saturated
object running off the frame must stay out of the subject, and a dark scene with
no clear subject must not be swallowed.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 15:36:53 +00:00
bhursey 24deb8e69b Deploy through the predeploy gate instead of by hand.
`npm run deploy` now runs the gate (typecheck, unit suite, render check) before
anything is copied, then rsyncs the source, rebuilds and restarts the service on
the target from LUMINARY_DEPLOY_* variables, and fails if the server is not
serving the same bundle hashes as the reviewed local build. npm runs a script
named predeploy before deploy on its own, so the gate runs once; invoked as
`node scripts/deploy.mjs` the script gates itself. Both scripts exit through
process.exitCode, because process.exit() truncated the failure messages when
they were piped.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 15:20:18 +00:00
bhursey 4b17ca00db Skip the pre-deploy build when only test files changed.
predeploy was a shell chain that always rebuilt, so a test-only edit paid for a
full Vite build. It is now scripts/predeploy.mjs: typecheck, tests and the render
check always run, and the build is skipped when a content hash of the bundle
inputs (src and public minus test files, plus the Vite/TS/package config) matches
the last successful build. The signature lives in node_modules/.cache, so it is
gitignored and never rsynced to the server.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 15:02:00 +00:00
bhursey 6e80699829 Show the shadow palette in the clipping legend and pin both overlay checks.
The shadow warning gained per-channel colours but the legend only explained the
highlight palette, so the new marks had no key. The legend now switches to the
shadow palette whenever shadow clipping is on, listing one channel, the three
two-channel colours and all three. The render check also fails if the shadow
overlay stops following Exposure, the way the highlight side already did.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 14:58:03 +00:00
bhursey a67e9ef458 Name the channels in the shadow clipping warning too.
Shadow warnings were a flat blue, so a single crushed channel looked the same as
all three. The shadow branch now uses the highlight palette: red/green/blue for
one channel, yellow (red+green), magenta (red+blue) and cyan (green+blue) for
pairs, white for all three. The render check covers both ends of the range, and
`npm run predeploy` chains typecheck, tests, the render check and the build so a
shader regression cannot reach a deploy.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 14:40:50 +00:00
bhursey a6491f6ef6 Show the clipping overlay's per-channel colours and follow the sliders.
The overlay had been collapsed to a single highlight bit, so every warning was
white. It now reads the finished frame per channel again: red for one clipped
channel, yellow for two, white for all three, and it updates as Exposure or
Recovery moves, which is what holding Ctrl is for. The render check renders the
overlay and asserts both the colours and that +6 EV turns a clear band white.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 14:38:48 +00:00
bhursey fe9d2aff3f Name the clipped channels in the Ctrl clipping overlay again.
0c113e7 packed clipping into two alpha states (shadow / highlight), so the finish
pass could only paint white even though the legend still promised red, green,
blue and yellow. The grade pass now writes a 4-bit code (R/G/B + shadow) into
alpha and the overlay paints the channels it actually lost: red for one, yellow
for two, white for all three. The render check renders the overlay so this
cannot regress silently.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 14:35:30 +00:00
bhursey 1e7ec0cf15 Add a headless render check for the 16-bit sidecar swap.
The proxy and sidecar reach the GPU through different upload paths, and whether
they agree depends on UNPACK_FLIP_Y_WEBGL being ignored for ImageBitmap. A unit
test cannot see that, so the picture could silently start flipping again. The
check encodes a two-tone sidecar with the server's encoder, serves it beside the
matching JPEG and measures the rows that land in a WebGL2 texture in headless
Chrome.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 14:30:36 +00:00
bhursey c10ff97670 Upload the 16-bit sidecar unflipped so it matches the JPEG proxy.
Chrome ignores UNPACK_FLIP_Y_WEBGL for ImageBitmap uploads, so the JPEG proxy
lands in the texture top-down while the parser pre-flipped the sidecar rows.
The picture jumped upside down a few seconds after load, when the sidecar
replaced the proxy. The parser now keeps the PNG's row order.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:59:55 +00:00
bhursey 2dc569256c Give Auto tone and Auto WB the raw's thumbnail URL.
Raw records keep their pixels in `thumbUrl` and leave `thumb` empty, so the
analysis was handed an empty string, failed to decode, and returned neutral
values — which made Auto WB look identical to As shot.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:45:37 +00:00
bhursey c7b01b31cb Resume the preview rebuild where a restart left it.
The job only lived in memory, so every deploy discarded hours of proxy work and
the next run started at the first photo. Mirror progress to the storage root
after each photo and pick the pending ids back up on boot.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:45:37 +00:00
bhursey 32616d5404 Report a failed GPU draw instead of painting black.
A rejected draw leaves the canvas untouched, so a broken frame looked like a
black photo with nothing to explain it. Poll the error queue once per frame and
raise an error the editor can show.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:45:37 +00:00
96 changed files with 10138 additions and 713 deletions
+8
View File
@@ -14,3 +14,11 @@ server/data/
.smoke/ .smoke/
*.log *.log
.DS_Store .DS_Store
# Windows native-window build output
windows/launcher/webview2/bin/
windows/launcher/webview2/obj/
# Transfer-only Windows release archives
windows/releases/*.zip
windows/releases/*.exe
+32 -1
View File
@@ -281,6 +281,22 @@ npm run build # type-checks and bundles dist/
npm start # serves dist/ and /api from one Node process npm start # serves dist/ and /api from one Node process
``` ```
To push a running install over ssh, `npm run deploy` runs the whole predeploy gate
first — a type error, a failing test or a clipping-overlay regression stops it before
anything is copied — then rsyncs the source, rebuilds, restarts the service and checks
that the server is serving the same bundle hashes. npm runs the `predeploy` script
before `deploy` on its own, so the gate runs exactly once; calling `node
scripts/deploy.mjs` directly runs the gate itself:
```bash
LUMINARY_DEPLOY_HOST=bhursey@photos.example.org \
LUMINARY_DEPLOY_SUDO_PASS=… npm run deploy
```
`LUMINARY_DEPLOY_PATH` (default `/srv/luminary`), `LUMINARY_DEPLOY_SERVICE` (default
`luminary`) and `LUMINARY_DEPLOY_SSH_PASS` cover a different layout; without the
password variables it uses your ssh key and passwordless sudo.
The server serves the built UI with an SPA fallback (unknown non-API paths return The server serves the built UI with an SPA fallback (unknown non-API paths return
`index.html`), caches `/assets/*` for a year as immutable, and returns `503` with a `index.html`), caches `/assets/*` for a year as immutable, and returns `503` with a
build hint if `dist/index.html` is missing. JSON responses are `no-store`; image bytes build hint if `dist/index.html` is missing. JSON responses are `no-store`; image bytes
@@ -956,6 +972,9 @@ positions. Camera-lens defaults require both a normalised camera and lens name t
| `npm run dev` | Vite HMR on 5173 | | `npm run dev` | Vite HMR on 5173 |
| `npm run typecheck` | `tsc --noEmit` | | `npm run typecheck` | `tsc --noEmit` |
| `npm test` | Vitest, one pass then exit | | `npm test` | Vitest, one pass then exit |
| `npm run check:render` | Headless Chrome check that the 16-bit sidecar and JPEG proxy upload in the same row order |
| `npm run predeploy` | Typecheck, unit suite, render check, then build — run this before pushing a deploy; the build is skipped when only test files changed since the last build |
| `npm run deploy` | Predeploy gate, then rsync, remote build, restart and bundle-hash check (see [Production deployment](#production-deployment)) |
Conventions worth knowing before changing code: Conventions worth knowing before changing code:
@@ -984,13 +1003,25 @@ Conventions worth knowing before changing code:
| `src/lib/lensNames.test.ts` | EXIF lens-name normalisation, search variants and match scoring | | `src/lib/lensNames.test.ts` | EXIF lens-name normalisation, search variants and match scoring |
| `src/lib/lensDefaults.test.ts` | Camera + lens default selection and rejection rules | | `src/lib/lensDefaults.test.ts` | Camera + lens default selection and rejection rules |
| `src/lib/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve | | `src/lib/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve |
| `src/lib/preview16.test.ts` | 16-bit PNG proxy parsing, row flip, half-float encoding and the camera matrix chunk | | `src/lib/preview16.test.ts` | 16-bit PNG proxy parsing, row order, half-float encoding and the camera matrix chunk |
| `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values | | `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values |
| `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold, rendering-intent selection and CMYK profiles | | `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold, rendering-intent selection and CMYK profiles |
| `src/lib/dcpLibrary.test.ts` | Per-camera DCP library: validation, replacement, forgetting and camera matching | | `src/lib/dcpLibrary.test.ts` | Per-camera DCP library: validation, replacement, forgetting and camera matching |
There are no server integration tests; the API is exercised through the UI. There are no server integration tests; the API is exercised through the UI.
`npm run check:render` covers the one thing the unit suite cannot: what a shader does to
real GPU pixels. It encodes a 16-bit sidecar with the server's own encoder, serves it
beside the matching JPEG proxy and measures the rows that reach a WebGL2 texture in
headless Chrome. Then it renders that image through the real `Renderer` with the Ctrl
clipping preview on, so the overlay has to paint red for one clipped channel and yellow
for two instead of collapsing to white, and an unclipped band has to turn white once
Exposure is pushed past the top of the range. The same run checks the shadow warning:
red for one channel at black, yellow for red+green, cyan for green+blue. `npm run
predeploy` chains it with the typecheck, unit suite and build. It fails on either regression, printing the
measured values, needs Chrome (`CHROME_PATH` overrides discovery) and skips with a notice
when none is installed.
--- ---
## Troubleshooting ## Troubleshooting
Binary file not shown.
+851 -376
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 488 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 390 KiB

After

Width:  |  Height:  |  Size: 488 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 373 KiB

After

Width:  |  Height:  |  Size: 764 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 343 KiB

After

Width:  |  Height:  |  Size: 365 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 342 KiB

After

Width:  |  Height:  |  Size: 651 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 174 KiB

After

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 202 KiB

After

Width:  |  Height:  |  Size: 246 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 192 KiB

After

Width:  |  Height:  |  Size: 394 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 KiB

After

Width:  |  Height:  |  Size: 343 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 501 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 384 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 285 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 226 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 398 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

+212
View File
@@ -0,0 +1,212 @@
# Linux (Ubuntu) bundle (optional)
An additive, self-contained way to produce a double-clickable Linux desktop
install of Luminary. The server and Docker workflow stay the source of truth:
this folder only *packages* the existing `dist/` + `server/` output, and the
build writes its artifacts **outside the checkout** — exactly like
[`windows/`](../windows/README.md).
## Isolation guarantees
1. **The packaging tree is additive.** There is no `package.json` script for
this, and no change to `.gitignore` (beyond ignoring the tarball in
`releases/`), `.dockerignore`, `Dockerfile`, `docker-compose.yml` or
`scripts/deploy.mjs`. Invoke it directly: `node linux/build.mjs`. The only
app-side behaviour used is the opt-in desktop mode in `server/config.mjs` +
`server/index.mjs` (`LUMINARY_LOCAL=1`), which the Windows launcher already
introduced; it stays off unless the launcher sets it.
2. **Artifacts live outside the repo** (default: `~/.cache/luminary-linux`). The
script refuses an `--out` inside the checkout, because `scripts/deploy.mjs`
rsyncs the worktree to production and `docker build` would pull a ~300 MB
bundle into its context.
3. **The worktree must be clean outside `linux/`** before and after a build (the
untracked `logo.png` is tolerated). `--allow-dirty` overrides it.
4. **Nothing in the app changes at run time.** The bundle is the unchanged
`server/` + `dist/` + production `node_modules`, started with `PORT`, `HOST`,
`NODE_ENV` and `LUMINARY_DATA` — all variables the server already reads.
## What the end user needs
Ubuntu 22.04 or 24.04, 64-bit, and a browser. Nothing to install: Node 24 is
inside the bundle (`runtime/bin/node`), sharp's Linux binaries are bundled, and
there is no deb, no apt step and no root.
| Piece | What it uses |
| --- | --- |
| `runtime/bin/node` | the official Node 24 linux-x64 build, SHA-256 checked against nodejs.org |
| `sharp` | `@img/sharp-linux-x64` + `@img/sharp-libvips-linux-x64`, installed from this repo's lockfile |
| app window | Chrome, Chromium, Edge, Brave or Vivaldi `--app=`; Firefox and the default browser are fallbacks |
| Develop module | a browser with WebGL2 |
## Build
```bash
node linux/build.mjs # npm run build, then the bundle
node linux/build.mjs --skip-build # reuse the existing dist/
node linux/build.mjs --out /srv/builds/luminary-linux
node linux/build.mjs --skip-build --publish
```
Output:
```
<out>/
Luminary-0.5.1-linux-x64.tar.gz portable bundle
Luminary-0.5.1-linux-amd64.deb Ubuntu package, built from the same bundle
stage/Luminary/ the unpacked bundle (kept for inspection)
cache/node-v24.22.2-linux-x64.tar.gz
cache/SHASUMS256-v24.22.2.txt
```
The build prints the archive size, its SHA-256, the Node version, the .deb size
and the staged folder. The tarball keeps the executable bits on `luminary` and
`runtime/bin/node`, so extracting it is enough — no `chmod` needed. The `.deb`
is built with the `dpkg` package's `dpkg-deb` when it is installed; on a host
without it the build prints a warning and produces only the tarball.
### Installing on Ubuntu
Easiest: install the `.deb`, which puts the app in `/opt/luminary`, adds
`/usr/bin/luminary`, an applications-menu entry and the icon. Your photos and
catalog still live in `~/.local/share/luminary`, so removing or upgrading the
package never touches them:
```bash
sudo apt install ./Luminary-0.5.1-linux-amd64.deb
luminary # or launch Luminary from the applications menu
```
`apt` pulls in the two runtime libraries it needs (`libstdc++6`, `libgomp1`);
Node, the server and sharp's Linux binaries are inside the package. Uninstall
with `sudo apt remove luminary`; `sudo apt purge luminary` also removes
`/opt/luminary` but never the data folder.
Or stay portable — nothing installed, nothing to root:
```bash
tar -xzf Luminary-0.5.1-linux-x64.tar.gz
cd Luminary
./luminary # starts desktop mode and opens the app window
./install.sh # optional: add Luminary to the applications menu
```
`--publish` copies the tarball and a `SHA256SUMS.txt` into
[`releases/`](releases/), the hand-off folder for a USB stick, network share or
release upload. That is the only write the builder makes inside the checkout.
`scripts/deploy.mjs` rsyncs the worktree, so remove the tarball from `releases/`
after transferring if you do not want it on the server.
## What is in the bundle
```
Luminary/
luminary bash launcher: start, health wait, app window
install.sh adds ~/.local/share/applications/luminary.desktop
Luminary.png 256×256 icon for the menu
version.txt version, commit, and the Node pin (version, SHA-256, size)
README-linux.txt end-user instructions
LICENSE, THIRD_PARTY_NOTICES.md, licenses/
runtime/ official Node 24 linux-x64 (bin/node, lib/node_modules)
app/
server/ unchanged, minus server/data and *.test.mjs
dist/ the normal Vite build (UI, lens db, guide PDF)
package.json provenance
package-lock.json
node_modules/ production deps installed with --os=linux --cpu=x64
```
## Running it
`./luminary` picks a free loopback port from 8787, sets
`LUMINARY_DATA=~/.local/share/luminary`, starts the server with
`LUMINARY_LOCAL=1`, waits for `/api/health`, then opens a chromeless window:
```
google-chrome --app=http://127.0.0.1:8787 \
--user-data-dir=~/.local/share/luminary/window-profile \
--class=Luminary
```
No tabs, no address bar, its own profile and window size. `./luminary --browser`
opens a normal tab instead (`LUMINARY_WINDOW=browser` works too).
| Command | What it does |
| --- | --- |
| `./luminary` | start (or reuse a running server) and open the window |
| `./luminary --stop` | stop the server; data stays |
| `./luminary --status` | bundle, data folder, pid, URL and `/api/health` |
| `./luminary --verify` | list any missing piece of the bundle |
| `./luminary --install` | add the applications-menu entry |
| `./luminary --uninstall` | remove that entry, keep the catalog |
The `.deb` installs the same launcher as `/usr/bin/luminary`, so every flag
works there too (`luminary --stop`, `--status`, `--verify`). Its data folder is
the same `~/.local/share/luminary`.
### Single-user desktop mode
The launcher starts the server with `LUMINARY_LOCAL=1`, the same mode the
Windows bundle uses:
- one admin (`local@luminary`) is created on first start and reused afterwards;
- `/api/auth/me` answers without a cookie, so the UI never shows signup or
sign-in, and registration returns 403;
- the account is an admin, so every panel works, with no password to remember;
- the server binds `127.0.0.1`, so this is not reachable from the network.
Starting with `HOST=0.0.0.0` and `LUMINARY_LOCAL=1` logs a warning at boot.
## Smoke test
The automated first pass is [`SMOKE-LINUX.sh`](SMOKE-LINUX.sh). Run it from the
extracted bundle (or a `.deb` install):
```bash
./SMOKE-LINUX.sh # bundle in this folder
./SMOKE-LINUX.sh --bundle /opt/luminary
```
It reports the distribution, browser and display, checks the bundle files and
`luminary --verify`, boots the real server through the launcher in desktop mode
(`local:true`, cookieless `/api/auth/me`, closed registration, `/api/sync`),
checks `--install`/`--uninstall` write and remove a real `.desktop` file, and
confirms `--stop` stops it. It uses a throwaway data folder and a private
`XDG_DATA_HOME`, so no real catalog or menu entry is touched, and it writes
`smoke-report.txt` next to the bundle. The app window itself stays a visual
check (the launcher runs with `LUMINARY_WINDOW=none` during the test).
## Data, updates and backups
- Catalog, originals, previews, `secret.key`, logs and the window profile live in
`~/.local/share/luminary` (or `$LUMINARY_DATA`), never inside the bundle.
- Update: `./luminary --stop`, replace `app/` and `runtime/` from a newer
bundle, start again. The SQLite schema migrates on boot.
- Back up: copy `~/.local/share/luminary` while Luminary is stopped, including
`lumenroom.db`, `lumenroom.db-wal`, `lumenroom.db-shm`.
## Verifying a build
```bash
cd <out>
sha256sum Luminary-0.5.1-linux-x64.tar.gz
tar -tzf Luminary-0.5.1-linux-x64.tar.gz | grep -E 'luminary$|runtime/bin/node$|app/server/index.mjs$'
tar -xzf Luminary-0.5.1-linux-x64.tar.gz -C /tmp/luminary-check
/tmp/luminary-check/Luminary/luminary --verify
```
On a real desktop also check the window opens, the UI is signed in as the local
admin, importing a RAW file works, and `--stop` closes the server.
## Limitations
- The `.deb` is unsigned (no repository, no signing key), so `apt` installs it
locally without verification and there is no auto-update. Only the portable
tarball and the `.deb` are produced — no AppImage or Snap in this version — and
there is no tray icon.
- The app window depends on a Chromium-based browser being installed; without
one it falls back to Firefox or the default browser as a normal window.
- Wayland compositors may ignore `--class=Luminary`, so the dock icon can be the
browser's.
- Loopback only by default; set `HOST=0.0.0.0` when starting the server by hand
for LAN proofing galleries.
- The launcher cannot clean up after a server crash; a stale PID file is ignored
on the next start (`--status` reports "stopped").
+277
View File
@@ -0,0 +1,277 @@
#!/usr/bin/env bash
# One-command smoke test for an extracted Luminary Linux bundle.
#
# Run it from the extracted bundle folder (or pass --bundle):
#
# ./SMOKE-LINUX.sh
# ./SMOKE-LINUX.sh --bundle /opt/luminary
#
# It writes smoke-report.txt next to the bundle and prints the same lines.
# Exit code 0 means every check passed.
#
# What it covers without a human clicking:
# - distro, architecture, glibc, display, and which browser the launcher picks
# - the bundle files the launcher needs, and `luminary --verify`
# - a real boot through the launcher in desktop mode: /api/health local:true,
# /api/auth/me 200 without a cookie, registration closed, /api/sync 200
# - the menu entry install/uninstall writing and removing a real .desktop file
# - `luminary --stop` actually stopping the server
#
# It uses a throwaway data folder under $TMPDIR and a private XDG_DATA_HOME, so
# it never touches a real catalog or your applications menu. The app window is
# not opened (the launcher runs with LUMINARY_WINDOW=none); it is a visual check.
set -u
BUNDLE=""
while [ "$#" -gt 0 ]; do
case "$1" in
--bundle)
BUNDLE="${2:-}"
shift 2
;;
--help|-h)
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
exit 0
;;
*)
printf 'unknown option %s (see --help)\n' "$1" >&2
exit 2
;;
esac
done
[ -n "$BUNDLE" ] || BUNDLE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUNDLE="$(readlink -f "$BUNDLE")"
LINES=()
FAILED=0
SKIPPED=0
say() {
LINES+=("$*")
printf '%s\n' "$*"
}
check() {
local name="$1" ok="$2" detail="${3:-}"
if [ "$ok" = "0" ]; then
say " PASS $name${detail:+ — $detail}"
else
FAILED=$((FAILED + 1))
say " FAIL $name${detail:+ — $detail}"
fi
}
skip() {
SKIPPED=$((SKIPPED + 1))
say " SKIP $1${2:+ — $2}"
}
[ -x "$BUNDLE/runtime/bin/node" ] && NODE="$BUNDLE/runtime/bin/node" || NODE="$(command -v node 2>/dev/null || true)"
if [ -z "$NODE" ]; then
printf 'Luminary: no Node runtime found in the bundle or on PATH\n' >&2
exit 1
fi
WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/luminary-smoke.XXXXXX")" || exit 1
export XDG_DATA_HOME="$WORK_DIR/xdg"
export LUMINARY_DATA="$WORK_DIR/data"
export LUMINARY_WINDOW=none
BODY="$WORK_DIR/body.json"
URL=""
cleanup() {
if [ -x "$BUNDLE/luminary" ] && [ -f "$LUMINARY_DATA/luminary.pid" ]; then
"$BUNDLE/luminary" --stop >/dev/null 2>&1 || true
fi
rm -rf "$WORK_DIR"
}
trap cleanup EXIT
# http <method> <url> [json-body] -> status code on stdout, body in $BODY
http() {
"$NODE" -e '
const [method, url, payload, out] = process.argv.slice(-4);
const init = { method };
if (payload) {
init.headers = { "Content-Type": "application/json" };
init.body = payload;
}
fetch(url, init)
.then(async (r) => { require("node:fs").writeFileSync(out, await r.text()); process.stdout.write(String(r.status)); })
.catch(() => process.stdout.write("0"));
' "$1" "$2" "${3:-}" "$BODY"
}
# jget <dotted.path> -> value from the last response body
jget() {
"$NODE" -e '
const fs = require("node:fs");
let value;
try { value = JSON.parse(fs.readFileSync(process.argv.slice(-2)[0], "utf8")); } catch { process.exit(0); }
for (const key of process.argv.slice(-1)[0].split(".")) value = value == null ? value : value[key];
if (value !== undefined && value !== null) process.stdout.write(String(value));
' "$BODY" "$1"
}
browser_name() {
local name
for name in google-chrome google-chrome-stable chromium chromium-browser \
microsoft-edge microsoft-edge-stable brave-browser vivaldi-stable firefox; do
if command -v "$name" >/dev/null 2>&1; then
printf '%s' "$name"
return 0
fi
done
return 1
}
say 'Luminary Linux smoke test'
say " bundle $BUNDLE"
say " time $(date -Is)"
say ''
say 'Environment'
if [ -r /etc/os-release ]; then
# shellcheck disable=SC1091
distro="$(. /etc/os-release && printf '%s' "${PRETTY_NAME:-${NAME:-unknown}}")"
else
distro="$(uname -s)"
fi
say " distro $distro"
say " arch $(uname -m)"
say " kernel $(uname -r)"
say " glibc $(ldd --version 2>/dev/null | head -n 1 || printf 'unknown')"
say " display ${DISPLAY:-none}${WAYLAND_DISPLAY:+ (wayland $WAYLAND_DISPLAY)}"
if browser="$(browser_name)"; then
say " browser $browser"
else
say ' browser none found (the launcher would fall back to the default browser)'
fi
say ''
say 'Bundle'
check 'luminary launcher present' $([ -x "$BUNDLE/luminary" ] && echo 0 || echo 1)
check 'runtime/bin/node present' $([ -x "$BUNDLE/runtime/bin/node" ] && echo 0 || echo 1) "$BUNDLE/runtime/bin/node"
check 'app/server/index.mjs present' $([ -f "$BUNDLE/app/server/index.mjs" ] && echo 0 || echo 1)
check 'app/dist/index.html present' $([ -f "$BUNDLE/app/dist/index.html" ] && echo 0 || echo 1)
check 'app/node_modules present' $([ -d "$BUNDLE/app/node_modules" ] && echo 0 || echo 1)
node_version="$("$NODE" --version 2>/dev/null)"
check 'node runs' $([ -n "$node_version" ] && echo 0 || echo 1) "$node_version"
check 'node is 24 or newer' "$("$NODE" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 24 ? 0 : 1)' 2>/dev/null; echo $?)"
if [ -x "$BUNDLE/luminary" ]; then
if "$BUNDLE/luminary" --verify >"$WORK_DIR/verify.txt" 2>&1; then
check '--verify exits 0' 0
else
check '--verify exits 0' 1 "$(tr '\n' ' ' <"$WORK_DIR/verify.txt")"
fi
else
check '--verify exits 0' 1 'launcher missing'
fi
say ''
say 'Server (desktop mode, via the launcher)'
"$BUNDLE/luminary" >"$WORK_DIR/start.txt" 2>&1
start_status=$?
check 'launcher start exits 0' "$start_status" "$(head -n 1 "$WORK_DIR/start.txt")"
if [ -f "$LUMINARY_DATA/runtime.json" ]; then
check 'runtime.json written' 0
URL="http://127.0.0.1:$("$NODE" -p "JSON.parse(require('fs').readFileSync('$LUMINARY_DATA/runtime.json','utf8')).port")"
else
check 'runtime.json written' 1 "$LUMINARY_DATA/runtime.json"
fi
if [ -n "$URL" ]; then
code="$(http GET "$URL/api/health")"
check 'health answers' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code"
if [ "$code" = "200" ]; then
check 'local mode advertised' $([ "$(jget local)" = "true" ] && echo 0 || echo 1) "local=$(jget local)"
check 'version advertised' $([ -n "$(jget version)" ] && echo 0 || echo 1) "version=$(jget version)"
check 'no setup prompt' $([ "$(jget needsSetup)" = "false" ] && echo 0 || echo 1)
check 'registration closed' $([ "$(jget registrationOpen)" = "false" ] && echo 0 || echo 1)
check 'libraw ready' $([ "$(jget raw.libraw)" = "true" ] && echo 0 || echo 1)
check 'sharp ready' $([ "$(jget raw.sharp)" = "true" ] && echo 0 || echo 1)
fi
code="$(http GET "$URL/api/auth/me")"
me_email="$(jget user.email)"
me_role="$(jget user.role)"
check 'signed in without a cookie' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code $me_email ($me_role)"
code="$(http POST "$URL/api/auth/register" '{"email":"smoke@example.test","password":"smoke-test-password"}')"
check 'registration refused' $([ "$code" = "403" ] && echo 0 || echo 1) "HTTP $code"
code="$(http GET "$URL/api/sync")"
check '/api/sync answers' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code"
code="$(http GET "$URL/")"
check 'UI index served' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code"
if [ "$code" = "200" ] && grep -q 'src/assets\|assets/' "$BODY"; then
check 'UI references built assets' 0
else
check 'UI references built assets' 1
fi
fi
if "$BUNDLE/luminary" --status 2>/dev/null | grep -q 'Status: running'; then
check '--status reports running' 0
else
check '--status reports running' 1
fi
say ''
say 'Menu entry'
if XDG_DATA_HOME="$WORK_DIR/xdg" "$BUNDLE/luminary" --install >/dev/null 2>&1 &&
[ -f "$WORK_DIR/xdg/applications/luminary.desktop" ]; then
check '--install writes a .desktop file' 0
if grep -q "^Exec=\"\?$BUNDLE/luminary\"\?$" "$WORK_DIR/xdg/applications/luminary.desktop"; then
check 'menu entry points at this bundle' 0
else
check 'menu entry points at this bundle' 1 "$(grep '^Exec=' "$WORK_DIR/xdg/applications/luminary.desktop")"
fi
else
check '--install writes a .desktop file' 1
fi
if XDG_DATA_HOME="$WORK_DIR/xdg" "$BUNDLE/luminary" --uninstall >/dev/null 2>&1 &&
[ ! -f "$WORK_DIR/xdg/applications/luminary.desktop" ]; then
check '--uninstall removes it' 0
else
check '--uninstall removes it' 1
fi
say ''
say 'Stop'
"$BUNDLE/luminary" --stop >/dev/null 2>&1
if [ -n "$URL" ]; then
code="$(http GET "$URL/api/health")"
check 'server stopped' $([ "$code" = "0" ] && echo 0 || echo 1) "HTTP $code"
else
check 'server stopped' 1 'server never started'
fi
if "$BUNDLE/luminary" --status 2>/dev/null | grep -q 'Status: stopped'; then
check '--status reports stopped' 0
else
check '--status reports stopped' 1
fi
say ''
say 'Window'
skip 'app window opens' 'visual check; the launcher opened nothing during this run'
say ''
if [ "$FAILED" -eq 0 ]; then
say 'RESULT: PASS'
else
say "RESULT: FAIL ($FAILED check(s))"
fi
report="$BUNDLE/smoke-report.txt"
if ! { printf '%s\n' "${LINES[@]}" >"$report"; } 2>/dev/null; then
report="$(pwd)/smoke-report.txt"
printf '%s\n' "${LINES[@]}" >"$report" 2>/dev/null || true
fi
[ -f "$report" ] && say " report $report"
[ "$FAILED" -eq 0 ] && exit 0 || exit 1
+758
View File
@@ -0,0 +1,758 @@
#!/usr/bin/env node
/**
* Build the optional Linux (Ubuntu) desktop bundle for Luminary.
*
* Like windows/build.mjs this is *outside* the main build: it only reads the
* repository (`dist/`, `server/`, `package.json`) and writes everything into a
* directory outside the checkout. Nothing in `src/`, `server/`, `package.json`,
* the Dockerfile, the deploy script or `dist/` is modified by this file, and no
* npm script is added for it. Run it directly:
*
* node linux/build.mjs # build dist/ then the bundle
* node linux/build.mjs --skip-build # reuse the existing dist/
* node linux/build.mjs --out /srv/lum # choose the output directory
*
* The bundle keeps the layout the server expects (it derives `DIST_DIR` from
* the parent of `server/`), so it is a plain folder plus a launcher:
*
* <out>/Luminary/
* luminary bash launcher: start, health wait, app window
* install.sh adds Luminary to the Ubuntu applications menu
* Luminary.png icon
* runtime/bin/node official Node 24 linux-x64, SHA-256 checked
* app/ unchanged server/, dist/, production node_modules/
* README-linux.txt
* version.txt
*/
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import {
chmodSync,
cpSync,
existsSync,
lstatSync,
mkdirSync,
readFileSync,
readdirSync,
renameSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..');
const LAUNCHER_FILES = path.join(HERE, 'launcher');
const RELEASES_DIR = path.join(HERE, 'releases');
const NPM = 'npm';
const DEFAULT_NODE = 'v24.22.2';
const HELP = `Luminary Linux (Ubuntu) bundle
Usage: node linux/build.mjs [options]
--out <dir> output directory (default: <cache>/luminary-linux).
Must be outside this repository; the bundle is staged in
<out>/stage and archived to
<out>/Luminary-<ver>-linux-x64.tar.gz.
--skip-build reuse the existing dist/ instead of running npm run build
--node <version> bundled Node version, e.g. v24.22.2 (must be >= 24)
--allow-dirty skip the check that the checkout is clean outside linux/
--publish copy the finished tar.gz and .deb to linux/releases (plus
a SHA256SUMS.txt) so they can be handed off or uploaded
--help print this text
Nothing in the repository is modified: the only writes outside the output
directory are the ones npm and nodejs.org make for their own caches.
`;
function fail(message) {
process.stderr.write(`linux: FAILED: ${message}\n`);
process.exit(1);
}
function log(step, message) {
process.stdout.write(`linux: ${step.padEnd(9)} ${message}\n`);
}
function warn(message) {
process.stderr.write(`linux: warning: ${message}\n`);
}
function defaultOutDir() {
return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-linux');
}
function parseArgs(argv) {
const options = {
out: defaultOutDir(),
node: DEFAULT_NODE,
build: true,
allowDirty: false,
publish: false,
help: false,
};
const value = (index, flag) => {
const next = argv[index + 1];
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
return next;
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--out') {
options.out = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--node') {
const version = value(i, arg);
options.node = version.startsWith('v') ? version : `v${version}`;
i += 1;
} else if (arg === '--skip-build') {
options.build = false;
} else if (arg === '--allow-dirty') {
options.allowDirty = true;
} else if (arg === '--publish') {
options.publish = true;
} else if (arg === '--help' || arg === '-h') {
options.help = true;
} else {
fail(`unknown option ${arg} (see --help)`);
}
}
if (!/^v\d+\.\d+\.\d+$/.test(options.node)) {
fail(`--node must look like v24.22.2 (got ${options.node})`);
}
return options;
}
function git(args, { trim = true } = {}) {
const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' });
if (result.error || result.status !== 0) return null;
return trim ? result.stdout.trim() : result.stdout;
}
/**
* The bundle must not land in the checkout: a staged Node runtime and
* node_modules would otherwise be rsynced to production by scripts/deploy.mjs
* and grow the Docker build context.
*/
function assertOutsideRepo(outDir) {
const relative = path.relative(ROOT, outDir);
const inside = !relative.startsWith('..') && !path.isAbsolute(relative);
if (inside) {
fail(
`--out resolves inside the repository (${outDir}).\n` +
'The bundle is large and would be copied by the deploy rsync; pick an\n' +
'output directory outside the checkout, or omit --out to use the cache.',
);
}
}
/**
* Only this folder may be dirty. `logo.png` is a long-standing untracked asset
* in this checkout and is not part of the app, so it is tolerated.
*/
function checkRepoClean(options) {
const status = git(['status', '--porcelain'], { trim: false });
if (status === null) {
warn('git is unavailable here; skipping the worktree check');
return;
}
const unexpected = status
.split('\n')
.filter((line) => line.length > 3)
.map((line) => line.slice(3).replace(/^"|"$/g, '').replace(/^.* -> /, '').trim())
.filter((file) => file && !file.startsWith('linux/') && file !== 'logo.png');
if (!unexpected.length) return;
if (options.allowDirty) {
warn(`building from a modified checkout: ${unexpected.join(', ')}`);
return;
}
fail(
`the checkout has changes outside linux/:\n ${unexpected.join('\n ')}\n` +
'Commit or stash them, or pass --allow-dirty to build anyway.',
);
}
function readPackage() {
const file = path.join(ROOT, 'package.json');
if (!existsSync(file)) fail('run this from a Luminary checkout (package.json missing)');
return JSON.parse(readFileSync(file, 'utf8'));
}
function run(command, args, cwd, extraEnv) {
log('run', [command, ...args].join(' '));
const result = spawnSync(command, args, {
cwd,
stdio: 'inherit',
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
});
if (result.error) fail(`${command} could not start: ${result.error.message}`);
if (result.status !== 0) fail(`${command} ${args.join(' ')} exited with ${result.status}`);
}
function ensureUi(options) {
const dist = path.join(ROOT, 'dist', 'index.html');
if (options.build) {
log('ui', 'npm run build (typecheck + vite build, the normal artifact)');
run(NPM, ['run', 'build'], ROOT);
} else {
log('ui', 'reusing the existing dist/ (--skip-build)');
}
if (!existsSync(dist)) {
fail('dist/index.html is missing; drop --skip-build or run "npm run build" first');
}
return dist;
}
function copyServer(bundle) {
const server = path.join(bundle, 'app', 'server');
cpSync(path.join(ROOT, 'server'), server, {
recursive: true,
filter: (source) => {
const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/');
// The developer catalog and the test files never belong in a bundle.
if (relative === 'data' || relative.startsWith('data/')) return false;
if (/\.test\.mjs$/.test(relative)) return false;
return true;
},
});
}
function copyLegal(bundle) {
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
const source = path.join(ROOT, name);
if (existsSync(source)) cpSync(source, path.join(bundle, name));
}
const licenses = path.join(ROOT, 'licenses');
if (existsSync(licenses)) cpSync(licenses, path.join(bundle, 'licenses'), { recursive: true });
}
function installLinuxDeps(bundle) {
const appDir = path.join(bundle, 'app');
cpSync(path.join(ROOT, 'package.json'), path.join(appDir, 'package.json'));
cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json'));
log('deps', 'npm ci --omit=dev --os=linux --cpu=x64 (sharp linux-x64 prebuild)');
// --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the
// prebuilt binary through optionalDependencies.
run(
NPM,
['ci', '--omit=dev', '--os=linux', '--cpu=x64', '--no-audit', '--no-fund', '--ignore-scripts'],
appDir,
);
// .bin shims are for an interactive shell, not for `node server/index.mjs`.
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
verifySharp(appDir);
}
function verifySharp(appDir) {
const dir = path.join(appDir, 'node_modules', '@img', 'sharp-linux-x64');
if (!existsSync(dir)) {
warn('@img/sharp-linux-x64 is missing; the server will fall back to PNG proxies');
return;
}
const binaries = [];
const walk = (current) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) walk(absolute);
else if (/\.(node|so(\.\d+)*)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute));
}
};
walk(dir);
if (!binaries.some((file) => file.endsWith('.node'))) {
warn('@img/sharp-linux-x64 has no .node binary; check the installed package');
} else {
log('deps', `sharp linux-x64 ready (${binaries.length} native files)`);
}
}
function sha256File(file) {
return createHash('sha256').update(readFileSync(file)).digest('hex');
}
async function download(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}`);
return Buffer.from(await response.arrayBuffer());
}
function extractTar(archive, destination) {
mkdirSync(destination, { recursive: true });
const result = spawnSync(
'tar',
['-xzf', archive, '-C', destination, '--strip-components=1'],
{ stdio: 'inherit' },
);
if (result.error || result.status !== 0) {
fail(`could not extract ${path.basename(archive)} (is tar installed?)`);
}
}
async function ensureNode(outDir, version) {
const major = Number(version.slice(1).split('.')[0]);
if (major < 24) {
fail(`Node ${version} is too old: node:sqlite and type stripping need 24 LTS`);
}
const cache = path.join(outDir, 'cache');
mkdirSync(cache, { recursive: true });
const name = `node-${version}-linux-x64.tar.gz`;
const archive = path.join(cache, name);
const sums = path.join(cache, `SHASUMS256-${version}.txt`);
const base = `https://nodejs.org/dist/${version}`;
if (!existsSync(archive)) {
// Unlike the Windows node.exe, the Linux tarballs sit at the dist root.
log('node', `downloading ${base}/${name}`);
try {
writeFileSync(archive, await download(`${base}/${name}`));
} catch (error) {
fail(`could not download ${name}: ${error.message}`);
}
} else {
log('node', `using cached ${name}`);
}
if (!existsSync(sums)) {
try {
writeFileSync(sums, (await download(`${base}/SHASUMS256.txt`)).toString('utf8'));
} catch (error) {
warn(`could not fetch SHASUMS256.txt (${error.message}); the cached tarball is unverified`);
}
}
const hash = sha256File(archive);
if (existsSync(sums)) {
const line = readFileSync(sums, 'utf8')
.split('\n')
.map((row) => row.trim().split(/\s+/))
.find((row) => row[1] === name);
if (!line) fail(`SHASUMS256.txt for ${version} has no ${name} entry`);
if (hash !== line[0]) {
rmSync(archive, { force: true });
fail(`${name} failed its SHA-256 check (${hash} != ${line[0]}); re-run to download again`);
}
log('node', `${version} linux-x64 verified (sha256 ${hash.slice(0, 12)}…)`);
} else {
warn(`using the Node tarball without a published checksum (sha256 ${hash})`);
}
return { archive, hash };
}
function installRuntime(bundle, archive) {
const runtime = path.join(bundle, 'runtime');
rmSync(runtime, { recursive: true, force: true });
log('runtime', 'extracting Node into runtime/ (bin/node, lib/node_modules)');
extractTar(archive, runtime);
const nodeBin = path.join(runtime, 'bin', 'node');
if (!existsSync(nodeBin)) fail('the Node tarball did not contain runtime/bin/node');
chmodSync(nodeBin, 0o755);
const check = spawnSync(nodeBin, ['--version'], { encoding: 'utf8' });
if (check.status !== 0) fail(`the bundled node binary does not run here: ${check.stderr || ''}`);
log('runtime', `bundled ${check.stdout.trim()} runs on this host`);
return nodeBin;
}
function installLauncher(bundle) {
const launcher = path.join(bundle, 'luminary');
cpSync(path.join(LAUNCHER_FILES, 'luminary'), launcher);
chmodSync(launcher, 0o755);
const installer = path.join(bundle, 'install.sh');
cpSync(path.join(LAUNCHER_FILES, 'install.sh'), installer);
chmodSync(installer, 0o755);
// Ships with the bundle so the first-run check is one command, and travels
// into /opt/luminary in the .deb.
const smoke = path.join(HERE, 'SMOKE-LINUX.sh');
if (existsSync(smoke)) {
cpSync(smoke, path.join(bundle, 'SMOKE-LINUX.sh'));
chmodSync(path.join(bundle, 'SMOKE-LINUX.sh'), 0o755);
}
log('launcher', 'luminary (app window + --stop/--status/--install), install.sh, SMOKE-LINUX.sh');
}
async function writeIcon(bundle) {
const logo = path.join(ROOT, 'logo.png');
const target = path.join(bundle, 'Luminary.png');
if (!existsSync(logo)) {
warn('logo.png is missing; the bundle has no menu icon');
return;
}
try {
const { default: sharp } = await import('sharp');
await sharp(logo).resize(256, 256, { fit: 'cover' }).png().toFile(target);
log('icon', `Luminary.png (${(statSync(target).size / 1024).toFixed(0)} KB)`);
} catch (error) {
cpSync(logo, target);
warn(`could not resize logo.png (${error.message}); copied it unchanged`);
}
}
function writeVersion(bundle, pkg, nodeVersion, nodeHash, nodeSize) {
const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown';
const lines = [
`Luminary ${pkg.version}`,
`commit ${commit}`,
`built ${new Date().toISOString()}`,
`node ${nodeVersion} linux-x64 sha256 ${nodeHash} size ${nodeSize}`,
'launcher luminary (bash)',
];
writeFileSync(path.join(bundle, 'version.txt'), `${lines.join('\n')}\n`);
return { version: pkg.version, commit };
}
function writeBundleReadme(bundle, info) {
const body = `Luminary ${info.version} for Linux (x64) — portable bundle
==============================================
Start: ./luminary
Stop: ./luminary --stop
Menu: ./install.sh (adds Luminary to your applications menu)
Open tab: ./luminary --browser
Status: ./luminary --status
Data: ~/.local/share/luminary (originals, previews, SQLite catalog)
Logs: ~/.local/share/luminary/logs/server.out.log and server.err.log
Sign-in: none — single-user desktop mode, no account setup
Requirements
- Ubuntu 22.04 or 24.04, 64-bit (any glibc distribution of similar age works).
- A Chromium-based browser for the app window: Chrome, Chromium, Edge, Brave
or Vivaldi. Firefox is used as a normal window, and the default browser is
the last resort. WebGL2 is needed for the Develop module.
- Nothing to install: Node.js is included in runtime/, and sharp's Linux
binaries are bundled. No root, no apt, no deb package.
- About 250 MB free where the data folder lives.
Extract the tarball anywhere, then run ./luminary from the extracted folder.
Nothing is written into /usr or /opt, so moving or deleting the folder is safe;
the catalog lives in ~/.local/share/luminary and is not touched on removal.
./install.sh adds a menu entry (~/.local/share/applications/luminary.desktop)
using this folder's absolute path, so install after you have put the folder
where you want to keep it. ./luminary --uninstall removes the entry again.
Back up the catalog by copying ~/.local/share/luminary while Luminary is
stopped, including lumenroom.db, lumenroom.db-wal, lumenroom.db-shm and
secret.key.
Updating: stop Luminary, replace app/ and runtime/ from a newer bundle, start
again. The data folder is outside the bundle and is untouched.
Notes
- The server listens on 127.0.0.1 only. Set HOST=0.0.0.0 when starting it
directly with node if client proofing galleries must reach other devices.
- The app window is the browser's own app mode with a private profile, so it
has no tabs or address bar. Some Wayland desktops ignore the requested
window class; the window still opens.
- RAW decoding uses the bundled libraw WebAssembly, so no system codec
packages are needed.
- Photo libraries on NTFS/exFAT drives work, but SQLite is happiest on a
native Linux filesystem.
`;
writeFileSync(path.join(bundle, 'README-linux.txt'), body);
}
/* ------------------------------------------------------------------ deb ---- */
function walkBytes(dir) {
let total = 0;
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const absolute = path.join(dir, entry.name);
if (entry.isDirectory()) total += walkBytes(absolute);
else total += lstatSync(absolute).size;
}
return total;
}
const DEB_MAINTAINER_SCRIPT = `#!/bin/sh
set -e
# Refresh the menu and icon caches so Luminary appears without a logout.
if command -v update-desktop-database >/dev/null 2>&1; then
update-desktop-database -q /usr/share/applications || true
fi
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor || true
fi
exit 0
`;
function debControlFile(pkg, installedBytes) {
return [
'Package: luminary',
`Version: ${pkg.version}`,
'Architecture: amd64',
'Maintainer: Brian Hursey <bhursey@gmail.com>',
`Installed-Size: ${Math.ceil(installedBytes / 1024)}`,
'Depends: libc6, libstdc++6, libgomp1',
'Recommends: chromium | google-chrome-stable | microsoft-edge-stable | firefox',
'Section: graphics',
'Priority: optional',
'Homepage: https://git.maple-street.net/bhursey/luminary',
'Description: photo library and raw editor',
' Luminary catalogs photos, develops camera raw files and serves client',
' proofing galleries. This package bundles the Node runtime and the server,',
' so it installs with no other dependencies. Photos and the catalog live in',
' ~/.local/share/luminary and are kept when the package is removed.',
'',
].join('\n');
}
function debDesktopEntry() {
return [
'[Desktop Entry]',
'Type=Application',
'Version=1.0',
'Name=Luminary',
'GenericName=Photo library',
'Comment=Photo library and raw editor',
'Exec=/usr/bin/luminary',
'Path=/opt/luminary',
'Icon=luminary',
'Terminal=false',
'Categories=Graphics;Photography;',
'Keywords=photo;raw;catalog;editor;',
'StartupNotify=true',
'StartupWMClass=Luminary',
'',
].join('\n');
}
function debCopyright() {
return [
'Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/',
'Upstream-Name: Luminary',
'Source: https://git.maple-street.net/bhursey/luminary',
'',
'Files: *',
'Copyright: 2026 Brian Hursey',
'License: MIT',
' The full MIT licence text is in /opt/luminary/LICENSE.',
'',
].join('\n');
}
/**
* Builds the opt-in Ubuntu package from the same staged bundle. Installed as
* /opt/luminary so the bundle layout (and therefore the launcher's bundle
* detection) is unchanged; the data folder stays in the user's home.
*/
function buildDeb(outDir, pkg, bundle) {
const probe = spawnSync('dpkg-deb', ['--version'], { encoding: 'utf8' });
if (probe.error || probe.status !== 0) {
warn('dpkg-deb is not installed; skipping the .deb (install the dpkg package)');
return null;
}
const work = path.join(outDir, 'deb.next');
rmSync(work, { recursive: true, force: true });
const root = path.join(work, 'root');
log('deb', 'staging /opt/luminary, /usr/bin/luminary and the menu entry');
const appTarget = path.join(root, 'opt', 'luminary');
mkdirSync(path.dirname(appTarget), { recursive: true });
cpSync(bundle, appTarget, { recursive: true });
const binDir = path.join(root, 'usr', 'bin');
mkdirSync(binDir, { recursive: true });
// Relative link so the package works whatever the prefix.
symlinkSync('../opt/luminary/luminary', path.join(binDir, 'luminary'));
const appsDir = path.join(root, 'usr', 'share', 'applications');
mkdirSync(appsDir, { recursive: true });
writeFileSync(path.join(appsDir, 'luminary.desktop'), debDesktopEntry());
const icon = path.join(bundle, 'Luminary.png');
const iconDir = path.join(root, 'usr', 'share', 'icons', 'hicolor', '256x256', 'apps');
mkdirSync(iconDir, { recursive: true });
if (existsSync(icon)) cpSync(icon, path.join(iconDir, 'luminary.png'));
else warn('the bundle has no Luminary.png; the menu entry will use a generic icon');
const docDir = path.join(root, 'usr', 'share', 'doc', 'luminary');
mkdirSync(docDir, { recursive: true });
cpSync(path.join(bundle, 'README-linux.txt'), path.join(docDir, 'README-linux.txt'));
writeFileSync(path.join(docDir, 'copyright'), debCopyright());
const installedBytes = walkBytes(root);
const controlDir = path.join(root, 'DEBIAN');
mkdirSync(controlDir, { recursive: true });
writeFileSync(path.join(controlDir, 'control'), debControlFile(pkg, installedBytes));
for (const name of ['postinst', 'postrm']) {
const file = path.join(controlDir, name);
writeFileSync(file, DEB_MAINTAINER_SCRIPT);
chmodSync(file, 0o755);
}
const debPath = path.join(outDir, `Luminary-${pkg.version}-linux-amd64.deb`);
rmSync(debPath, { force: true });
const result = spawnSync(
'dpkg-deb',
['--root-owner-group', '-Zxz', '--build', root, debPath],
{ stdio: 'inherit' },
);
if (result.error || result.status !== 0) fail('dpkg-deb could not build the package');
const listed = spawnSync('dpkg-deb', ['--contents', debPath], { encoding: 'utf8' });
if (listed.status !== 0) fail('the .deb could not be read back');
for (const required of [
'opt/luminary/luminary',
'opt/luminary/runtime/bin/node',
'usr/bin/luminary',
'usr/share/applications/luminary.desktop',
]) {
if (!listed.stdout.includes(required)) fail(`the .deb is missing ${required}`);
}
log('deb', `${path.basename(debPath)} (${(statSync(debPath).size / 1024 / 1024).toFixed(1)} MB)`);
rmSync(work, { recursive: true, force: true });
return debPath;
}
/* ------------------------------------------------------------------ tar ---- */
function createArchive(workRoot, tarPath) {
rmSync(tarPath, { force: true });
const deterministic = [
'--sort=name',
'--owner=0',
'--group=0',
'--numeric-owner',
'--mtime=@1577836800',
'-czf',
tarPath,
'-C',
workRoot,
'Luminary',
];
let result = spawnSync('tar', deterministic, { stdio: 'inherit' });
if (result.error || result.status !== 0) {
warn('this tar has no --sort/--owner support; writing a plain archive instead');
result = spawnSync('tar', ['-czf', tarPath, '-C', workRoot, 'Luminary'], { stdio: 'inherit' });
}
if (result.error || result.status !== 0) fail('tar could not create the archive');
const list = spawnSync('tar', ['-tzf', tarPath], { encoding: 'utf8' });
if (list.status !== 0) fail('the archive could not be read back');
const entries = list.stdout.split('\n').filter(Boolean);
for (const required of [
'Luminary/luminary',
'Luminary/runtime/bin/node',
'Luminary/app/server/index.mjs',
'Luminary/app/dist/index.html',
]) {
if (!entries.includes(required)) fail(`the archive is missing ${required}`);
}
return { files: entries.length, bytes: statSync(tarPath).size };
}
/* ----------------------------------------------------------------- main ---- */
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
process.stdout.write(HELP);
return 0;
}
assertOutsideRepo(options.out);
const pkg = readPackage();
log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`);
log('out', options.out);
checkRepoClean(options);
ensureUi(options);
// Build into a sibling and swap at the end, so a failed run never replaces
// the last complete bundle with a partial tree.
const stageRoot = path.join(options.out, 'stage');
const workRoot = path.join(options.out, 'stage.next');
const bundle = path.join(workRoot, 'Luminary');
rmSync(workRoot, { recursive: true, force: true });
mkdirSync(path.join(bundle, 'app'), { recursive: true });
log('stage', 'copying dist/ and server/ (unchanged layout the server expects)');
cpSync(path.join(ROOT, 'dist'), path.join(bundle, 'app', 'dist'), { recursive: true });
copyServer(bundle);
copyLegal(bundle);
installLinuxDeps(bundle);
const node = await ensureNode(options.out, options.node);
const nodeBin = installRuntime(bundle, node.archive);
// Remember the size now: the bundle is renamed into stage/ before the summary.
const nodeBinSize = statSync(nodeBin).size;
installLauncher(bundle);
await writeIcon(bundle);
const info = writeVersion(
bundle,
pkg,
options.node,
node.hash,
statSync(node.archive).size,
);
writeBundleReadme(bundle, info);
const tarPath = path.join(options.out, `Luminary-${pkg.version}-linux-x64.tar.gz`);
log('tar', path.basename(tarPath));
const archive = createArchive(workRoot, tarPath);
// The .deb is built from the same staged bundle, before it is moved into
// stage/, so both artifacts are guaranteed to come from one build.
const debPath = buildDeb(options.out, pkg, bundle);
rmSync(stageRoot, { recursive: true, force: true });
renameSync(workRoot, stageRoot);
// The isolation contract: nothing outside linux/ may have changed.
if (!options.allowDirty) checkRepoClean(options);
const stagedBundle = path.join(stageRoot, 'Luminary');
// Hand-off copy. Staging and the archives stay outside the checkout; this is
// the one write into the repository, into linux/releases.
const published = [];
if (options.publish) {
mkdirSync(RELEASES_DIR, { recursive: true });
const sums = [];
for (const artifact of [tarPath, ...(debPath ? [debPath] : [])]) {
const target = path.join(RELEASES_DIR, path.basename(artifact));
cpSync(artifact, target);
sums.push(`${sha256File(target)} ${path.basename(target)}`);
log('publish', path.relative(ROOT, target));
published.push(target);
}
writeFileSync(path.join(RELEASES_DIR, 'SHA256SUMS.txt'), `${sums.join('\n')}\n`);
}
process.stdout.write(
[
'',
'linux build PASSED',
` artifact ${tarPath}`,
` size ${(archive.bytes / 1024 / 1024).toFixed(1)} MB (${archive.files} entries)`,
` sha256 ${sha256File(tarPath)}`,
` node ${options.node} linux-x64 (${(nodeBinSize / 1024 / 1024).toFixed(0)} MB binary)`,
` launcher luminary (bash)`,
...(debPath
? [
` deb ${debPath}`,
` deb size ${(statSync(debPath).size / 1024 / 1024).toFixed(1)} MB`,
]
: []),
` staged ${stagedBundle}`,
...published.map((file) => ` publish ${path.relative(ROOT, file)}`),
'',
published.length
? 'Only linux/ was written: the archives in linux/releases are ready to transfer.'
: 'The repository was not modified; only linux/ and the output directory were touched.',
'',
].join('\n'),
);
return 0;
}
main().then(
(code) => {
process.exitCode = code;
},
(error) => {
fail(error instanceof Error ? error.message : String(error));
},
);
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# Add this Luminary bundle to the Ubuntu applications menu.
#
# Creates ~/.local/share/applications/luminary.desktop pointing at this folder,
# so keep the folder where it is (or re-run this after moving it). Photos and the
# catalog stay in ~/.local/share/luminary and are never touched by the menu entry.
set -euo pipefail
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
exec "$here/luminary" --install
+357
View File
@@ -0,0 +1,357 @@
#!/usr/bin/env bash
# Luminary desktop launcher for Linux.
#
# Starts the bundled server in single-user desktop mode on a free loopback port,
# waits for /api/health, then opens the UI in a chromeless app window (Chrome,
# Chromium, Edge, Brave or Vivaldi). Firefox, or the default browser, is the
# fallback.
#
# ./luminary start and open the window
# ./luminary --stop stop the running server
# ./luminary --status report pid, URL, data folder and health
# ./luminary --browser open a normal browser tab instead
# ./luminary --verify check that this is a complete bundle
# ./luminary --install add Luminary to the applications menu
# ./luminary --uninstall remove that menu entry
#
# Everything the app writes lives in ~/.local/share/luminary (or $LUMINARY_DATA),
# never inside this folder, so the bundle can be moved or deleted safely.
set -u
SELF="$(readlink -f "${BASH_SOURCE[0]}")"
BUNDLE="$(dirname "$SELF")"
APP="$BUNDLE/app"
DATA_DIR="${LUMINARY_DATA:-${XDG_DATA_HOME:-$HOME/.local/share}/luminary}"
LOG_DIR="$DATA_DIR/logs"
PID_FILE="$DATA_DIR/luminary.pid"
RUNTIME_FILE="$DATA_DIR/runtime.json"
FIRST_PORT=8787
LAST_PORT=8887
WINDOW_MODE="${LUMINARY_WINDOW:-window}"
say() { printf '%s\n' "$*"; }
problem() { printf 'Luminary: %s\n' "$*" >&2; }
usage() {
sed -n '2,18p' "$SELF" | sed 's/^# \{0,1\}//'
}
find_node() {
if [ -x "$BUNDLE/runtime/bin/node" ]; then
NODE="$BUNDLE/runtime/bin/node"
return 0
fi
if command -v node >/dev/null 2>&1; then
NODE="$(command -v node)"
return 0
fi
problem "No Node runtime found: runtime/bin/node is missing and there is no node on PATH."
problem "Download this bundle again, or install Node 24 (https://nodejs.org)."
return 1
}
node_is_recent() {
"$NODE" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 24 ? 0 : 1)' 2>/dev/null
}
port_free() {
! (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null
}
choose_port() {
local port="$FIRST_PORT"
while [ "$port" -le "$LAST_PORT" ]; do
if port_free "$port"; then
printf '%s' "$port"
return 0
fi
port=$((port + 1))
done
return 1
}
running_pid() {
[ -f "$PID_FILE" ] || return 1
local pid
pid="$(cat "$PID_FILE" 2>/dev/null)"
[ -n "$pid" ] || return 1
kill -0 "$pid" 2>/dev/null || return 1
printf '%s' "$pid"
}
current_port() {
[ -f "$RUNTIME_FILE" ] || return 1
sed -n 's/.*"port": *\([0-9][0-9]*\).*/\1/p' "$RUNTIME_FILE" | head -n 1
}
wait_health() {
local url="http://127.0.0.1:$1/api/health" tries=0
while [ "$tries" -lt 150 ]; do
if "$NODE" -e "fetch('$url').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))" >/dev/null 2>&1; then
return 0
fi
tries=$((tries + 1))
sleep 0.2
done
return 1
}
verify_bundle() {
local missing=0
for rel in runtime/bin/node app/server/index.mjs app/dist/index.html luminary; do
if [ ! -e "$BUNDLE/$rel" ]; then
problem "missing: $rel"
missing=1
fi
done
if [ -d "$APP/node_modules" ]; then
say "node_modules: present"
else
problem "missing: app/node_modules (production dependencies)"
missing=1
fi
if [ "$missing" -ne 0 ]; then
problem "This folder is not a complete Luminary bundle; extract the whole tarball."
return 1
fi
say "Bundle: $BUNDLE"
say "Version: $(sed -n '1p' "$BUNDLE/version.txt" 2>/dev/null)"
if find_node; then
say "Node: $("$NODE" --version 2>/dev/null) ($NODE)"
fi
return 0
}
start() {
local pid port
pid="$(running_pid)" && {
port="$(current_port)"
if [ -n "${port:-}" ]; then
say "Luminary is already running at http://127.0.0.1:$port (pid $pid)."
open_window "http://127.0.0.1:$port"
return 0
fi
say "Luminary is already running (pid $pid)."
return 0
}
verify_bundle >/dev/null || return 1
find_node || return 1
if ! node_is_recent; then
problem "Node $("$NODE" --version 2>/dev/null) is too old; Luminary needs Node 24 or newer."
return 1
fi
mkdir -p "$DATA_DIR" "$LOG_DIR" || {
problem "could not create $DATA_DIR"
return 1
}
chmod 700 "$DATA_DIR" 2>/dev/null || true
port="$(choose_port)" || {
problem "no free loopback port between $FIRST_PORT and $LAST_PORT"
return 1
}
(
cd "$APP" || exit 1
LUMINARY_LOCAL=1 \
PORT="$port" \
HOST=127.0.0.1 \
NODE_ENV=production \
LUMINARY_DATA="$DATA_DIR" \
nohup "$NODE" server/index.mjs >>"$LOG_DIR/server.out.log" 2>>"$LOG_DIR/server.err.log" &
printf '%s\n' "$!" >"$PID_FILE"
)
pid="$(cat "$PID_FILE" 2>/dev/null)"
if ! wait_health "$port"; then
problem "the server did not answer on /api/health."
problem "See $LOG_DIR/server.err.log, or run: cd \"$APP\" && \"$NODE\" server/index.mjs"
return 1
fi
printf '{"pid": %s, "port": %s, "url": "http://127.0.0.1:%s", "data": "%s"}\n' \
"$pid" "$port" "$port" "$DATA_DIR" >"$RUNTIME_FILE"
say "Luminary is running at http://127.0.0.1:$port (pid $pid)"
say "Data: $DATA_DIR"
if [ "$WINDOW_MODE" = "browser" ]; then
open_tab "http://127.0.0.1:$port"
elif [ "$WINDOW_MODE" = "none" ]; then
# Used by SMOKE-LINUX.sh: start the server but do not open anything.
:
else
open_window "http://127.0.0.1:$port" || open_tab "http://127.0.0.1:$port"
fi
return 0
}
stop() {
local pid
if ! pid="$(running_pid)"; then
rm -f "$PID_FILE" "$RUNTIME_FILE"
say "Luminary is not running."
return 0
fi
kill "$pid" 2>/dev/null
local tries=0
while kill -0 "$pid" 2>/dev/null && [ "$tries" -lt 50 ]; do
tries=$((tries + 1))
sleep 0.1
done
if kill -0 "$pid" 2>/dev/null; then
kill -9 "$pid" 2>/dev/null
fi
rm -f "$PID_FILE" "$RUNTIME_FILE"
say "Stopped Luminary (pid $pid)."
}
status() {
local pid port
say "Bundle: $BUNDLE"
say "Data: $DATA_DIR"
if pid="$(running_pid)"; then
port="$(current_port)"
say "Status: running (pid $pid)"
if [ -n "${port:-}" ]; then
say "URL: http://127.0.0.1:$port"
find_node >/dev/null 2>&1 &&
"$NODE" -e "fetch('http://127.0.0.1:$port/api/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))" >/dev/null 2>&1 &&
say "Health: ok" || say "Health: unreachable"
fi
else
say "Status: stopped"
fi
say "Logs: $LOG_DIR"
}
browser_candidates() {
printf '%s\n' google-chrome google-chrome-stable chromium chromium-browser \
microsoft-edge microsoft-edge-stable brave-browser vivaldi-stable
}
open_window() {
local url="$1" name browser
while IFS= read -r name; do
if browser="$(command -v "$name" 2>/dev/null)"; then
say "Opening the app window with $name"
setsid "$browser" \
--app="$url" \
--user-data-dir="$DATA_DIR/window-profile" \
--class=Luminary \
--no-first-run \
--no-default-browser-check \
>/dev/null 2>&1 &
return 0
fi
done <<EOF
$(browser_candidates)
EOF
if command -v firefox >/dev/null 2>&1; then
say "No Chromium-based browser found; opening Firefox."
setsid firefox --new-window "$url" >/dev/null 2>&1 &
return 0
fi
return 1
}
open_tab() {
local url="$1"
if command -v xdg-open >/dev/null 2>&1; then
setsid xdg-open "$url" >/dev/null 2>&1 &
say "Opening $url in your browser."
return 0
fi
say "Open $url in your browser."
return 0
}
desktop_dir() {
printf '%s' "${XDG_DATA_HOME:-$HOME/.local/share}/applications"
}
icon_dir() {
printf '%s' "${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/256x256/apps"
}
install_menu_entry() {
local apps icons entry
apps="$(desktop_dir)"
icons="$(icon_dir)"
mkdir -p "$apps" "$icons" || {
problem "could not create $apps"
return 1
}
if [ -f "$BUNDLE/Luminary.png" ]; then
cp "$BUNDLE/Luminary.png" "$icons/luminary.png"
fi
entry="$apps/luminary.desktop"
cat >"$entry" <<EOF
[Desktop Entry]
Type=Application
Version=1.0
Name=Luminary
GenericName=Photo library
Comment=Photo library and raw editor
Exec="$SELF"
Path=$BUNDLE
Icon=$icons/luminary.png
Terminal=false
Categories=Graphics;Photography;
Keywords=photo;raw;catalog;editor;
StartupNotify=true
StartupWMClass=Luminary
EOF
chmod +x "$entry"
if command -v update-desktop-database >/dev/null 2>&1; then
update-desktop-database "$apps" >/dev/null 2>&1 || true
fi
say "Added Luminary to your applications menu: $entry"
say "If it does not appear yet, log out and back in."
}
uninstall_menu_entry() {
local entry
entry="$(desktop_dir)/luminary.desktop"
rm -f "$entry"
rm -f "$(icon_dir)/luminary.png"
if command -v update-desktop-database >/dev/null 2>&1; then
update-desktop-database "$(desktop_dir)" >/dev/null 2>&1 || true
fi
say "Removed the menu entry. Your photos and catalog in $DATA_DIR were kept."
}
case "${1:-}" in
""|--start)
start
;;
--stop)
stop
;;
--status)
status
;;
--browser)
WINDOW_MODE=browser
start
;;
--verify)
verify_bundle
;;
--install)
install_menu_entry
;;
--uninstall)
uninstall_menu_entry
;;
--help|-h)
usage
;;
*)
problem "unknown option $1"
usage >&2
exit 2
;;
esac
+3
View File
@@ -0,0 +1,3 @@
# Transfer-only release archives: keep the checksums reviewable, not the tarballs.
*.tar.gz
*.deb
+29
View File
@@ -0,0 +1,29 @@
# Linux release hand-off
`node linux/build.mjs --skip-build --publish` drops the finished artifacts here:
```
Luminary-0.5.1-linux-x64.tar.gz portable bundle
Luminary-0.5.1-linux-amd64.deb Ubuntu package
SHA256SUMS.txt
```
The archives are git-ignored; only `SHA256SUMS.txt` and this note are tracked,
so the checksums stay reviewable while the multi-hundred-megabyte archives do
not end up in the repository (or in the deploy rsync).
Verify a copy with:
```bash
sha256sum -c SHA256SUMS.txt
tar -tzf Luminary-0.5.1-linux-x64.tar.gz | head
dpkg-deb --info Luminary-0.5.1-linux-amd64.deb
```
On Ubuntu the easiest install is `sudo apt install ./Luminary-0.5.1-linux-amd64.deb`,
which adds Luminary to the applications menu. The portable route is to extract
the whole tarball and run `./luminary` from the extracted `Luminary` folder;
`./install.sh` adds that copy to the applications menu.
After publishing, the product site needs the new `.deb` copied to
`luminary-site/downloads/` with the size and SHA-256 in its download card.
+2
View File
@@ -0,0 +1,2 @@
7b2f91d603b49aa19734e681278a16f8024018c618b1c342d2607c75a2e6722f Luminary-0.5.1-linux-x64.tar.gz
5649939b748946409a99d6e8e99a4d5a5613f7602458b23d9af23ef9b7f65d04 Luminary-0.5.1-linux-amd64.deb
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 975 KiB

+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "luminary", "name": "luminary",
"version": "1.0.0", "version": "0.5.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "luminary", "name": "luminary",
"version": "1.0.0", "version": "0.5.1",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"exifr": "^7.1.3", "exifr": "^7.1.3",
+4 -1
View File
@@ -2,7 +2,7 @@
"name": "luminary", "name": "luminary",
"private": true, "private": true,
"license": "MIT", "license": "MIT",
"version": "1.0.0", "version": "0.5.1",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -13,6 +13,9 @@
"preview": "vite preview", "preview": "vite preview",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"test": "vitest run", "test": "vitest run",
"check:render": "node scripts/render-check.mjs",
"predeploy": "node scripts/predeploy.mjs",
"deploy": "node scripts/deploy.mjs",
"build:lens-db": "node scripts/build-lens-db.mjs" "build:lens-db": "node scripts/build-lens-db.mjs"
}, },
"dependencies": { "dependencies": {
Binary file not shown.
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env node
/**
* Deploy Luminary: run the predeploy gate, then copy the source to the server,
* rebuild it there and restart the service.
*
* The gate runs first and a failure exits before anything touches the server,
* so a type error, a failing test or a shader regression caught by the render
* check cannot reach production. The local bundle is compared with the one the
* server just built, so a deploy that silently ships stale assets is visible.
*
* Exits via process.exitCode rather than process.exit(): stdout/stderr are
* async when piped, and exiting early truncates the very lines that explain
* why a deploy stopped.
*
* Environment:
* LUMINARY_DEPLOY_HOST ssh target, e.g. bhursey@photos.example.org (required)
* LUMINARY_DEPLOY_PATH remote checkout of this repo (default /srv/luminary)
* LUMINARY_DEPLOY_SERVICE systemd unit to restart (default luminary)
* LUMINARY_DEPLOY_SSH_PASS optional ssh password, passed to sshpass via env
* LUMINARY_DEPLOY_SUDO_PASS optional sudo password for the remote build/restart
*/
import { execFileSync } from 'node:child_process';
import { existsSync, readdirSync } from 'node:fs';
import path from 'node:path';
const env = process.env;
const HOST = env.LUMINARY_DEPLOY_HOST;
const REMOTE_PATH = env.LUMINARY_DEPLOY_PATH || '/srv/luminary';
const SERVICE = env.LUMINARY_DEPLOY_SERVICE || 'luminary';
const SSH_PASS = env.LUMINARY_DEPLOY_SSH_PASS || '';
const SUDO_PASS = env.LUMINARY_DEPLOY_SUDO_PASS || '';
/** Local-only state that must never be copied over the server's copy. */
const EXCLUDES = [
'node_modules',
'dist',
'data',
'.git',
'.freebuff',
'.check',
'.smoke',
'logo.png',
'*.log',
];
function run(command, args, extraEnv) {
execFileSync(command, args, {
stdio: 'inherit',
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
});
}
function sshArgs(script) {
return ['-o', 'StrictHostKeyChecking=accept-new', HOST, script];
}
/** Runs a remote script with stdout echoed, returning what it printed. */
function sshCapture(script, input) {
const piped = input !== undefined;
const output = execFileSync(
SSH_PASS ? 'sshpass' : 'ssh',
SSH_PASS ? ['-e', 'ssh', ...sshArgs(script)] : sshArgs(script),
{
stdio: [piped ? 'pipe' : 'inherit', 'pipe', 'inherit'],
input,
encoding: 'utf8',
env: SSH_PASS ? { ...process.env, SSHPASS: SSH_PASS } : process.env,
},
);
process.stdout.write(output);
return output;
}
function localBundles() {
const dir = path.join(process.cwd(), 'dist', 'assets');
if (!existsSync(dir)) return [];
return readdirSync(dir)
.filter((file) => /^index-.*\.(js|css)$/.test(file))
.sort();
}
function main() {
if (!HOST) {
console.error('deploy: set LUMINARY_DEPLOY_HOST to the ssh target, e.g. user@server.');
return 2;
}
// 1. Gate. Nothing below this line may run if the gate fails.
// npm runs a script called "predeploy" before "deploy", so under `npm run
// deploy` the gate has already passed before this process starts; running it
// again would typecheck and render-check the same source twice. Invoked
// directly, this script has to run the gate itself.
if (env.npm_lifecycle_event === 'deploy') {
console.log('deploy: predeploy gate passed (npm predeploy hook)');
} else {
console.log('deploy: predeploy gate');
try {
run(process.execPath, [path.join('scripts', 'predeploy.mjs')]);
} catch {
console.error('deploy: aborted - predeploy failed, nothing was sent to the server.');
return 1;
}
}
// 2. Copy the source, keeping server-side data and build output.
console.log(`\ndeploy: rsync to ${HOST}:${REMOTE_PATH}`);
const rsyncArgs = ['-az'];
for (const item of EXCLUDES) rsyncArgs.push(`--exclude=${item}`);
const remoteShell = SSH_PASS
? `sshpass -e ssh -o StrictHostKeyChecking=accept-new`
: `ssh -o StrictHostKeyChecking=accept-new`;
rsyncArgs.push('-e', remoteShell, './', `${HOST}:${REMOTE_PATH}/`);
try {
run('rsync', rsyncArgs, SSH_PASS ? { SSHPASS: SSH_PASS } : undefined);
} catch {
console.error('deploy: aborted - rsync failed.');
return 1;
}
// 3. Rebuild and restart there, then report what is actually being served.
const sudo = SUDO_PASS ? `sudo -S -p '' ` : '';
const sudoLines = SUDO_PASS ? `${SUDO_PASS}\n${SUDO_PASS}\n` : undefined;
const script = [
`cd ${REMOTE_PATH} || exit 3`,
`${sudo}npm run build`,
'build=$?',
'[ "$build" -eq 0 ] || { echo "deploy: remote build failed ($build)"; exit "$build"; }',
`${sudo}systemctl restart ${SERVICE}`,
'sleep 2',
`systemctl is-active ${SERVICE}`,
'sha256sum dist/assets/*.js dist/assets/*.css',
].join('\n');
console.log(`\ndeploy: build and restart ${SERVICE} on ${HOST}`);
let output;
try {
output = sshCapture(script, sudoLines);
} catch {
console.error('deploy: aborted - the remote build or restart failed.');
return 1;
}
// 4. The server must be serving the bundle the gate just reviewed.
const remoteHashes = new Map();
for (const line of output.split('\n')) {
const match = /^([0-9a-f]{64})\s+dist\/assets\/(index-[^/\s]+)$/.exec(line.trim());
if (match) remoteHashes.set(match[2], match[1]);
}
const missing = localBundles().filter((file) => !remoteHashes.has(file));
if (missing.length) {
console.error(
`\ndeploy: FAILED - the server is not serving ${missing.join(', ')}; check the remote build.`,
);
return 1;
}
const served = [...remoteHashes.entries()];
console.log(
`\ndeploy PASSED: ${SERVICE} is active on ${HOST} serving ${served
.map(([file, hash]) => `${file} (${hash.slice(0, 12)})`)
.join(', ')}.`,
);
return 0;
}
process.exitCode = main();
+672
View File
@@ -0,0 +1,672 @@
#!/usr/bin/env node
/**
* Render film-look sample frames and build the film gallery page.
*
* Every frame is produced by the app's own WebGL renderer with the preset's real
* edits, so the gallery shows what Luminary actually does rather than a mock-up.
* Black and white looks are documented with the contrast filter they carry, and
* one stock is rendered through every colour filter the editor offers.
*
* node scripts/film-samples.mjs --photo sample.jpg
* node scripts/film-samples.mjs --photo sample.jpg --out /tmp/film --per-category 2
*
* Output stays outside the checkout (default ~/.cache/luminary-film-gallery):
*
* <out>/original.jpg the untouched frame
* <out>/<preset-id>.jpg one frame per sampled stock
* <out>/<preset-id>--<filter>.jpg the black and white filter demo
* <out>/film.html the gallery page
* <out>/film-looks.json the catalogue data
*
* Copy the frames to the site's assets/film/ and film.html to the site root.
* Needs Chrome/Chromium with WebGL2 (SwiftShader is used when there is no GPU).
*/
import { spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import sharp from 'sharp';
import { createServer } from 'vite';
import { FILM_PRESETS } from '../src/lib/presets.ts';
// Filled from Vite's ssrLoadModule below: edits.ts imports './curves' without an
// extension, which Node's own resolver cannot follow from a plain import here.
let BW_FILTERS = [];
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const DIR = path.join(ROOT, '.film-samples');
const PAGE = path.join(DIR, 'index.html');
const PORT = 5201;
const RENDER_WIDTH = 1000;
const RENDER_HEIGHT = 667;
const JPEG_QUALITY = 84;
/** The stock used to show what each B&W contrast filter does. */
const BW_DEMO_STOCK = 'film-tri-x-400';
const FILTER_HINTS = {
none: 'No filter: the stock as it renders by default',
yellow: 'Mild: slightly darker sky, natural skin',
orange: 'Stronger: deeper sky, warmer skin separation',
red: 'Dramatic: near-black sky, bright skin and foliage highlights',
green: 'Lifts foliage, darkens lips and skin blemishes',
blue: 'Lightens haze and shadow detail, darkens skin',
};
const CATEGORY_ORDER = [
'Colour Negative',
'Colour Slide',
'Black & White',
'Cinema',
'Instant',
'Redscale',
'Experimental',
];
const CATEGORY_HINTS = {
'Colour Negative':
'C-41 print films: warm skin, open shadows and the colour people mean by "film".',
'Colour Slide':
'E-6 and K-14 reversal films: dense blacks, saturated colour and very little latitude.',
'Black & White':
'Panchromatic stocks and chromogenic B&W, each with its own grain, contrast and colour filter.',
Cinema: 'Motion-picture negatives: flat midtones and soft shoulders, built to grade.',
Instant: 'Integral and peel-apart instant film: lifted blacks, soft colour, gentle contrast.',
Redscale: 'Film exposed through its base: amber highlights, red midtones, deep shadows.',
Experimental:
'Cross-process, faded print, infrared and other deliberate departures from a normal negative.',
};
/** Three representative stocks per category: the ones people ask for by name. */
const SAMPLE_PICKS = {
'Colour Negative': ['film-portra-400', 'film-gold-200', 'film-ektar-100'],
'Colour Slide': ['film-velvia-50', 'film-provia-100f', 'film-kodachrome-64'],
'Black & White': ['film-tri-x-400', 'film-tmax-100', 'film-hp5-plus-400'],
Cinema: ['film-cinestill-800t', 'film-vision3-250d', 'film-cinestill-50d'],
Instant: ['film-polaroid-600', 'film-instax-mini', 'film-fp-100c'],
Redscale: ['film-redscale-xr', 'film-redscale-deep', 'film-redscale-gold-200'],
Experimental: ['film-lomochrome-purple', 'film-xpro-cross-process', 'film-aerochrome'],
};
const HELP = `Luminary film gallery generator
Usage: node scripts/film-samples.mjs --photo <file> [options]
--photo <file> source frame (JPEG/PNG) to render every look onto
--out <dir> output directory (default: <cache>/luminary-film-gallery)
--per-category <n> sampled stocks per category (default: 3, max: all picks)
--quality <1-100> JPEG quality for the frames (default: ${JPEG_QUALITY})
--help print this text
Frames come from the app's own renderer in headless Chrome, so WebGL2 must work
there (SwiftShader is fine). ${BW_DEMO_STOCK} is also rendered through every B&W
colour filter. The repository is not modified; the temporary render page is
deleted at the end.
`;
const CHROME_CANDIDATES = [
process.env.CHROME_PATH,
'google-chrome',
'google-chrome-stable',
'chromium',
'chromium-browser',
].filter(Boolean);
function fail(message) {
process.stderr.write(`film-samples: FAILED: ${message}\n`);
process.exit(1);
}
function log(step, message) {
process.stdout.write(`film-samples: ${step.padEnd(9)} ${message}\n`);
}
function parseArgs(argv) {
const options = {
photo: null,
out: path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-film-gallery'),
perCategory: 3,
quality: JPEG_QUALITY,
help: false,
};
const value = (index, flag) => {
const next = argv[index + 1];
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
return next;
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--photo') {
options.photo = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--out') {
options.out = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--per-category') {
options.perCategory = Number(value(i, arg));
i += 1;
} else if (arg === '--quality') {
options.quality = Number(value(i, arg));
i += 1;
} else if (arg === '--help' || arg === '-h') {
options.help = true;
} else {
fail(`unknown option ${arg} (see --help)`);
}
}
if (!Number.isInteger(options.perCategory) || options.perCategory < 1) {
fail('--per-category must be a positive integer');
}
if (!Number.isInteger(options.quality) || options.quality < 1 || options.quality > 100) {
fail('--quality must be 1-100');
}
if (!options.help && !options.photo) fail('--photo is required (see --help)');
if (options.photo && !existsSync(options.photo)) fail(`photo not found: ${options.photo}`);
return options;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function spawnSyncOk(bin) {
const probe = spawn(bin, ['--version'], { stdio: 'ignore' });
return new Promise((resolve) => {
probe.on('error', () => resolve(false));
probe.on('exit', (code) => resolve(code === 0));
});
}
async function findChrome() {
for (const candidate of CHROME_CANDIDATES) {
if (candidate.includes(path.sep)) {
if (existsSync(candidate)) return candidate;
continue;
}
if (await spawnSyncOk(candidate)) return candidate;
}
return null;
}
const PAGE_HTML = `<!doctype html>
<meta charset="utf-8" />
<pre id="out">boot</pre>
<script type="module">
import { Renderer } from '/src/gl/renderer.ts';
import { FILM_PRESETS } from '/src/lib/presets.ts';
import { defaultEdits, normalizeEdits } from '/src/lib/edits.ts';
const pre = document.getElementById('out');
try {
const canvas = document.createElement('canvas');
const renderer = new Renderer(canvas);
const blob = await (await fetch('/.film-samples/photo.jpg')).blob();
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
renderer.setImage(bitmap, null);
const size = { width: ${RENDER_WIDTH}, height: ${RENDER_HEIGHT} };
// filter is only used by the B&W strip: it overrides the stock's own filter.
window.renderLook = async (id, filter) => {
const preset = FILM_PRESETS.find((entry) => entry.id === id);
const edits = preset
? normalizeEdits(
filter
? { ...preset.edits, bw: true, bwFilter: filter, bwFilterAmount: 100 }
: preset.edits,
)
: defaultEdits();
renderer.render(edits, size);
return canvas.toDataURL('image/jpeg', ${JPEG_QUALITY} / 100);
};
window.ready = true;
pre.textContent = 'READY';
} catch (error) {
pre.textContent = 'ERROR ' + (error && error.message ? error.message : String(error));
}
</script>
`;
async function drive(chromeBin, url, jobs, outDir, quality) {
const port = 9333;
const child = spawn(
chromeBin,
[
'--headless=new',
'--no-sandbox',
'--disable-gpu-sandbox',
'--use-gl=angle',
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
`--remote-debugging-port=${port}`,
`--user-data-dir=${path.join(DIR, 'profile')}`,
'about:blank',
],
{ stdio: 'ignore' },
);
try {
let target = null;
for (let i = 0; i < 120 && !target; i++) {
try {
const res = await fetch(`http://127.0.0.1:${port}/json/list`);
target = (await res.json()).find((t) => t.type === 'page') ?? null;
} catch {
/* devtools not up yet */
}
if (!target) await sleep(250);
}
if (!target) throw new Error('Chrome DevTools endpoint never came up');
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
ws.onopen = resolve;
ws.onerror = () => reject(new Error('DevTools websocket failed'));
});
let nextId = 1;
const pending = new Map();
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.id && pending.has(message.id)) {
pending.get(message.id)(message);
pending.delete(message.id);
}
};
const send = (method, params = {}) => {
const id = nextId++;
return new Promise((resolve) => {
pending.set(id, resolve);
ws.send(JSON.stringify({ id, method, params }));
});
};
const evaluate = async (expression, awaitPromise = false) => {
const response = await send('Runtime.evaluate', {
expression,
awaitPromise,
returnByValue: true,
});
if (response.result?.exceptionDetails) {
throw new Error(
response.result.exceptionDetails.exception?.description ??
response.result.exceptionDetails.text,
);
}
return response.result?.result?.value;
};
await send('Page.enable');
await send('Runtime.enable');
await send('Page.navigate', { url });
const deadline = Date.now() + 120000;
let status = '';
while (Date.now() < deadline) {
status = (await evaluate("document.getElementById('out')?.textContent ?? ''")) ?? '';
if (status.startsWith('READY') || status.startsWith('ERROR')) break;
await sleep(400);
}
if (status.startsWith('ERROR')) throw new Error(status.slice(6));
if (!status.startsWith('READY')) throw new Error('the render page never became ready');
const written = [];
for (const job of jobs) {
const dataUrl = await evaluate(
`window.renderLook(${JSON.stringify(job.id)}, ${JSON.stringify(job.filter ?? null)})`,
true,
);
if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/jpeg;base64,')) {
throw new Error(`renderer returned no JPEG for ${job.file}`);
}
const buffer = Buffer.from(dataUrl.slice('data:image/jpeg;base64,'.length), 'base64');
const file = path.join(outDir, job.file);
// Re-encode so the frames carry consistent metadata and no EXIF bloat.
await sharp(buffer).jpeg({ quality, mozjpeg: true }).toFile(file);
log('render', `${job.file} (${(buffer.length / 1024).toFixed(0)} KB)`);
written.push(job.file);
}
ws.close();
return written;
} finally {
child.kill('SIGKILL');
await sleep(400);
}
}
/* ------------------------------------------------------------------ page ---- */
function escapeHtml(value) {
return String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function slug(category) {
return category
.toLowerCase()
.replace(/&/g, 'and')
.replace(/[^a-z0-9]+/g, '-')
.replace(/(^-|-$)/g, '');
}
function filterLabel(id) {
return BW_FILTERS.find((filter) => filter.id === id)?.label ?? null;
}
function buildFilterDemo(catalogue) {
const group = catalogue.find((entry) => entry.category === 'Black & White');
if (!group) return '';
const withFilter = group.looks.filter((look) => look.filter && look.filter !== 'none').length;
const figures = BW_FILTERS.map(
(filter) => `<figure>
<img src="assets/film/${BW_DEMO_STOCK}--${filter.id}.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" loading="lazy" alt="${escapeHtml(
filter.label,
)} filter on ${escapeHtml(group.looks.find((look) => look.id === BW_DEMO_STOCK)?.name ?? 'a black and white film')}">
<figcaption>${escapeHtml(filter.label)}</figcaption>
<p>${escapeHtml(FILTER_HINTS[filter.id] ?? '')}</p>
</figure>`,
).join('\n ');
return ` <div class="film-filter-demo">
<h3>Colour filters, the way they were used on the lens</h3>
<p class="film-filter-lede">
Before digital, contrast in black and white came from screwing a coloured filter onto
the lens: it held back its own colour, so a red filter turned a blue sky nearly black
while leaving skin bright, and a green one lifted foliage. Each monochrome look here
records the filter it was built with, and ${withFilter} of the ${group.looks.length}
name one. The same Tri-X 400 frame through every filter:
</p>
<div class="film-filters">
${figures}
</div>
<p class="fineprint">Filter strength is adjustable in the editor, so a look can be dialled back from the full strength shown here.</p>
</div>
`;
}
function buildPage(catalogue, framesByCategory) {
const total = catalogue.reduce((sum, group) => sum + group.looks.length, 0);
const chips = catalogue
.map(
(group) =>
`<a href="#${slug(group.category)}">${escapeHtml(group.category)} <span>${group.looks.length}</span></a>`,
)
.join('\n ');
const sections = catalogue
.map((group) => {
const frames = framesByCategory[group.category] ?? [];
const figures = frames
.map(
(frame) => `<figure class="film-set">
<img src="assets/film/${frame.id}.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" loading="lazy" alt="${escapeHtml(frame.name)} applied to the sample photograph">
<figcaption>${escapeHtml(frame.name)}${frame.iso ? ` · ISO ${frame.iso}` : ''}${
frame.process ? ` · ${escapeHtml(frame.process)}` : ''
}</figcaption>
</figure>`,
)
.join('\n ');
const looks = group.looks
.map(
(look) => `<li>
<span class="film-name">${escapeHtml(look.name)}</span>
<span class="film-meta">${[
look.iso ? `ISO ${look.iso}` : '',
look.process ?? '',
look.filter && look.filter !== 'none' ? `${filterLabel(look.filter)} filter` : '',
]
.filter(Boolean)
.join(' · ')}</span>
${look.note ? `<span class="film-note">${escapeHtml(look.note)}</span>` : ''}
</li>`,
)
.join('\n ');
return ` <section class="section${group.index % 2 === 1 ? ' section-alt' : ''}" id="${slug(group.category)}">
<div class="wrap">
<div class="section-head">
<p class="kicker">${escapeHtml(group.category)} · ${group.looks.length} looks</p>
<h2>${escapeHtml(group.category)}</h2>
<p class="section-lede">${escapeHtml(CATEGORY_HINTS[group.category] ?? '')}</p>
</div>
${group.category === 'Black & White' ? buildFilterDemo(catalogue) : ''} <div class="film-sets">
${figures}
</div>
<ul class="film-looks">
${looks}
</ul>
</div>
</section>`;
})
.join('\n\n');
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Luminary film looks: ${total} documented film emulations</title>
<meta name="description" content="The full Luminary film pack: ${total} film looks by category, each with the stock, ISO, process and a note on the look, rendered on one frame by Luminary's own editor. Black and white looks also record their contrast filter.">
<meta name="theme-color" content="#0c0e11">
<meta property="og:title" content="Luminary film looks: ${total} documented emulations">
<meta property="og:description" content="Colour negative, slide, black and white, cinema, instant, redscale and experimental looks, with frames rendered by the editor itself and the B&W contrast filters shown side by side.">
<meta property="og:type" content="website">
<meta property="og:image" content="assets/film/film-portra-400.jpg">
<link rel="icon" href="assets/favicon.png" type="image/png">
<link rel="apple-touch-icon" href="assets/icon-256.png">
<link rel="stylesheet" href="styles.css?v=20261128g">
</head>
<body>
<a class="skip" href="#main">Skip to content</a>
<header class="site-header">
<div class="wrap header-inner">
<a class="brand" href="index.html" aria-label="Luminary home">
<span class="brand-mark"><img src="assets/icon-256.png" alt="" width="36" height="36"></span>
<span class="brand-name">Luminary</span>
</a>
<nav class="nav" aria-label="Main">
<a href="index.html#develop">Raw editing</a>
<a href="film.html">Film looks</a>
<a href="index.html#library">Organise</a>
<a href="index.html#proofing">Galleries</a>
<a href="index.html#downloads">Download</a>
</nav>
<div class="header-actions">
<details class="mobile-nav">
<summary>Menu</summary>
<nav class="mobile-menu" aria-label="Sections">
<a href="index.html#develop">Raw editing</a>
<a href="film.html">Film looks</a>
<a href="index.html#library">Organise</a>
<a href="index.html#proofing">Galleries</a>
<a href="index.html#downloads">Download</a>
<a href="index.html#install">Install</a>
</nav>
</details>
<a class="btn btn-primary btn-small" href="index.html#downloads">Download</a>
</div>
</div>
</header>
<main id="main">
<section class="hero film-hero" id="top">
<div class="wrap">
<p class="eyebrow"><span class="dot"></span> Film pack · ${total} looks</p>
<h1>${total} film looks.<br><em>One frame, one engine.</em></h1>
<p class="lede">
Every frame below was rendered by Luminary's own editor with the look applied to the
same photograph — no screenshots from another app, no pasted LUTs. Each entry lists
the stock it emulates, its ISO and process, and a note on what it does.
</p>
<div class="film-cats" aria-label="Categories">
${chips}
</div>
<p class="fineprint">Sample frame: a digital photograph, unedited, rendered at ${RENDER_WIDTH}×${RENDER_HEIGHT}. Grain and colour come from the look itself.</p>
</div>
</section>
<section class="section" id="sample">
<div class="wrap">
<figure class="film-original">
<img src="assets/film/original.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" alt="The sample photograph with no film look applied">
<figcaption>The starting frame: no look, no crop, no colour work.</figcaption>
</figure>
<p class="fineprint">
The black and white section also shows the colour-filter technique: the same stock
rendered through yellow, orange, red, green and blue filters, the way contrast was
shaped on film before digital.
</p>
</div>
</section>
${sections}
</main>
<footer class="site-footer">
<div class="wrap footer-inner">
<div class="footer-brand">
<span class="brand-mark small"><img src="assets/icon-256.png" alt="" width="28" height="28"></span>
<div>
<p class="footer-name">Luminary</p>
<p class="footer-note">A photo library and raw editor for people who'd rather own their photos. MIT licensed. © 2026 Brian Hursey.</p>
</div>
</div>
<nav class="footer-links" aria-label="Footer">
<a href="index.html">Product page</a>
<a href="index.html#downloads">Download</a>
<a href="index.html#changelog">Changelog</a>
<a href="https://git.maple-street.net/bhursey/luminary" target="_blank" rel="noopener">Source</a>
<a href="mailto:bhursey@gmail.com?subject=Luminary%20film%20looks">Feedback</a>
</nav>
</div>
</footer>
</body>
</html>
`;
}
/* ------------------------------------------------------------------ main ---- */
function filterDemoJobs() {
return BW_FILTERS.map((filter) => ({
id: BW_DEMO_STOCK,
filter: filter.id,
file: `${BW_DEMO_STOCK}--${filter.id}.jpg`,
}));
}
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
process.stdout.write(HELP);
return 0;
}
const chromeBin = await findChrome();
if (!chromeBin) {
fail('no Chrome/Chromium found; set CHROME_PATH or install one (WebGL2 is required)');
}
const categories = CATEGORY_ORDER.filter((category) =>
FILM_PRESETS.some((preset) => preset.category === category),
);
const catalogue = categories.map((category, index) => ({
category,
index,
looks: FILM_PRESETS.filter((preset) => preset.category === category).map((preset) => ({
id: preset.id,
name: preset.name,
iso: preset.film?.speed ?? null,
process: preset.film?.process ?? null,
filter: preset.edits.bw ? preset.edits.bwFilter ?? 'none' : null,
note: preset.description ?? null,
})),
}));
const framesByCategory = {};
const jobs = [{ id: 'original', file: 'original.jpg' }];
for (const group of catalogue) {
const picks = (SAMPLE_PICKS[group.category] ?? [])
.filter((id) => group.looks.some((look) => look.id === id))
.slice(0, options.perCategory);
framesByCategory[group.category] = picks.map((id) => {
const look = group.looks.find((entry) => entry.id === id);
return { id, name: look.name, iso: look.iso, process: look.process };
});
for (const id of picks) jobs.push({ id, file: `${id}.jpg` });
}
await mkdir(options.out, { recursive: true });
await rm(DIR, { recursive: true, force: true });
await mkdir(DIR, { recursive: true });
// A 3:2 frame keeps every look comparable; the page states the source size.
await sharp(options.photo)
.rotate()
.resize(RENDER_WIDTH, RENDER_HEIGHT, { fit: 'cover', position: 'centre' })
.jpeg({ quality: 95, chromaSubsampling: '4:4:4' })
.toFile(path.join(DIR, 'photo.jpg'));
const server = await createServer({
root: ROOT,
logLevel: 'error',
server: { host: '127.0.0.1', port: PORT, strictPort: false },
});
await server.listen();
const base = (server.resolvedUrls?.local?.[0] ?? `http://127.0.0.1:${PORT}/`).replace(/\/$/, '');
// The editor's own filter list, so the page cannot drift from the app.
BW_FILTERS = (await server.ssrLoadModule('/src/lib/edits.ts')).BW_FILTERS;
jobs.push(...filterDemoJobs());
await writeFile(PAGE, PAGE_HTML);
log('photo', `${path.relative(process.cwd(), options.photo)} → ${RENDER_WIDTH}×${RENDER_HEIGHT}`);
log('render', `${jobs.length} frames through the editor's renderer`);
let written;
try {
written = await drive(chromeBin, `${base}/.film-samples/`, jobs, options.out, options.quality);
} finally {
await server.close();
await rm(DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(() => {});
}
if (written.length !== jobs.length) fail(`only ${written.length} of ${jobs.length} frames rendered`);
await writeFile(
path.join(options.out, 'film-looks.json'),
`${JSON.stringify({ total: FILM_PRESETS.length, categories: catalogue }, null, 2)}\n`,
);
await writeFile(path.join(options.out, 'film.html'), buildPage(catalogue, framesByCategory));
const bytes = (
await Promise.all(written.map((file) => readFile(path.join(options.out, file))))
).reduce((sum, buffer) => sum + buffer.length, 0);
process.stdout.write(
[
'',
'film gallery PASSED',
` frames ${written.length} JPEGs, ${(bytes / 1024 / 1024).toFixed(1)} MB`,
` looks ${FILM_PRESETS.length} across ${catalogue.length} categories`,
` filters ${BW_FILTERS.length} on ${BW_DEMO_STOCK}`,
` page ${path.join(options.out, 'film.html')}`,
` data ${path.join(options.out, 'film-looks.json')}`,
'',
'Copy the frames to assets/film/ and film.html to the site root.',
'',
].join('\n'),
);
return 0;
}
main().then(
(code) => {
process.exitCode = code;
},
(error) => {
fail(error instanceof Error ? error.message : String(error));
},
);
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env node
/**
* Pre-deploy gate: typecheck, unit suite, render check, then the production
* build -- skipped when nothing that feeds the bundle has changed since the
* last successful build, so editing only a test file does not rebuild dist.
*
* The signature is stored under node_modules/.cache: that directory is
* gitignored and excluded from the deploy rsync, so it is per-checkout state
* and never travels to the server.
*
* Exits via process.exitCode rather than process.exit(): piped stdout is async
* and exiting early truncates the failure message.
*/
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import {
existsSync,
mkdirSync,
readFileSync,
readdirSync,
statSync,
writeFileSync,
} from 'node:fs';
import path from 'node:path';
const ROOT = process.cwd();
const CACHE = path.join(ROOT, 'node_modules', '.cache', 'luminary-predeploy.json');
/** Vite inputs: everything the bundle is built from, plus the config it reads. */
const INPUTS = [
'src',
'public',
'index.html',
'vite.config.ts',
'tsconfig.json',
'package.json',
'package-lock.json',
];
/** Test files never reach the bundle, so their edits must not force a rebuild. */
const NOT_BUNDLED = /(^|\/)(__tests__|__mocks__|__fixtures__)(\/|$)|\.(test|spec)\.[cm]?[jt]sx?$/;
class StepFailed extends Error {}
function walk(target) {
if (!existsSync(target)) return [];
if (statSync(target).isFile()) return [target];
return readdirSync(target, { withFileTypes: true }).flatMap((entry) =>
walk(path.join(target, entry.name)),
);
}
function inputSignature() {
const files = INPUTS.flatMap((entry) => walk(entry))
.map((file) => path.relative(ROOT, file).split(path.sep).join('/'))
.filter((file) => !NOT_BUNDLED.test(file))
.sort();
const hash = createHash('sha256');
for (const file of files) {
hash.update(file);
hash.update('\0');
hash.update(readFileSync(path.join(ROOT, file)));
hash.update('\0');
}
return { count: files.length, digest: hash.digest('hex') };
}
function run(name, args) {
console.log(`\npredeploy: ${name}`);
try {
execFileSync('npm', args, { cwd: ROOT, stdio: 'inherit' });
} catch {
throw new StepFailed(name);
}
}
function main() {
const signature = inputSignature();
const previous = existsSync(CACHE) ? JSON.parse(readFileSync(CACHE, 'utf8')) : null;
const upToDate =
existsSync(path.join(ROOT, 'dist', 'index.html')) && previous?.digest === signature.digest;
try {
run('typecheck', ['run', 'typecheck']);
run('tests', ['run', 'test']);
run('render check', ['run', 'check:render']);
if (upToDate) {
console.log(
`\npredeploy: build skipped - the ${signature.count} bundle inputs are unchanged since the last build.`,
);
} else {
run('build', ['run', 'build']);
}
} catch (err) {
if (!(err instanceof StepFailed)) throw err;
console.error(`\npredeploy FAILED at ${err.message}.`);
return 1;
}
if (!upToDate) {
mkdirSync(path.dirname(CACHE), { recursive: true });
writeFileSync(
CACHE,
`${JSON.stringify({ digest: signature.digest, count: signature.count, at: new Date().toISOString() }, null, 2)}\n`,
);
}
console.log('\npredeploy PASSED.');
return 0;
}
process.exitCode = main();
+740
View File
@@ -0,0 +1,740 @@
#!/usr/bin/env node
/**
* Headless render check for the 16-bit proxy swap.
*
* The editor shows the JPEG proxy first and swaps in the 16-bit sidecar a few
* seconds later. Both uploads go through `Renderer.setImage`, and whether they
* agree depends on a WebGL detail that no unit test can cover: `UNPACK_FLIP_Y_WEBGL`
* is ignored for `ImageBitmap` sources (the proxy) but honoured for typed arrays
* (the sidecar). If the two disagree, the picture jumps upside down at the swap.
*
* This script builds a two-tone 16-bit PNG with the server's own encoder plus the
* matching JPEG, serves `parsePreview16` through Vite, and measures the rows that
* actually reach the GPU in headless Chrome. It fails if the top row of the proxy
* is not the top row of the sidecar.
*
* Runs outside `npm test` because it needs a WebGL2-capable Chrome:
* npm run check:render
*/
import { spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import { mkdir, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import sharp from 'sharp';
import { createServer } from 'vite';
import { encodePng16 } from '../server/imaging.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const DIR = path.join(ROOT, '.render-check');
const PAGE = path.join(DIR, 'index.html');
const W = 96;
const H = 64;
const CHROME_CANDIDATES = [
process.env.CHROME_PATH,
'google-chrome',
'google-chrome-stable',
'chromium',
'chromium-browser',
].filter(Boolean);
async function findChrome() {
for (const candidate of CHROME_CANDIDATES) {
if (candidate.includes(path.sep)) {
if (existsSync(candidate)) return candidate;
continue;
}
if (await spawnSyncOk(candidate)) return candidate;
}
return null;
}
function spawnSyncOk(bin) {
const probe = spawn(bin, ['--version'], { stdio: 'ignore' });
return new Promise((resolve) => {
probe.on('error', () => resolve(false));
probe.on('exit', (code) => resolve(code === 0));
});
}
/**
* Horizontal bands that exercise both ends of the range: one and two channels
* blown, one clean band, then one and two channels crushed, plus a green+blue
* crush to check the secondary colour. The same image proves the clipping
* overlay names the channels instead of painting every warning one colour.
*/
const BANDS = [
[1.0, 0.55, 0.08], // highlight: red only
[1.0, 1.0, 0.08], // highlight: red + green (yellow)
[0.24, 0.28, 0.35], // nothing clipped
[0.0, 0.3, 0.35], // shadow: red only
[0.0, 0.0, 0.35], // shadow: red + green (yellow)
[0.3, 0.0, 0.0], // shadow: green + blue (cyan)
];
function buildSource() {
const rgb16 = new Uint16Array(W * H * 3);
const rgb8 = new Uint8Array(W * H * 3);
const bands = BANDS;
for (let y = 0; y < H; y++) {
const band = bands[Math.min(bands.length - 1, Math.floor((y / H) * bands.length))];
for (let x = 0; x < W; x++) {
const i = (y * W + x) * 3;
for (let c = 0; c < 3; c++) {
rgb16[i + c] = Math.round(band[c] * 65535);
rgb8[i + c] = Math.round(band[c] * 255);
}
}
}
return { rgb8, rgb16 };
}
const PAGE_HTML = `<!doctype html>
<meta charset="utf-8" />
<pre id="out">boot</pre>
<script type="module">
import { parsePreview16 } from '/src/lib/preview16.ts';
import { Renderer } from '/src/gl/renderer.ts';
import { defaultEdits, defaultLocalComponent, defaultLocalLayer } from '/src/lib/edits.ts';
const pre = document.getElementById('out');
const half = (bits) => {
const s = bits >> 15 ? -1 : 1;
const e = (bits >> 10) & 0x1f;
const m = bits & 0x3ff;
if (e === 0) return s * m * Math.pow(2, -24);
if (e === 31) return m ? NaN : s * Infinity;
return s * (1 + m / 1024) * Math.pow(2, e - 15);
};
try {
const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl2', { alpha: false, antialias: false });
if (!gl) { pre.textContent = 'ERROR no WebGL2 in this Chrome'; throw new Error('no webgl2'); }
const makeTex = () => {
const t = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, t);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return t;
};
// readPixels rows start at the framebuffer's bottom row, which is texel row 0.
const rowLuma = (tex, y, w) => {
gl.bindTexture(gl.TEXTURE_2D, tex);
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
throw new Error('framebuffer incomplete');
}
const buf = new Uint8Array(w * 4);
gl.readPixels(0, y, w, 1, gl.RGBA, gl.UNSIGNED_BYTE, buf);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.deleteFramebuffer(fb);
let sum = 0;
for (let i = 0; i < w; i++) {
sum += 0.2126 * buf[i * 4] + 0.7152 * buf[i * 4 + 1] + 0.0722 * buf[i * 4 + 2];
}
return sum / w / 255;
};
const blob = await (await fetch('/.render-check/proxy.jpg')).blob();
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
const w = bitmap.width;
const h = bitmap.height;
// Exactly what Renderer.setImage does for the JPEG proxy.
const texFlip = makeTex();
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
const texNoFlip = makeTex();
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
const png = await (await fetch('/.render-check/side.p16.png')).arrayBuffer();
const parsed = await parsePreview16(png);
if (!parsed) throw new Error('parsePreview16 returned null');
if (parsed.width !== w || parsed.height !== h) {
throw new Error('sidecar ' + parsed.width + 'x' + parsed.height + ' vs proxy ' + w + 'x' + h);
}
// Exactly what Renderer.setImage does for the sidecar: rows in parser order, unflipped.
const sideRow = (y) => {
const out = new Uint8Array(w * 4);
for (let x = 0; x < w; x++) {
const i = (y * w + x) * 4;
const toByte = (bits) => Math.round(Math.min(1, Math.max(0, half(bits))) * 255);
out[x * 4] = toByte(parsed.rgba[i]);
out[x * 4 + 1] = toByte(parsed.rgba[i + 1]);
out[x * 4 + 2] = toByte(parsed.rgba[i + 2]);
out[x * 4 + 3] = 255;
}
const tex = makeTex();
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, out);
return tex;
};
const sideTopTex = sideRow(0);
const sideBottomTex = sideRow(h - 1);
const proxyTop = rowLuma(texFlip, 0, w);
const proxyBottom = rowLuma(texFlip, h - 1, w);
const proxyNoFlipTop = rowLuma(texNoFlip, 0, w);
const sideTop = rowLuma(sideTopTex, 0, w);
const sideBottom = rowLuma(sideBottomTex, 0, w);
const same = (a, b) => Math.abs(a - b) < 0.02;
// Clipping overlay: red for one clipped channel, yellow for two. This renders
// through the real Renderer, so a shader that collapses the warning to white
// (or loses the shadow/highlight bit) fails here.
const view = document.createElement('canvas');
const renderer = new Renderer(view);
renderer.setImage(bitmap, parsed);
renderer.render(defaultEdits(), { width: w, height: h, clipPreview: true });
const viewGl = view.getContext('webgl2');
const sampleBand = (index) => {
// readPixels rows start at the bottom, so flip the band centre.
const py = h - 1 - Math.floor((h * (index + 0.5)) / ${BANDS.length});
const px = new Uint8Array(4);
viewGl.readPixels(Math.floor(w / 2), py, 1, 1, viewGl.RGBA, viewGl.UNSIGNED_BYTE, px);
return [px[0], px[1], px[2]];
};
const clipPixels = [0, 1, 2].map(sampleBand);
const near = (pixel, target) =>
Math.abs(pixel[0] - target[0]) < 14 &&
Math.abs(pixel[1] - target[1]) < 14 &&
Math.abs(pixel[2] - target[2]) < 14;
const RED_MARK = [255, 31, 31];
const YELLOW_MARK = [255, 230, 26];
// The preview has to follow the sliders it is shown for: +6 EV blows every
// channel of the unclipped band, so it must turn white, not stay clear.
const brightEdits = defaultEdits();
brightEdits.exposure = 6;
renderer.render(brightEdits, { width: w, height: h, clipPreview: true });
const brightPixel = sampleBand(2);
// Shadow clipping: same palette at the other end of the histogram.
renderer.render(defaultEdits(), { width: w, height: h, clipping: 'shadows' });
const shadowPixels = [2, 3, 4, 5].map(sampleBand);
// And it has to move with the sliders, not just exist: -9 EV drives every
// channel of the clean band to black, so that band must turn white in shadow
// mode, just as it turns white at +6 EV in highlight mode.
const shadowEdits = defaultEdits();
shadowEdits.exposure = -9;
renderer.render(shadowEdits, { width: w, height: h, clipping: 'shadows' });
const shadowDarkPixel = sampleBand(2);
// Per-mask curve: a radial covering the whole frame, first with an identity
// curve and then with one that halves the output. The mask must leave the
// frame alone with the identity curve and darken it with the real one.
const maskLayer = defaultLocalLayer('radial', 0);
const maskShape = maskLayer.components[0];
maskShape.feather = 0;
maskShape.radial = { cx: 0.5, cy: 0.5, rx: 1.2, ry: 1.2 };
const darkCurve = [
{ x: 0, y: 0 },
{ x: 1, y: 0.4 },
];
const maskedEdits = defaultEdits();
maskedEdits.local = [{ ...maskLayer, curve: [{ x: 0, y: 0 }, { x: 1, y: 1 }] }];
renderer.render(maskedEdits, { width: w, height: h });
const maskIdentityPixel = sampleBand(2);
maskedEdits.local = [{ ...maskLayer, curve: darkCurve }];
renderer.render(maskedEdits, { width: w, height: h });
const maskCurvePixel = sampleBand(2);
// Mask groups: a second shape has to composite into the layer's own mask.
// Subtracting a frame-wide shape from an equally wide add shape clears the
// group, so the darkened curve must stop touching the frame; intersecting
// with the same shape keeps full coverage, so it must still darken.
const groupShape = defaultLocalComponent('radial');
groupShape.feather = 0;
groupShape.radial = { cx: 0.5, cy: 0.5, rx: 1.2, ry: 1.2 };
const groupEdits = defaultEdits();
groupEdits.local = [
{
...maskLayer,
curve: darkCurve,
components: [maskShape, { ...groupShape, mode: 'subtract' }],
},
];
renderer.render(groupEdits, { width: w, height: h });
const maskGroupSubtractPixel = sampleBand(2);
groupEdits.local = [
{
...maskLayer,
curve: darkCurve,
components: [maskShape, { ...groupShape, mode: 'intersect' }],
},
];
renderer.render(groupEdits, { width: w, height: h });
const maskGroupIntersectPixel = sampleBand(2);
// Brush masks are source-space and feather softens the rim inside the brush
// circle. The dab below has a radius of 0.08 of the frame width, so it spans
// 0.12 of the frame height; nothing outside that may be touched, even at a
// high feather, and the rim itself must be a gradient rather than a step.
const pixelAt = (fx, fy) => {
const px = new Uint8Array(4);
const py = h - 1 - Math.min(h - 1, Math.floor(fy * h));
viewGl.readPixels(Math.min(w - 1, Math.floor(fx * w)), py, 1, 1, viewGl.RGBA, viewGl.UNSIGNED_BYTE, px);
return [px[0], px[1], px[2]];
};
const dabRadiusY = 0.08 * (w / h);
const brushEdits = (feather) => {
const layer = defaultLocalLayer('brush', 0);
const shape = layer.components[0];
shape.feather = feather;
shape.brush.strokes = [{ points: [{ x: 0.25, y: 0.2 }], size: 0.08, erase: false }];
return { ...defaultEdits(), local: [{ ...layer, curve: darkCurve }] };
};
renderer.render(brushEdits(0), { width: w, height: h });
const dabHard = pixelAt(0.25, 0.2);
const dabOutsideHard = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
renderer.render(brushEdits(80), { width: w, height: h });
const dabSoft = pixelAt(0.25, 0.2);
const dabRimSoft = pixelAt(0.25, 0.2 + dabRadiusY * 0.75);
const dabOutsideSoft = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
// The develop view tints the baked mask instead of redrawing the stroke, so
// the overlay has to follow the same coverage: strong in the core, a real
// gradient at the rim, and nothing at all outside the brush circle.
renderer.render(brushEdits(80), { width: w, height: h, maskView: 0 });
const tintCore = pixelAt(0.25, 0.2);
const tintRim = pixelAt(0.25, 0.2 + dabRadiusY * 0.75);
const tintOutside = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
// Source-space alignment. Masks are baked over the whole source, so a crop
// that keeps a dab in frame but moves it on screen must move its tint and
// its local detail with it: source (0.6, 0.4) inside a quarter-frame crop
// lands at screen (0.4, 0.6), and nothing may be tinted at (0.6, 0.4).
const cropRect = {
x: 0.5,
y: 0.25,
w: 0.25,
h: 0.25,
angle: 0,
quarter: 0,
aspect: 'original',
flipH: false,
flipV: false,
};
const dabEdits = (at, size, adjust) => {
const layer = defaultLocalLayer('brush', 0);
const shape = layer.components[0];
shape.feather = 0;
shape.brush.strokes = [{ points: [at], size, erase: false }];
return {
...defaultEdits(),
local: [{ ...layer, adjust: { ...layer.adjust, ...(adjust || {}) } }],
};
};
const cropped = { ...defaultEdits(), crop: cropRect };
renderer.render(cropped, { width: w, height: h });
const cropRef = pixelAt(0.4, 0.6);
const cropRefOff = pixelAt(0.6, 0.4);
const cropDab = dabEdits({ x: 0.6, y: 0.4 }, 0.02);
cropDab.crop = cropRect;
renderer.render(cropDab, { width: w, height: h, maskView: 0 });
const cropTintOn = pixelAt(0.4, 0.6);
const cropTintOff = pixelAt(0.6, 0.4);
// Same crop and dab, but as a local detail amount instead of a tint: the
// finish pass has to read the mask through the same source coordinate.
const cropDetail = dabEdits({ x: 0.6, y: 0.4 }, 0.02, { dehaze: 100 });
cropDetail.crop = cropRect;
renderer.render(cropDetail, { width: w, height: h });
const cropDetailOn = pixelAt(0.4, 0.6);
const cropDetailOff = pixelAt(0.6, 0.4);
// Tint strength and toggle: full strength must read stronger than the default
// half, and no maskView at all must leave the photo untouched.
renderer.render(brushEdits(80), { width: w, height: h, maskView: 0, maskStrength: 1 });
const tintFull = pixelAt(0.25, 0.2);
renderer.render(brushEdits(80), { width: w, height: h });
const tintOffPixel = pixelAt(0.25, 0.2);
// Lens warp: a geometry map that magnifies the centre by 1.6 puts the dab at
// source (0.7, 0.45) at screen (0.625, 0.469); its source uv must be clear.
const lensN = 33;
const lensData = new Float32Array(lensN * lensN * 4);
for (let ly = 0; ly < lensN; ly++) {
for (let lx = 0; lx < lensN; lx++) {
const i = (ly * lensN + lx) * 4;
lensData[i] = 0.5 + ((lx + 0.5) / lensN - 0.5) * 1.6;
lensData[i + 1] = 0.5 + ((ly + 0.5) / lensN - 0.5) * 1.6;
lensData[i + 2] = 0;
lensData[i + 3] = 1;
}
}
const lensWarp = {
key: 'render-check-warp',
scale: 1,
geometry: { data: lensData, width: lensN, height: lensN },
};
renderer.render(defaultEdits(), { width: w, height: h, lens: lensWarp });
const lensRef = pixelAt(0.625, 0.469);
const lensRefOff = pixelAt(0.7, 0.469);
const lensDab = dabEdits({ x: 0.7, y: 0.45 }, 0.04);
renderer.render(lensDab, { width: w, height: h, lens: lensWarp, maskView: 0 });
const lensTintOn = pixelAt(0.625, 0.469);
const lensTintOff = pixelAt(0.7, 0.469);
pre.textContent = 'RESULT ' + JSON.stringify({
clipPixels,
clipRed: near(clipPixels[0], RED_MARK),
clipYellow: near(clipPixels[1], YELLOW_MARK),
clipClear:
!near(clipPixels[2], RED_MARK) &&
!near(clipPixels[2], YELLOW_MARK) &&
!near(clipPixels[2], [255, 255, 255]),
clipFollowsExposure: near(brightPixel, [255, 255, 255]),
brightPixel,
shadowPixels,
shadowClear:
!near(shadowPixels[0], RED_MARK) && !near(shadowPixels[0], YELLOW_MARK),
shadowRed: near(shadowPixels[1], RED_MARK),
shadowYellow: near(shadowPixels[2], YELLOW_MARK),
shadowCyan: near(shadowPixels[3], [26, 217, 255]),
shadowFollowsExposure: near(shadowDarkPixel, [255, 255, 255]),
shadowDarkPixel,
maskIdentityPixel,
maskCurvePixel,
maskIdentityFlat: near(maskIdentityPixel, [61, 71, 89]),
maskCurveDarkens: maskCurvePixel[0] < maskIdentityPixel[0] * 0.75,
maskGroupSubtractPixel,
maskGroupSubtractCleared: near(maskGroupSubtractPixel, maskIdentityPixel),
maskGroupIntersectPixel,
maskGroupIntersectDarkens: maskGroupIntersectPixel[0] < maskIdentityPixel[0] * 0.75,
dabHard,
dabOutsideHard,
dabSoft,
dabRimSoft,
dabOutsideSoft,
tintCore,
tintRim,
tintOutside,
// Orange tint: blue is the channel the overlay pushes up, so it ranks the
// coverage without depending on how dark the adjustment left the pixels.
tintFollowsMask: tintCore[2] > tintRim[2] && tintRim[2] > tintOutside[2] + 5,
tintBounded: Math.abs(tintOutside[2] - dabOutsideSoft[2]) <= 1,
cropRef,
cropRefOff,
cropTintOn,
cropTintOff,
cropDetailOn,
cropDetailOff,
lensRef,
lensRefOff,
lensTintOn,
lensTintOff,
tintFull,
tintOffPixel,
// The tint pushes red up hard on the dark mid band, so red ranks coverage.
cropTintAligned: cropTintOn[0] > cropRef[0] + 40,
cropTintBounded: Math.abs(cropTintOff[0] - cropRefOff[0]) <= 2,
// Local dehaze lifts the blue of that band, so blue marks where it landed.
cropDetailAligned: cropDetailOn[2] > cropDetailOff[2] + 10,
cropDetailBounded: Math.abs(cropDetailOff[2] - cropRefOff[2]) <= 3,
lensTintAligned: lensTintOn[0] > lensRef[0] + 40,
lensTintBounded: Math.abs(lensTintOff[0] - lensRefOff[0]) <= 2,
tintStrengthWorks: tintFull[2] > tintCore[2] + 8,
tintOffMatches: Math.abs(tintOffPixel[2] - dabSoft[2]) <= 1,
// A hard dab covers the core, and even an 80 % feather stops at the rim.
dabCoreDarkened: dabHard[0] < 140,
dabSoftCoreDarkened: dabSoft[0] < 140,
dabRimSmooth: dabRimSoft[0] > 140 && dabRimSoft[0] < 240,
dabBoundedHard: dabOutsideHard[0] > 240,
dabBoundedSoft: dabOutsideSoft[0] > 240,
flagHonouredForBitmap: !same(proxyTop, proxyNoFlipTop),
proxyTop: +proxyTop.toFixed(4),
sidecarTop: +sideTop.toFixed(4),
proxyBottom: +proxyBottom.toFixed(4),
sidecarBottom: +sideBottom.toFixed(4),
matchTop: same(proxyTop, sideTop),
matchBottom: same(proxyBottom, sideBottom),
reversed: same(proxyTop, sideBottom) && same(proxyBottom, sideTop),
});
} catch (err) {
if (!String(pre.textContent).startsWith('ERROR')) {
pre.textContent = 'ERROR ' + (err && err.message ? err.message : String(err));
}
}
</script>`;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function drive(chromeBin, url) {
const port = 9333 + Math.floor(Math.random() * 200);
const child = spawn(
chromeBin,
[
'--headless=new',
'--no-sandbox',
'--disable-gpu-sandbox',
'--use-gl=angle',
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
`--remote-debugging-port=${port}`,
`--user-data-dir=${path.join(DIR, 'profile')}`,
'about:blank',
],
{ stdio: 'ignore' },
);
try {
let target = null;
for (let i = 0; i < 120 && !target; i++) {
try {
const res = await fetch(`http://127.0.0.1:${port}/json/list`);
target = (await res.json()).find((t) => t.type === 'page') ?? null;
} catch {
/* devtools not up yet */
}
if (!target) await sleep(250);
}
if (!target) throw new Error('Chrome DevTools endpoint never came up');
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
ws.onopen = resolve;
ws.onerror = () => reject(new Error('DevTools websocket failed'));
});
let nextId = 1;
const pending = new Map();
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.id && pending.has(message.id)) {
pending.get(message.id)(message);
pending.delete(message.id);
}
};
const send = (method, params = {}) => {
const id = nextId++;
return new Promise((resolve) => {
pending.set(id, resolve);
ws.send(JSON.stringify({ id, method, params }));
});
};
await send('Page.enable');
await send('Runtime.enable');
await send('Page.navigate', { url });
let text = '';
const deadline = Date.now() + 90000;
while (Date.now() < deadline) {
const res = await send('Runtime.evaluate', {
expression: "document.getElementById('out')?.textContent ?? ''",
returnByValue: true,
});
text = res.result?.result?.value ?? '';
if (text.includes('RESULT') || text.startsWith('ERROR')) break;
await sleep(500);
}
ws.close();
return text;
} finally {
child.kill('SIGKILL');
// Chrome writes its profile until the process is gone; give it a moment so
// the cleanup below does not race the file handles it still holds.
await sleep(500);
}
}
async function main() {
const chromeBin = await findChrome();
const { rgb8, rgb16 } = buildSource();
await mkdir(DIR, { recursive: true });
await writeFile(path.join(DIR, 'proxy.jpg'), await sharp(rgb8, { raw: { width: W, height: H, channels: 3 } })
.jpeg({ quality: 96, chromaSubsampling: '4:4:4' })
.toBuffer());
await writeFile(path.join(DIR, 'side.p16.png'), encodePng16(rgb16, W, H));
await writeFile(PAGE, PAGE_HTML);
const server = await createServer({
root: ROOT,
logLevel: 'error',
server: { host: '127.0.0.1', port: 5199, strictPort: false },
});
await server.listen();
const base = server.resolvedUrls?.local?.[0] ?? 'http://127.0.0.1:5199/';
let text = '';
try {
if (!chromeBin) {
console.log('render check SKIPPED: no Chrome/Chromium found (set CHROME_PATH to run it).');
return 0;
}
text = await drive(chromeBin, `${base.replace(/\/$/, '')}/.render-check/`);
} finally {
await server.close();
}
if (text.startsWith('ERROR')) {
console.error(`render check FAILED: ${text.slice(6)}`);
return 1;
}
const marker = text.indexOf('RESULT');
if (marker < 0) {
console.error('render check FAILED: the probe never reported a result.');
console.error(text.slice(0, 500));
return 1;
}
const result = JSON.parse(text.slice(marker + 7));
console.log(
`render check: proxy top=${result.proxyTop} bottom=${result.proxyBottom}` +
` | sidecar top=${result.sidecarTop} bottom=${result.sidecarBottom}` +
` | flip flag honoured for ImageBitmap=${result.flagHonouredForBitmap}`,
);
console.log(
`render check: clipping overlay red=${JSON.stringify(result.clipPixels[0])}` +
` yellow=${JSON.stringify(result.clipPixels[1])}` +
` clear=${JSON.stringify(result.clipPixels[2])}` +
` | at +6EV the clear band is ${JSON.stringify(result.brightPixel)}`,
);
console.log(
`render check: shadow overlay clear=${JSON.stringify(result.shadowPixels[0])}` +
` red=${JSON.stringify(result.shadowPixels[1])}` +
` yellow=${JSON.stringify(result.shadowPixels[2])}` +
` cyan=${JSON.stringify(result.shadowPixels[3])}` +
` | at -9EV the clean band is ${JSON.stringify(result.shadowDarkPixel)}`,
);
console.log(
`render check: mask curve identity=${JSON.stringify(result.maskIdentityPixel)}` +
` darkened=${JSON.stringify(result.maskCurvePixel)}`,
);
console.log(
`render check: mask group subtract=${JSON.stringify(result.maskGroupSubtractPixel)}` +
` intersect=${JSON.stringify(result.maskGroupIntersectPixel)}`,
);
if (!result.matchTop || !result.matchBottom) {
console.error(
result.reversed
? 'render check FAILED: the sidecar lands upside down against the proxy.'
: 'render check FAILED: proxy and sidecar rows do not line up.',
);
return 1;
}
if (!result.clipRed || !result.clipYellow || !result.clipClear) {
console.error(
'render check FAILED: the clipping overlay lost its channel colours ' +
`(red=${result.clipRed}, yellow=${result.clipYellow}, clear=${result.clipClear}).`,
);
return 1;
}
if (!result.shadowClear || !result.shadowRed || !result.shadowYellow || !result.shadowCyan) {
console.error(
'render check FAILED: the shadow clipping overlay lost its channel colours ' +
`(clear=${result.shadowClear}, red=${result.shadowRed}, ` +
`yellow=${result.shadowYellow}, cyan=${result.shadowCyan}).`,
);
return 1;
}
if (!result.maskIdentityFlat || !result.maskCurveDarkens) {
console.error(
'render check FAILED: the per-mask curve is not reaching the grade ' +
`(identity=${JSON.stringify(result.maskIdentityPixel)}, ` +
`curve=${JSON.stringify(result.maskCurvePixel)}).`,
);
return 1;
}
if (!result.maskGroupSubtractCleared || !result.maskGroupIntersectDarkens) {
console.error(
'render check FAILED: mask group shapes are not compositing ' +
`(subtract=${JSON.stringify(result.maskGroupSubtractPixel)}, ` +
`intersect=${JSON.stringify(result.maskGroupIntersectPixel)}).`,
);
return 1;
}
if (!result.shadowFollowsExposure) {
console.error(
'render check FAILED: the shadow clipping overlay does not follow Exposure; ' +
`at -9EV the clean band stayed ${JSON.stringify(result.shadowDarkPixel)}.`,
);
return 1;
}
if (!result.clipFollowsExposure) {
console.error(
'render check FAILED: the clipping overlay does not follow Exposure; ' +
`the unclipped band stayed ${JSON.stringify(result.brightPixel)} at +6 EV.`,
);
return 1;
}
console.log(
`render check: brush dab hard=${JSON.stringify(result.dabHard)}` +
` outsideHard=${JSON.stringify(result.dabOutsideHard)} soft=${JSON.stringify(result.dabSoft)}` +
` rimSoft=${JSON.stringify(result.dabRimSoft)} outsideSoft=${JSON.stringify(result.dabOutsideSoft)}`,
);
console.log(
`render check: mask overlay core=${JSON.stringify(result.tintCore)}` +
` rim=${JSON.stringify(result.tintRim)} outside=${JSON.stringify(result.tintOutside)}`,
);
console.log(
`render check: crop mask tint on=${JSON.stringify(result.cropTintOn)}` +
` off=${JSON.stringify(result.cropTintOff)} ref=${JSON.stringify(result.cropRef)}` +
` | local detail on=${JSON.stringify(result.cropDetailOn)}` +
` off=${JSON.stringify(result.cropDetailOff)}`,
);
console.log(
`render check: lens mask tint on=${JSON.stringify(result.lensTintOn)}` +
` off=${JSON.stringify(result.lensTintOff)} ref=${JSON.stringify(result.lensRef)}` +
` | tint strength full=${JSON.stringify(result.tintFull)}` +
` half=${JSON.stringify(result.tintCore)}`,
);
if (
!result.cropTintAligned ||
!result.cropTintBounded ||
!result.cropDetailAligned ||
!result.cropDetailBounded ||
!result.lensTintAligned ||
!result.lensTintBounded ||
!result.tintStrengthWorks ||
!result.tintOffMatches
) {
console.error(
'render check FAILED: the local mask does not stay on its source pixels ' +
'through a crop or a lens warp ' +
`(crop tint ${JSON.stringify(result.cropTintOn)}/${JSON.stringify(result.cropTintOff)}` +
` vs ${JSON.stringify(result.cropRef)}, detail ` +
`${JSON.stringify(result.cropDetailOn)}/${JSON.stringify(result.cropDetailOff)}` +
`, lens tint ${JSON.stringify(result.lensTintOn)}/${JSON.stringify(result.lensTintOff)}` +
` vs ${JSON.stringify(result.lensRef)}).`,
);
return 1;
}
if (
!result.dabCoreDarkened ||
!result.dabSoftCoreDarkened ||
!result.dabRimSmooth ||
!result.dabBoundedHard ||
!result.dabBoundedSoft ||
!result.tintFollowsMask ||
!result.tintBounded
) {
console.error(
'render check FAILED: the brush mask does not follow the brush circle ' +
`(hard=${JSON.stringify(result.dabHard)}, rim=${JSON.stringify(result.dabRimSoft)}, ` +
`outsideHard=${JSON.stringify(result.dabOutsideHard)}, ` +
`outsideSoft=${JSON.stringify(result.dabOutsideSoft)}, ` +
`tint=${JSON.stringify(result.tintCore)}/${JSON.stringify(result.tintRim)}/` +
`${JSON.stringify(result.tintOutside)}).`,
);
return 1;
}
console.log(
'render check PASSED: proxy and sidecar share a row order and the clipping overlay names the channels.',
);
return 0;
}
let code = 1;
try {
code = await main();
} catch (err) {
console.error(`render check FAILED: ${err instanceof Error ? err.message : String(err)}`);
} finally {
await rm(DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(() => {
/* a stray Chrome profile is not worth failing the check over */
});
}
process.exit(code);
+10
View File
@@ -27,6 +27,16 @@ export const HOST = process.env.HOST || '0.0.0.0';
/** Shared invite code required to register after the first account exists. */ /** Shared invite code required to register after the first account exists. */
export const INVITE = setting('INVITE'); export const INVITE = setting('INVITE');
/**
* Single-user desktop mode, set by the Windows launcher (LUMINARY_LOCAL=1).
* The server creates one admin account and treats an unauthenticated request as
* that account, so a personal install never shows a signup or sign-in screen.
* Only safe on loopback, which is where the launcher binds; the server warns if
* it is enabled with a reachable HOST.
*/
export const LOCAL_MODE = setting('LOCAL') === '1';
export const LOCAL_EMAIL = setting('LOCAL_EMAIL', 'local@luminary');
/** Base URL of the dashboard this editor is bridged to, e.g. http://hub:3000. */ /** Base URL of the dashboard this editor is bridged to, e.g. http://hub:3000. */
export const GLENLOCH_URL = (process.env.GLENLOCH_URL || '').replace(/\/+$/, ''); export const GLENLOCH_URL = (process.env.GLENLOCH_URL || '').replace(/\/+$/, '');
+50
View File
@@ -281,6 +281,56 @@ if (!immichAlbumColumns.includes('kind')) {
db.exec("ALTER TABLE immich_albums ADD COLUMN kind TEXT NOT NULL DEFAULT 'import'"); db.exec("ALTER TABLE immich_albums ADD COLUMN kind TEXT NOT NULL DEFAULT 'import'");
} }
/**
* Applying a lens profile used to enable its vignetting correction, and that
* flat-field gain over-exposed the edges. The correction is opt-in now, so the
* flag older edits stored is cleared once, here, before anything reads the
* catalogue. Matching on the JSON text keeps the scan to the few rows that ever
* carried it, and the rows it rewrites no longer match, so it is idempotent.
*/
const legacyVignetting = db
.prepare(`SELECT id, data FROM photos WHERE instr(data, '"vignetting":true') > 0`)
.all();
if (legacyVignetting.length) {
const updateData = db.prepare('UPDATE photos SET data = ?, updated_at = ? WHERE id = ?');
const clear = (edits) => {
const lens = edits && edits.lens;
if (!lens || !lens.corrections || lens.corrections.vignetting !== true) return edits;
return { ...edits, lens: { ...lens, corrections: { ...lens.corrections, vignetting: false } } };
};
let cleared = 0;
for (const row of legacyVignetting) {
let record;
try {
record = JSON.parse(row.data);
} catch {
continue;
}
if (!record || typeof record !== 'object') continue;
let changed = false;
const strip = (edits) => {
const next = clear(edits);
if (next !== edits) changed = true;
return next;
};
record.edits = strip(record.edits);
if (Array.isArray(record.snapshots)) {
record.snapshots = record.snapshots.map((snap) =>
snap && snap.edits ? { ...snap, edits: strip(snap.edits) } : snap,
);
}
if (Array.isArray(record.history)) {
record.history = record.history.map((entry) =>
entry && entry.edits ? { ...entry, edits: strip(entry.edits) } : entry,
);
}
if (!changed) continue;
updateData.run(JSON.stringify(record), Date.now(), row.id);
cleared += 1;
}
if (cleared) console.log(`lens vignetting: cleared the stored corner gain on ${cleared} photo(s)`);
}
const q = { const q = {
upsertEvent: db.prepare(` upsertEvent: db.prepare(`
INSERT INTO events (id, owner_id, sort_index, created_at, data) VALUES (?, ?, ?, ?, ?) INSERT INTO events (id, owner_id, sort_index, created_at, data) VALUES (?, ?, ?, ?, ?)
+131 -14
View File
@@ -8,6 +8,8 @@ import {
DIST_DIR, DIST_DIR,
HOST, HOST,
INVITE, INVITE,
LOCAL_EMAIL,
LOCAL_MODE,
MAX_UPLOAD, MAX_UPLOAD,
PORT, PORT,
RAW_PREVIEW_EDGE, RAW_PREVIEW_EDGE,
@@ -78,7 +80,7 @@ import {
writeThumb16, writeThumb16,
} from './storage.mjs'; } from './storage.mjs';
import { previewRebuildTargets, startPreviewRebuild } from './previewRebuild.mjs'; import { previewRebuildTargets, startPreviewRebuild } from './previewRebuild.mjs';
import { decodeRaw, isRawName, rawSupport } from './raw.mjs'; import { decodeRaw, decodeStill, isRawName, isStillName, rawSupport } from './raw.mjs';
import { import {
bridgeConfigured, bridgeConfigured,
bridgeForEvent, bridgeForEvent,
@@ -124,7 +126,7 @@ import {
startImmichImport, startImmichImport,
} from './immich.mjs'; } from './immich.mjs';
const VERSION = '1.0.0'; const VERSION = '0.5.1';
const COOKIE = 'lumen_session'; const COOKIE = 'lumen_session';
/** Self-only policy; must allow the wasm engines and React inline styles. */ /** Self-only policy; must allow the wasm engines and React inline styles. */
@@ -337,6 +339,32 @@ function sessionCookie(req, token, maxAge) {
return `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`; return `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`;
} }
/**
* LUMINARY_LOCAL=1 (the Windows desktop bundle): one admin account, no signup,
* no sign-in, and an unauthenticated request is the local owner. The password
* is random and never shown, so the account cannot be signed into over a
* network; the launcher also binds loopback only.
*/
let localOwner = null;
async function prepareLocalOwner() {
if (!LOCAL_MODE) return;
const existing = users.byEmail(LOCAL_EMAIL);
if (existing) {
localOwner = publicUser(existing);
return;
}
const id = crypto.randomUUID();
users.create({
id,
email: LOCAL_EMAIL,
name: 'Local',
passHash: await hashPassword(crypto.randomBytes(32).toString('hex')),
role: 'admin',
});
localOwner = publicUser(users.byId(id));
}
function currentUser(req) { function currentUser(req) {
const cookieToken = parseCookies(req)[COOKIE]; const cookieToken = parseCookies(req)[COOKIE];
if (cookieToken) { if (cookieToken) {
@@ -346,7 +374,10 @@ function currentUser(req) {
if (user && !user.disabled) return publicUser(user); if (user && !user.disabled) return publicUser(user);
} }
} }
return authenticate(req); const authenticated = authenticate(req);
if (authenticated) return authenticated;
// A personal, loopback-only install has one owner: no credentials needed.
return LOCAL_MODE ? localOwner : null;
} }
function requireAdmin(req, res) { function requireAdmin(req, res) {
@@ -599,8 +630,10 @@ route('GET', '/api/health', async ({ req, res }) => {
ok: true, ok: true,
app: 'luminary', app: 'luminary',
version: VERSION, version: VERSION,
needsSetup: users.count() === 0, needsSetup: !LOCAL_MODE && users.count() === 0,
registrationOpen: users.count() === 0 || Boolean(INVITE) || invites.pendingCount() > 0, registrationOpen:
!LOCAL_MODE && (users.count() === 0 || Boolean(INVITE) || invites.pendingCount() > 0),
local: LOCAL_MODE,
photos: stats.photos, photos: stats.photos,
bytes: stats.bytes, bytes: stats.bytes,
// The absolute data path is only for signed-in team members. // The absolute data path is only for signed-in team members.
@@ -610,6 +643,9 @@ route('GET', '/api/health', async ({ req, res }) => {
}); });
route('POST', '/api/auth/register', async ({ req, res }) => { route('POST', '/api/auth/register', async ({ req, res }) => {
if (LOCAL_MODE) {
return error(res, 403, 'This is a single-user desktop install; accounts are not used');
}
const body = await readJson(req, 64 * 1024); const body = await readJson(req, 64 * 1024);
const email = normalizeEmail(body.email); const email = normalizeEmail(body.email);
const password = typeof body.password === 'string' ? body.password : ''; const password = typeof body.password === 'string' ? body.password : '';
@@ -665,6 +701,18 @@ route('POST', '/api/auth/register', async ({ req, res }) => {
}); });
route('POST', '/api/auth/login', async ({ req, res }) => { route('POST', '/api/auth/login', async ({ req, res }) => {
// Desktop mode has no password; hand out the local session so a stale login
// form or bookmark cannot strand the user on a sign-in screen.
if (LOCAL_MODE && localOwner) {
const token = createSession(localOwner.id);
return json(
res,
200,
{ token, user: localOwner },
{ 'Set-Cookie': sessionCookie(req, token, 30 * 24 * 3600) },
);
}
const ipKey = `login:ip:${clientIp(req)}`; const ipKey = `login:ip:${clientIp(req)}`;
if (authFailures(ipKey) >= LOGIN_IP_LIMIT) { if (authFailures(ipKey) >= LOGIN_IP_LIMIT) {
return error(res, 429, 'Too many sign-in attempts. Try again later.', { 'Retry-After': '900' }); return error(res, 429, 'Too many sign-in attempts. Try again later.', { 'Retry-After': '900' });
@@ -800,6 +848,9 @@ route('PATCH', '/api/admin/users/:id', async ({ req, res, params }) => {
if (!admin) return; if (!admin) return;
const target = users.byId(params.id); const target = users.byId(params.id);
if (!target) return error(res, 404, 'No such account'); if (!target) return error(res, 404, 'No such account');
if (LOCAL_MODE && localOwner && target.id === localOwner.id) {
return error(res, 403, 'The local account is managed by the desktop launcher');
}
const body = await readJson(req, 64 * 1024); const body = await readJson(req, 64 * 1024);
const patch = {}; const patch = {};
@@ -872,6 +923,9 @@ route('DELETE', '/api/admin/users/:id', async ({ req, res, params }) => {
if (params.id === admin.id) return error(res, 400, 'You cannot delete your own account'); if (params.id === admin.id) return error(res, 400, 'You cannot delete your own account');
const target = users.byId(params.id); const target = users.byId(params.id);
if (!target) return error(res, 404, 'No such account'); if (!target) return error(res, 404, 'No such account');
if (LOCAL_MODE && localOwner && target.id === localOwner.id) {
return error(res, 403, 'The local account is managed by the desktop launcher');
}
if (target.role === 'admin' && users.activeAdmins() <= 1) { if (target.role === 'admin' && users.activeAdmins() <= 1) {
return error(res, 400, 'Keep at least one active administrator'); return error(res, 400, 'Keep at least one active administrator');
} }
@@ -974,6 +1028,55 @@ route('PUT', '/api/admin/storage', async ({ req, res }) => {
let previewRebuild = null; let previewRebuild = null;
/** Progress file, so a restart resumes a run instead of starting it over. */
function previewRebuildFile() {
return path.join(storageRoot(), 'preview-rebuild.json');
}
function savePreviewRebuild(state) {
try {
fs.writeFileSync(previewRebuildFile(), JSON.stringify(state));
} catch {
/* Progress is a convenience; a read-only storage root must not stop a run. */
}
}
/**
* Runs the job and mirrors its progress to disk after every photo. The proxy
* rebuild takes hours on a full library, so losing it to a deploy means
* starting from the first photo again.
*/
function beginPreviewRebuild(targets) {
const job = startPreviewRebuild({
targets,
regenerate: (photo) => regenerateRawPreview(photo.id, photo, photoOwner(photo.id) ?? ''),
onProgress: (snapshot, pending) =>
savePreviewRebuild({ ...snapshot, pending: pending.map((photo) => photo.id) }),
});
savePreviewRebuild({ ...job.snapshot(), pending: targets.map((photo) => photo.id) });
void job.finished.then(() => savePreviewRebuild({ ...job.snapshot(), pending: [] }));
previewRebuild = job;
return job;
}
/** Restarts a run that a restart interrupted, skipping finished photos. */
function resumePreviewRebuild() {
let saved = null;
try {
saved = JSON.parse(fs.readFileSync(previewRebuildFile(), 'utf8'));
} catch {
return;
}
if (saved?.state !== 'running' || !Array.isArray(saved.pending) || saved.pending.length === 0) {
return;
}
const byId = new Map(listPhotos().map((photo) => [photo.id, photo]));
const targets = saved.pending.map((id) => byId.get(id)).filter(Boolean);
if (targets.length === 0) return;
console.log(` previews: resuming rebuild, ${targets.length} photo(s) left`);
beginPreviewRebuild(targets);
}
function previewRebuildStatus() { function previewRebuildStatus() {
return ( return (
previewRebuild?.snapshot() ?? { previewRebuild?.snapshot() ?? {
@@ -1005,11 +1108,8 @@ route('POST', '/api/admin/previews/rebuild', async ({ req, res }) => {
const current = previewRebuildStatus(); const current = previewRebuildStatus();
if (current.state === 'running') return json(res, 202, { rebuild: current }); if (current.state === 'running') return json(res, 202, { rebuild: current });
const targets = previewRebuildTargets(listPhotos()); const targets = previewRebuildTargets(listPhotos());
previewRebuild = startPreviewRebuild({ const rebuild = beginPreviewRebuild(targets);
targets, json(res, 202, { rebuild: rebuild.snapshot() });
regenerate: (photo) => regenerateRawPreview(photo.id, photo, photoOwner(photo.id) ?? ''),
});
json(res, 202, { rebuild: previewRebuild.snapshot() });
}); });
route('GET', '/api/quota', async ({ req, res }) => { route('GET', '/api/quota', async ({ req, res }) => {
@@ -1980,7 +2080,10 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
const drop = url.searchParams.get('drop') === '1'; const drop = url.searchParams.get('drop') === '1';
const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name); const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name);
const ext = (name.split('.').pop() || 'bin').toLowerCase(); const ext = (name.split('.').pop() || 'bin').toLowerCase();
const raw = isRawName(name) || drop; // TIFF is not a raw container, but browsers cannot decode it either. It takes
// the same upload path and is turned into a JPEG proxy here with sharp.
const still = isStillName(name);
const raw = isRawName(name) || drop || still;
// New ids are part of the normal import flow: the client uploads bytes first // New ids are part of the normal import flow: the client uploads bytes first
// and PUTs the record afterwards. Until that row exists the bytes are charged // and PUTs the record afterwards. Until that row exists the bytes are charged
@@ -2048,7 +2151,7 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
if (raw) { if (raw) {
try { try {
const data = await fsp.readFile(target); const data = await fsp.readFile(target);
const decoded = await decodeRaw(data); const decoded = still ? await decodeStill(data) : await decodeRaw(data);
await writePreview(params.id, decoded.jpeg, decoded.ext); await writePreview(params.id, decoded.jpeg, decoded.ext);
if (decoded.preview16) { if (decoded.preview16) {
await writePreview16(params.id, decoded.preview16.data); await writePreview16(params.id, decoded.preview16.data);
@@ -2061,11 +2164,13 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
} }
const info = await jpegInfo(decoded.jpeg); const info = await jpegInfo(decoded.jpeg);
return json(res, 201, { return json(res, 201, {
raw: true, raw: isRawName(name) || drop,
serverDecoded: still,
engine: decoded.engine, engine: decoded.engine,
width: info?.width || decoded.width, width: info?.width || decoded.width,
height: info?.height || decoded.height, height: info?.height || decoded.height,
mime: 'image/jpeg', mime: 'image/jpeg',
previewBytes: decoded.jpeg.length,
previewUrl: `/api/photos/${params.id}/preview`, previewUrl: `/api/photos/${params.id}/preview`,
thumbUrl: `/api/photos/${params.id}/thumb`, thumbUrl: `/api/photos/${params.id}/thumb`,
note: decoded.note ?? null, note: decoded.note ?? null,
@@ -2521,6 +2626,13 @@ async function sweepOrphanOriginals() {
} }
} }
await prepareLocalOwner();
if (LOCAL_MODE && !['127.0.0.1', 'localhost', '::1'].includes(HOST)) {
console.warn(
` local: LUMINARY_LOCAL=1 with HOST=${HOST}; every client is treated as the local admin`,
);
}
server.listen(PORT, HOST, async () => { server.listen(PORT, HOST, async () => {
startQuotaWorker(); startQuotaWorker();
const raw = await rawSupport(); const raw = await rawSupport();
@@ -2529,8 +2641,13 @@ server.listen(PORT, HOST, async () => {
console.log( console.log(
` raw: libraw ${raw.libraw ? `ready (${raw.workers} parallel worker${raw.workers === 1 ? '' : 's'})` : 'missing'} · jpeg ${raw.sharp ? 'sharp' : 'png fallback'}`, ` raw: libraw ${raw.libraw ? `ready (${raw.workers} parallel worker${raw.workers === 1 ? '' : 's'})` : 'missing'} · jpeg ${raw.sharp ? 'sharp' : 'png fallback'}`,
); );
console.log(` users: ${users.count()} account(s)${users.count() === 0 ? ' — first signup becomes admin' : ''}`); if (LOCAL_MODE) {
console.log(` local: ${LOCAL_EMAIL} — sign-in disabled (LUMINARY_LOCAL=1)`);
} else {
console.log(` users: ${users.count()} account(s)${users.count() === 0 ? ' — first signup becomes admin' : ''}`);
}
if (!raw.libraw) console.log(' note: install libraw-wasm for full raw demosaic (embedded previews still work)'); if (!raw.libraw) console.log(' note: install libraw-wasm for full raw demosaic (embedded previews still work)');
resumePreviewRebuild();
}); });
setInterval(() => { setInterval(() => {
+6 -4
View File
@@ -3,8 +3,9 @@
* *
* A decode is CPU bound and holds a LibRaw worker for seconds, so the work runs * A decode is CPU bound and holds a LibRaw worker for seconds, so the work runs
* one photo at a time behind a snapshot: a request that blocked for an hour * one photo at a time behind a snapshot: a request that blocked for an hour
* would time out, and decoding in parallel would starve the editor. Progress * would time out, and decoding in parallel would starve the editor. The job
* lives in memory only, so an interrupted rebuild simply starts again. * itself keeps progress in memory; `onProgress` lets the caller persist it so a
* restart can pick the run up where it stopped.
*/ */
/** Photos that have a proxy worth regenerating: camera raws that still exist. */ /** Photos that have a proxy worth regenerating: camera raws that still exist. */
@@ -18,7 +19,7 @@ export function previewRebuildTargets(photos) {
* A photo that fails is counted and recorded, and the run continues: one * A photo that fails is counted and recorded, and the run continues: one
* unreadable original must not strand the rest of the library. * unreadable original must not strand the rest of the library.
*/ */
export function startPreviewRebuild({ targets, regenerate, now = Date.now }) { export function startPreviewRebuild({ targets, regenerate, now = Date.now, onProgress }) {
const job = { const job = {
state: 'running', state: 'running',
total: targets.length, total: targets.length,
@@ -31,7 +32,7 @@ export function startPreviewRebuild({ targets, regenerate, now = Date.now }) {
}; };
const finished = (async () => { const finished = (async () => {
for (const photo of targets) { for (const [index, photo] of targets.entries()) {
try { try {
const result = await regenerate(photo); const result = await regenerate(photo);
if (result?.sidecar) job.sidecars += 1; if (result?.sidecar) job.sidecars += 1;
@@ -43,6 +44,7 @@ export function startPreviewRebuild({ targets, regenerate, now = Date.now }) {
} }
} }
job.done += 1; job.done += 1;
onProgress?.({ ...job, errors: [...job.errors] }, targets.slice(index + 1));
} }
job.state = 'done'; job.state = 'done';
job.finishedAt = now(); job.finishedAt = now();
+16
View File
@@ -63,6 +63,22 @@ describe('preview rebuild job', () => {
expect(job.snapshot().errors).toEqual([]); expect(job.snapshot().errors).toEqual([]);
}); });
it('reports progress and what is still pending after each photo', async () => {
const steps = [];
const job = startPreviewRebuild({
targets: [{ id: 'a' }, { id: 'b' }, { id: 'c' }],
regenerate: async () => ({ sidecar: false }),
onProgress: (snapshot, pending) =>
steps.push({ done: snapshot.done, pending: pending.map((photo) => photo.id) }),
});
await job.finished;
expect(steps).toEqual([
{ done: 1, pending: ['b', 'c'] },
{ done: 2, pending: ['c'] },
{ done: 3, pending: [] },
]);
});
it('finishes immediately when there is nothing to rebuild', async () => { it('finishes immediately when there is nothing to rebuild', async () => {
const job = startPreviewRebuild({ targets: [], regenerate: async () => ({ sidecar: false }) }); const job = startPreviewRebuild({ targets: [], regenerate: async () => ({ sidecar: false }) });
await job.finished; await job.finished;
+43 -6
View File
@@ -28,6 +28,26 @@ export function isRawName(name = '') {
return RAW_EXTENSIONS.has(ext); return RAW_EXTENSIONS.has(ext);
} }
/**
* Standard images that browsers cannot decode. TIFF takes the raw upload path
* (store the original, serve a JPEG proxy) but is decoded by sharp, not LibRaw.
*/
export const SERVER_IMAGE_EXTENSIONS = new Set(['tif', 'tiff']);
export function isStillName(name = '') {
const ext = name.split('.').pop()?.toLowerCase() ?? '';
return SERVER_IMAGE_EXTENSIONS.has(ext);
}
/** Rejects instead of waiting forever when a decoder wedges on one file. */
function withTimeout(promise, ms, message) {
let timer;
const guard = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(message)), ms);
});
return Promise.race([promise, guard]).finally(() => clearTimeout(timer));
}
/** True when the buffer starts with a container signature LibRaw can open. */ /** True when the buffer starts with a container signature LibRaw can open. */
export function looksLikeRaw(buffer) { export function looksLikeRaw(buffer) {
if (!buffer || buffer.length < 64) return false; if (!buffer || buffer.length < 64) return false;
@@ -45,6 +65,19 @@ export function looksLikeRaw(buffer) {
let engineState = 'unloaded'; let engineState = 'unloaded';
export async function decodeStill(buffer) {
const proxy = await toJpegProxy(buffer, RAW_PREVIEW_EDGE);
if (!proxy) throw new Error('Could not decode this image');
const size = await jpegInfo(proxy.data);
return {
jpeg: proxy.data,
width: size?.width || proxy.width,
height: size?.height || proxy.height,
engine: 'sharp',
ext: proxy.ext,
};
}
export async function rawEngine() { export async function rawEngine() {
if (engineState === 'unloaded') { if (engineState === 'unloaded') {
try { try {
@@ -187,10 +220,14 @@ export function extractEmbeddedJpeg(buffer) {
async function embeddedPreview(buffer) { async function embeddedPreview(buffer) {
if ((await rawEngine()) === 'ready') { if ((await rawEngine()) === 'ready') {
try { try {
const thumb = await rawPool.use(async (lib) => { const thumb = await withTimeout(
await lib.open(Buffer.from(buffer), { useCameraWb: true }); rawPool.use(async (lib) => {
return lib.thumbnailData(); await lib.open(Buffer.from(buffer), { useCameraWb: true });
}); return lib.thumbnailData();
}),
12000,
'LibRaw preview timed out',
);
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) { if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
return Buffer.from(thumb.data); return Buffer.from(thumb.data);
} }
@@ -209,10 +246,10 @@ export async function decodeRaw(buffer) {
let librawError = null; let librawError = null;
if (looksLikeRaw(buffer)) { if (looksLikeRaw(buffer)) {
try { try {
let frame = await demosaic(buffer, true); let frame = await withTimeout(demosaic(buffer, true), 45000, 'LibRaw timed out on this file');
// No usable matrix (an odd body or older engine): decode the familiar sRGB // No usable matrix (an odd body or older engine): decode the familiar sRGB
// way instead of shipping camera samples nobody can convert. // way instead of shipping camera samples nobody can convert.
if (!frame.rgbCam || !frame.rgb16) frame = await demosaic(buffer, false); if (!frame.rgbCam || !frame.rgb16) frame = await withTimeout(demosaic(buffer, false), 45000, 'LibRaw timed out on this file');
const { width, height, rgbCam } = frame; const { width, height, rgbCam } = frame;
// Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and // Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and
// `rgb16` the camera-native sidecar, sharing one white point. // `rgb16` the camera-native sidecar, sharing one white point.
+108
View File
@@ -0,0 +1,108 @@
import { readFileSync, existsSync } from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import {
RAW_EXTENSIONS,
decodeRaw,
decodeStill,
isRawName,
isStillName,
looksLikeRaw,
rawEngine,
} from './raw.mjs';
/** TIFF-family containers: CR2, NEF and DNG all start with the same header. */
function tiffHeader() {
const buffer = Buffer.alloc(64);
Buffer.from('49492a00', 'hex').copy(buffer, 0);
return buffer;
}
function withAscii(bytes) {
const buffer = Buffer.alloc(64);
buffer.write(bytes, 0, 'latin1');
return buffer;
}
describe('raw format coverage', () => {
it.each(['cr2', 'nef', 'cr3', 'dng'])('routes .%s to the raw decoder', (ext) => {
expect(RAW_EXTENSIONS.has(ext)).toBe(true);
expect(isRawName(`IMG_0001.${ext}`)).toBe(true);
expect(isRawName(`IMG_0001.${ext.toUpperCase()}`)).toBe(true);
expect(isStillName(`IMG_0001.${ext}`)).toBe(false);
});
it.each(['tif', 'tiff'])('routes .%s to the still decoder', (ext) => {
expect(isStillName(`scan.${ext}`)).toBe(true);
expect(isStillName(`scan.${ext.toUpperCase()}`)).toBe(true);
expect(isRawName(`scan.${ext}`)).toBe(false);
});
it('recognises the container signatures of the main families', () => {
expect(looksLikeRaw(tiffHeader())).toBe(true); // CR2, NEF, DNG
const cr3 = Buffer.alloc(64);
cr3.write('ftyp', 4, 'latin1');
expect(looksLikeRaw(cr3)).toBe(true);
expect(looksLikeRaw(withAscii('IIRO'))).toBe(true); // ORF
expect(looksLikeRaw(withAscii('IIU\0'))).toBe(true); // RW2
expect(looksLikeRaw(withAscii('FUJIFILMCCD-RAW'))).toBe(true); // RAF
expect(looksLikeRaw(withAscii('FOVb'))).toBe(true); // X3F
expect(looksLikeRaw(Buffer.alloc(64))).toBe(false);
expect(looksLikeRaw(Buffer.alloc(8))).toBe(false);
});
});
describe('TIFF decoding', () => {
it('turns a TIFF into a JPEG proxy', async () => {
const { default: sharp } = await import('sharp');
const tiff = await sharp({
create: {
width: 48,
height: 32,
channels: 3,
background: { r: 20, g: 120, b: 210 },
},
})
.tiff()
.toBuffer();
const decoded = await decodeStill(tiff);
expect(decoded.engine).toBe('sharp');
expect(decoded.ext).toBe('jpg');
expect(decoded.width).toBe(48);
expect(decoded.height).toBe(32);
expect(decoded.jpeg.subarray(0, 2)).toEqual(Buffer.from([0xff, 0xd8]));
});
it('rejects a file that is not an image', async () => {
await expect(decodeStill(Buffer.from('not a tiff at all'))).rejects.toThrow(
/could not decode/i,
);
});
});
/**
* Real containers are optional: point LUMINARY_RAW_FIXTURES at a directory
* holding sample.cr2, sample.nef, sample.cr3 and sample.dng. The samples are
* deliberately not committed (they are 10-40 MB each and camera-specific), but
* when they are present this exercises the same libraw path an import takes.
*/
const FIXTURES = process.env.LUMINARY_RAW_FIXTURES;
const fixture = (ext) => (FIXTURES ? path.join(FIXTURES, `sample.${ext}`) : '');
const available = (ext) => Boolean(FIXTURES) && existsSync(fixture(ext));
const rawFormats = ['cr2', 'nef', 'cr3', 'dng'];
describe.skipIf(!FIXTURES)('real raw containers', () => {
it('has libraw available', async () => {
expect(await rawEngine()).toBe('ready');
});
for (const ext of rawFormats) {
it.skipIf(!available(ext))(`decodes sample.${ext}`, async () => {
const decoded = await decodeRaw(readFileSync(fixture(ext)));
expect(decoded.jpeg.length).toBeGreaterThan(4096);
expect(['libraw', 'embedded']).toContain(decoded.engine);
expect(decoded.width).toBeGreaterThan(0);
expect(decoded.height).toBeGreaterThan(0);
}, 120000);
}
});
+14 -3
View File
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import AboutModal from './components/AboutModal';
import AdminPanel from './components/AdminPanel'; import AdminPanel from './components/AdminPanel';
import CloudPanel from './components/CloudPanel'; import CloudPanel from './components/CloudPanel';
import CommandPalette from './components/CommandPalette'; import CommandPalette from './components/CommandPalette';
@@ -138,6 +139,7 @@ export default function App() {
const [undoAction, setUndoAction] = useState<{ message: string; run: () => void } | null>(null); const [undoAction, setUndoAction] = useState<{ message: string; run: () => void } | null>(null);
const [menu, setMenu] = useState<{ x: number; y: number; ids: string[] } | null>(null); const [menu, setMenu] = useState<{ x: number; y: number; ids: string[] } | null>(null);
const [helpOpen, setHelpOpen] = useState(false); const [helpOpen, setHelpOpen] = useState(false);
const [aboutOpen, setAboutOpen] = useState(false);
const [searchOpen, setSearchOpen] = useState(false); const [searchOpen, setSearchOpen] = useState(false);
const [shareEventId, setShareEventId] = useState<string | null>(null); const [shareEventId, setShareEventId] = useState<string | null>(null);
/** Client proofing picks, keyed to the photos they chose. */ /** Client proofing picks, keyed to the photos they chose. */
@@ -1898,6 +1900,7 @@ export default function App() {
mod && mod &&
k === 'k' && k === 'k' &&
!helpOpen && !helpOpen &&
!aboutOpen &&
!importOpen && !importOpen &&
!exportOpen && !exportOpen &&
!cloudOpen && !cloudOpen &&
@@ -1916,7 +1919,7 @@ export default function App() {
setHelpOpen((v) => !v); setHelpOpen((v) => !v);
return; return;
} }
if (helpOpen || importOpen || exportOpen || cloudOpen || adminOpen || compareOpen) return; if (helpOpen || aboutOpen || importOpen || exportOpen || cloudOpen || adminOpen || compareOpen) return;
if (mod && k === 'i') { if (mod && k === 'i') {
e.preventDefault(); e.preventDefault();
@@ -2221,6 +2224,11 @@ export default function App() {
); );
} }
// The Windows desktop bundle runs as one local admin (LUMINARY_LOCAL=1).
// Accounts and team administration have nothing to manage there, so both
// panels and the entry point to them stay out of the UI.
const localMode = cloudHealth?.local === true;
return ( return (
<div className="app"> <div className="app">
<TopBar <TopBar
@@ -2230,6 +2238,7 @@ export default function App() {
selectedCount={selected.length} selectedCount={selected.length}
cloudLabel={cloudUser ? cloudUser.name || cloudUser.email : cloudHealth ? 'Sign in' : 'Local only'} cloudLabel={cloudUser ? cloudUser.name || cloudUser.email : cloudHealth ? 'Sign in' : 'Local only'}
cloudOn={!!cloudUser} cloudOn={!!cloudUser}
localMode={localMode}
onViewChange={(v) => { onViewChange={(v) => {
setCatalogOpen(false); setCatalogOpen(false);
if (v === 'develop' && !activePhoto) { if (v === 'develop' && !activePhoto) {
@@ -2248,6 +2257,7 @@ export default function App() {
setCloudOpen(true); setCloudOpen(true);
}} }}
onHelp={() => setHelpOpen(true)} onHelp={() => setHelpOpen(true)}
onAbout={() => setAboutOpen(true)}
onSearch={() => setSearchOpen(true)} onSearch={() => setSearchOpen(true)}
onCatalog={() => { onCatalog={() => {
setView('grid'); setView('grid');
@@ -2605,6 +2615,7 @@ export default function App() {
)} )}
{helpOpen && <Shortcuts onClose={() => setHelpOpen(false)} />} {helpOpen && <Shortcuts onClose={() => setHelpOpen(false)} />}
{aboutOpen && <AboutModal onClose={() => setAboutOpen(false)} />}
{searchOpen && ( {searchOpen && (
<CommandPalette <CommandPalette
@@ -2646,7 +2657,7 @@ export default function App() {
</div> </div>
)} )}
{cloudOpen && ( {cloudOpen && !localMode && (
<CloudPanel <CloudPanel
health={cloudHealth} health={cloudHealth}
user={cloudUser} user={cloudUser}
@@ -2669,7 +2680,7 @@ export default function App() {
/> />
)} )}
{adminOpen && cloudUser && ( {adminOpen && cloudUser && !localMode && (
<AdminPanel <AdminPanel
user={cloudUser} user={cloudUser}
onClose={() => setAdminOpen(false)} onClose={() => setAdminOpen(false)}
+68
View File
@@ -0,0 +1,68 @@
import { useEffect } from 'react';
import { APP_VERSION, GUIDE_UPDATED, GUIDE_VERSION } from '../lib/about';
interface Props {
onClose: () => void;
}
export default function AboutModal({ onClose }: Props) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [onClose]);
return (
<div
className="modal-backdrop"
onPointerDown={(e) => e.target === e.currentTarget && onClose()}
>
<div className="modal about-modal" role="dialog" aria-label="About Luminary">
<header className="modal-head">
<h2>About Luminary</h2>
<button className="icon-btn" onClick={onClose} aria-label="Close">
✕
</button>
</header>
<div className="modal-body">
<div className="about-brand">
<img src="/logo.png" alt="" height={28} />
<div>
<strong>Luminary</strong>
<div className="muted small">Version {APP_VERSION} · Beta</div>
</div>
</div>
<dl className="cloud-stats about-facts">
<div>
<dt>User guide</dt>
<dd>Version {GUIDE_VERSION}</dd>
</div>
<div>
<dt>Guide updated</dt>
<dd>{GUIDE_UPDATED}</dd>
</div>
</dl>
<p className="muted small">
The guide covers every screen, panel and setting, with server, Docker and
Windows install instructions. Its screenshots are taken from a live catalog.
</p>
<div className="btn-row">
<a
className="btn primary"
href="/luminary-user-guide.pdf"
target="_blank"
rel="noreferrer"
>
Open user guide (PDF)
</a>
<button className="btn ghost" onClick={onClose}>
Close
</button>
</div>
</div>
</div>
</div>
);
}
+368 -103
View File
@@ -2,8 +2,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { import {
ASPECTS, ASPECTS,
defaultEdits, defaultEdits,
defaultLocalComponent,
defaultLocalLayer, defaultLocalLayer,
MAX_HEAL_SPOTS, MAX_HEAL_SPOTS,
MAX_LOCAL_COMPONENTS,
MAX_LOCAL_LAYERS, MAX_LOCAL_LAYERS,
} from '../lib/edits'; } from '../lib/edits';
import { subscribeClipPreview } from '../lib/clipPreview'; import { subscribeClipPreview } from '../lib/clipPreview';
@@ -35,6 +37,7 @@ import type {
EventRecord, EventRecord,
Flag, Flag,
HealSpot, HealSpot,
LocalComponent,
LocalLayer, LocalLayer,
LocalMaskKind, LocalMaskKind,
LocalStroke, LocalStroke,
@@ -105,16 +108,21 @@ const EMPTY_GEO: Geometry = {
function cloneLocalLayer(layer: LocalLayer): LocalLayer { function cloneLocalLayer(layer: LocalLayer): LocalLayer {
return { return {
...layer, ...layer,
brush: { components: layer.components.map((component) => ({
strokes: layer.brush.strokes.map((stroke) => ({ ...component,
...stroke, brush: {
points: stroke.points.map((point) => ({ ...point })), strokes: component.brush.strokes.map((stroke) => ({
})), ...stroke,
}, points: stroke.points.map((point) => ({ ...point })),
linear: { ...layer.linear }, })),
radial: { ...layer.radial }, },
linear: { ...component.linear },
radial: { ...component.radial },
...(component.raster ? { raster: { ...component.raster } } : {}),
})),
adjust: { ...layer.adjust }, adjust: { ...layer.adjust },
range: { ...layer.range }, range: { ...layer.range },
curve: layer.curve.map((point) => ({ ...point })),
}; };
} }
@@ -253,11 +261,18 @@ export default function Develop({
const healDrag = useRef<{ index: number; mode: 'target' | 'source'; spot: HealSpot } | null>(null); const healDrag = useRef<{ index: number; mode: 'target' | 'source'; spot: HealSpot } | null>(null);
const [localSelected, setLocalSelected] = useState<string | null>(null); const [localSelected, setLocalSelected] = useState<string | null>(null);
const [localComponentSelected, setLocalComponentSelected] = useState<string | null>(null);
const [localMode, setLocalMode] = useState(false); const [localMode, setLocalMode] = useState(false);
const [autoMaskBusy, setAutoMaskBusy] = useState(false); const [autoMaskBusy, setAutoMaskBusy] = useState(false);
const [localBrush, setLocalBrush] = useState(72); const [localBrush, setLocalBrush] = useState(72);
const [localHover, setLocalHover] = useState<{ x: number; y: number } | null>(null); const [localHover, setLocalHover] = useState<{ x: number; y: number } | null>(null);
const [localDraft, setLocalDraft] = useState<LocalStroke | null>(null); const [localDraft, setLocalDraft] = useState<LocalStroke | null>(null);
// The mask tint is a view aid, not an edit: it has its own toggle (O) and
// strength, and both are display preferences rather than catalog data.
const [maskOverlay, setMaskOverlay] = usePersistentState('develop.maskOverlay', true);
const [maskStrength, setMaskStrength] = usePersistentState('develop.maskStrength', 50);
// How the next mask gesture combines with the group: paint or erase.
const [localErase, setLocalErase] = useState(false);
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null); const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
const [lensSplit, setLensSplit] = useState(false); const [lensSplit, setLensSplit] = useState(false);
const [lensSplitAt, setLensSplitAt] = useState(0.5); const [lensSplitAt, setLensSplitAt] = useState(0.5);
@@ -266,7 +281,8 @@ export default function Develop({
error: null, error: null,
}); });
const localDrag = useRef<{ const localDrag = useRef<{
id: string; layerId: string;
componentId: string;
mode: 'brush' | 'center' | 'edge' | 'edgeX' | 'edgeY' | 'start' | 'end'; mode: 'brush' | 'center' | 'edge' | 'edgeX' | 'edgeY' | 'start' | 'end';
stroke: LocalStroke | null; stroke: LocalStroke | null;
} | null>(null); } | null>(null);
@@ -280,6 +296,10 @@ export default function Develop({
[photos, photo.meta?.camera], [photos, photo.meta?.camera],
); );
const activeLocal = (edits.local ?? []).find((layer) => layer.id === localSelected) ?? null; const activeLocal = (edits.local ?? []).find((layer) => layer.id === localSelected) ?? null;
const activeComponent =
activeLocal?.components.find((component) => component.id === localComponentSelected) ??
activeLocal?.components[0] ??
null;
const zoomed = zoom.pct !== 'fit'; const zoomed = zoom.pct !== 'fit';
// The filmstrip has its own Lightroom-style cull filter so you can narrow the // The filmstrip has its own Lightroom-style cull filter so you can narrow the
@@ -583,6 +603,15 @@ export default function Develop({
: view, : view,
); );
// The mask overlay is the baked mask itself, and it is a view toggle: off
// while holding \\ (before/after), while the mask tool is closed, or when
// the user hides it. The histogram ignores it: a tinted chart is not a
// measurement of the photo.
const maskView =
showOriginal || !localMode || !maskOverlay
? -1
: (edits.local ?? []).findIndex((layer) => layer.id === localSelected);
try { try {
renderer.setImage(bitmap, hdrSource); renderer.setImage(bitmap, hdrSource);
// "Show original" must show the untouched source, not the cleaned proxy. // "Show original" must show the untouched source, not the cleaned proxy.
@@ -592,7 +621,7 @@ export default function Develop({
height: pxH, height: pxH,
cropPreview: cropMode, cropPreview: cropMode,
// The histogram describes the whole photo, so it is only refreshed at fit. // The histogram describes the whole photo, so it is only refreshed at fit.
histogram: !cropMode && !showOriginal && zoomFactor <= 1.0001, histogram: !cropMode && !showOriginal && zoomFactor <= 1.0001 && maskView < 0,
view: zoomFactor <= 1.0001 ? undefined : view, view: zoomFactor <= 1.0001 ? undefined : view,
// Holding the grain still keeps the noise from crawling while a crop // Holding the grain still keeps the noise from crawling while a crop
// handle moves; the new crop-relative scale applies on release. // handle moves; the new crop-relative scale applies on release.
@@ -604,6 +633,8 @@ export default function Develop({
clipping: clipping ?? undefined, clipping: clipping ?? undefined,
lens: showOriginal ? null : lensCorrection, lens: showOriginal ? null : lensCorrection,
lensSplit: lensSplit && !showOriginal ? lensSplitAt : undefined, lensSplit: lensSplit && !showOriginal ? lensSplitAt : undefined,
maskView,
maskStrength: maskStrength / 100,
}); });
histRef.current = renderer.histogram; histRef.current = renderer.histogram;
setHistVersion((v) => v + 1); setHistVersion((v) => v + 1);
@@ -625,6 +656,10 @@ export default function Develop({
lensCorrection, lensCorrection,
lensSplit, lensSplit,
lensSplitAt, lensSplitAt,
localMode,
localSelected,
maskOverlay,
maskStrength,
// Loading or clearing a printer profile changes the finish pass, and the // Loading or clearing a printer profile changes the finish pass, and the
// cube lives outside the edit record, so the redraw is keyed on it here. // cube lives outside the edit record, so the redraw is keyed on it here.
proofProfile, proofProfile,
@@ -740,7 +775,7 @@ export default function Develop({
if ((e.target as HTMLElement | null)?.closest('.loupe-adjust')) return; if ((e.target as HTMLElement | null)?.closest('.loupe-adjust')) return;
if (cropMode) return; if (cropMode) return;
// While painting a mask, the wheel sizes the brush instead of zooming. // While painting a mask, the wheel sizes the brush instead of zooming.
if (localMode && activeLocal?.kind === 'brush') { if (localMode && activeComponent?.kind === 'brush') {
e.preventDefault(); e.preventDefault();
setLocalBrush((v) => clampNum(v * Math.exp(-e.deltaY * 0.0015), 8, 320)); setLocalBrush((v) => clampNum(v * Math.exp(-e.deltaY * 0.0015), 8, 320));
return; return;
@@ -760,7 +795,7 @@ export default function Develop({
}; };
el.addEventListener('wheel', onWheel, { passive: false }); el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel); return () => el.removeEventListener('wheel', onWheel);
}, [cropMode, applyZoom, healMode, localMode, activeLocal]); }, [cropMode, applyZoom, healMode, localMode, activeComponent]);
const beginPan = (e: React.PointerEvent<HTMLCanvasElement>) => { const beginPan = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (picking || rangePicking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return; if (picking || rangePicking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return;
@@ -1013,6 +1048,26 @@ export default function Develop({
[commitLocal, photo.edits.local], [commitLocal, photo.edits.local],
); );
/** Updates one shape inside a layer's mask group. */
const patchComponent = useCallback(
(layerId: string, componentId: string, patch: Partial<LocalComponent>, label = 'Local adjustment') => {
commitLocal(
(photo.edits.local ?? []).map((layer) =>
layer.id === layerId
? {
...layer,
components: layer.components.map((component) =>
component.id === componentId ? { ...component, ...patch } : component,
),
}
: layer,
),
label,
);
},
[commitLocal, photo.edits.local],
);
const addLocalLayer = useCallback( const addLocalLayer = useCallback(
(kind: LocalMaskKind) => { (kind: LocalMaskKind) => {
const layers = edits.local ?? []; const layers = edits.local ?? [];
@@ -1020,6 +1075,7 @@ export default function Develop({
const layer = defaultLocalLayer(kind, layers.length); const layer = defaultLocalLayer(kind, layers.length);
commitLocal([...layers, layer], 'Add local adjustment'); commitLocal([...layers, layer], 'Add local adjustment');
setLocalSelected(layer.id); setLocalSelected(layer.id);
setLocalComponentSelected(layer.components[0]?.id ?? null);
setLocalMode(true); setLocalMode(true);
setCropMode(false); setCropMode(false);
setHealMode(false); setHealMode(false);
@@ -1037,10 +1093,14 @@ export default function Develop({
const raster = await buildAutoMask(source, kind); const raster = await buildAutoMask(source, kind);
const layer = defaultLocalLayer('raster', layers.length); const layer = defaultLocalLayer('raster', layers.length);
layer.name = `Auto ${kind}`; layer.name = `Auto ${kind}`;
layer.raster = raster; const shape = layer.components[0];
layer.feather = 30; if (shape) {
shape.raster = raster;
shape.feather = 30;
}
commitLocal([...layers, layer], `Auto ${kind} mask`); commitLocal([...layers, layer], `Auto ${kind} mask`);
setLocalSelected(layer.id); setLocalSelected(layer.id);
setLocalComponentSelected(layer.components[0]?.id ?? null);
setLocalMode(false); setLocalMode(false);
setCropMode(false); setCropMode(false);
setHealMode(false); setHealMode(false);
@@ -1109,6 +1169,7 @@ export default function Develop({
(id: string) => { (id: string) => {
commitLocal((edits.local ?? []).filter((layer) => layer.id !== id), 'Delete local adjustment'); commitLocal((edits.local ?? []).filter((layer) => layer.id !== id), 'Delete local adjustment');
setLocalSelected(null); setLocalSelected(null);
setLocalComponentSelected(null);
setLocalMode(false); setLocalMode(false);
}, },
[commitLocal, edits.local], [commitLocal, edits.local],
@@ -1127,6 +1188,7 @@ export default function Develop({
}; };
commitLocal([...layers, copy], 'Duplicate local adjustment'); commitLocal([...layers, copy], 'Duplicate local adjustment');
setLocalSelected(copy.id); setLocalSelected(copy.id);
setLocalComponentSelected(copy.components[0]?.id ?? null);
}, },
[commitLocal, edits.local], [commitLocal, edits.local],
); );
@@ -1146,11 +1208,39 @@ export default function Develop({
}; };
commitLocal([...layers, copy], 'Paste local adjustment'); commitLocal([...layers, copy], 'Paste local adjustment');
setLocalSelected(copy.id); setLocalSelected(copy.id);
setLocalComponentSelected(copy.components[0]?.id ?? null);
setLocalMode(true); setLocalMode(true);
setCropMode(false); setCropMode(false);
setHealMode(false); setHealMode(false);
}, [commitLocal, edits.local, localClipboard]); }, [commitLocal, edits.local, localClipboard]);
const addLocalComponent = useCallback(
(kind: LocalMaskKind) => {
if (!activeLocal) return;
if (activeLocal.components.length >= MAX_LOCAL_COMPONENTS) return;
const component = defaultLocalComponent(kind);
patchLocal(activeLocal.id, { components: [...activeLocal.components, component] }, 'Add mask shape');
setLocalComponentSelected(component.id);
setLocalMode(true);
setCropMode(false);
setHealMode(false);
setPicking(false);
},
[activeLocal, patchLocal],
);
const deleteLocalComponent = useCallback(
(componentId: string) => {
// A layer is its group: removing the last shape would leave an adjustment
// with no mask, so Delete layer is the way to remove it.
if (!activeLocal || activeLocal.components.length <= 1) return;
const remaining = activeLocal.components.filter((component) => component.id !== componentId);
patchLocal(activeLocal.id, { components: remaining }, 'Delete mask shape');
setLocalComponentSelected(remaining[0]?.id ?? null);
},
[activeLocal, patchLocal],
);
const toggleLocalMode = useCallback(() => { const toggleLocalMode = useCallback(() => {
if (!activeLocal) return; if (!activeLocal) return;
setLocalMode((v) => !v); setLocalMode((v) => !v);
@@ -1160,21 +1250,25 @@ export default function Develop({
}, [activeLocal]); }, [activeLocal]);
const startLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => { const startLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!localMode || !activeLocal || !bitmap) return; if (!localMode || !activeLocal || !activeComponent || !bitmap) return;
const p = sourcePointFromEvent(e); const p = sourcePointFromEvent(e);
if (!p) return; if (!p) return;
e.preventDefault(); e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId); e.currentTarget.setPointerCapture(e.pointerId);
if (activeLocal.kind === 'brush') { if (activeComponent.kind === 'brush') {
const stroke: LocalStroke = { points: [p], size: localRadius(), erase: e.altKey }; const stroke: LocalStroke = {
localDrag.current = { id: activeLocal.id, mode: 'brush', stroke }; points: [p],
size: localRadius(),
erase: e.altKey || localErase,
};
localDrag.current = { layerId: activeLocal.id, componentId: activeComponent.id, mode: 'brush', stroke };
setLocalDraft(stroke); setLocalDraft(stroke);
return; return;
} }
if (activeLocal.kind === 'radial') { if (activeComponent.kind === 'radial') {
const aspect = bitmap.height / bitmap.width; const aspect = bitmap.height / bitmap.width;
const nx = (p.x - activeLocal.radial.cx) / Math.max(0.001, activeLocal.radial.rx); const nx = (p.x - activeComponent.radial.cx) / Math.max(0.001, activeComponent.radial.rx);
const ny = ((p.y - activeLocal.radial.cy) * aspect) / Math.max(0.001, activeLocal.radial.ry); const ny = ((p.y - activeComponent.radial.cy) * aspect) / Math.max(0.001, activeComponent.radial.ry);
const mode = const mode =
Math.abs(nx) > 0.82 && Math.abs(ny) < 0.65 Math.abs(nx) > 0.82 && Math.abs(ny) < 0.65
? 'edgeX' ? 'edgeX'
@@ -1183,12 +1277,23 @@ export default function Develop({
: Math.hypot(nx, ny) > 0.82 : Math.hypot(nx, ny) > 0.82
? 'edge' ? 'edge'
: 'center'; : 'center';
localDrag.current = { id: activeLocal.id, mode, stroke: null }; localDrag.current = { layerId: activeLocal.id, componentId: activeComponent.id, mode, stroke: null };
return; return;
} }
const ds = Math.hypot(p.x - activeLocal.linear.x1, (p.y - activeLocal.linear.y1) * (bitmap.height / bitmap.width)); const ds = Math.hypot(
const de = Math.hypot(p.x - activeLocal.linear.x2, (p.y - activeLocal.linear.y2) * (bitmap.height / bitmap.width)); p.x - activeComponent.linear.x1,
localDrag.current = { id: activeLocal.id, mode: ds <= de ? 'start' : 'end', stroke: null }; (p.y - activeComponent.linear.y1) * (bitmap.height / bitmap.width),
);
const de = Math.hypot(
p.x - activeComponent.linear.x2,
(p.y - activeComponent.linear.y2) * (bitmap.height / bitmap.width),
);
localDrag.current = {
layerId: activeLocal.id,
componentId: activeComponent.id,
mode: ds <= de ? 'start' : 'end',
stroke: null,
};
}; };
const moveLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => { const moveLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
@@ -1198,8 +1303,9 @@ export default function Develop({
setLocalHover(p); setLocalHover(p);
const drag = localDrag.current; const drag = localDrag.current;
if (!drag) return; if (!drag) return;
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.id); const layer = (photo.edits.local ?? []).find((item) => item.id === drag.layerId);
if (!layer) return; const shape = layer?.components.find((item) => item.id === drag.componentId);
if (!layer || !shape) return;
if (drag.mode === 'brush' && drag.stroke) { if (drag.mode === 'brush' && drag.stroke) {
const last = drag.stroke.points[drag.stroke.points.length - 1]; const last = drag.stroke.points[drag.stroke.points.length - 1];
if (last && Math.hypot((p.x - last.x) * bitmap.width, (p.y - last.y) * bitmap.height) < 1.2) return; if (last && Math.hypot((p.x - last.x) * bitmap.width, (p.y - last.y) * bitmap.height) < 1.2) return;
@@ -1209,46 +1315,51 @@ export default function Develop({
return; return;
} }
if (drag.mode === 'center') { if (drag.mode === 'center') {
patchLocal(layer.id, { radial: { ...layer.radial, cx: p.x, cy: p.y } }, 'Move local mask'); patchComponent(layer.id, shape.id, { radial: { ...shape.radial, cx: p.x, cy: p.y } }, 'Move local mask');
} else if (drag.mode === 'edgeX') { } else if (drag.mode === 'edgeX') {
patchLocal( patchComponent(
layer.id, layer.id,
{ radial: { ...layer.radial, rx: clampNum(Math.abs(p.x - layer.radial.cx), 0.01, 1.5) } }, shape.id,
{ radial: { ...shape.radial, rx: clampNum(Math.abs(p.x - shape.radial.cx), 0.01, 1.5) } },
'Resize local mask', 'Resize local mask',
); );
} else if (drag.mode === 'edgeY') { } else if (drag.mode === 'edgeY') {
patchLocal( patchComponent(
layer.id, layer.id,
{ radial: { ...layer.radial, ry: clampNum(Math.abs(p.y - layer.radial.cy), 0.01, 1.5) } }, shape.id,
{ radial: { ...shape.radial, ry: clampNum(Math.abs(p.y - shape.radial.cy), 0.01, 1.5) } },
'Resize local mask', 'Resize local mask',
); );
} else if (drag.mode === 'edge') { } else if (drag.mode === 'edge') {
patchLocal( patchComponent(
layer.id, layer.id,
shape.id,
{ {
radial: { radial: {
...layer.radial, ...shape.radial,
rx: clampNum(Math.abs(p.x - layer.radial.cx), 0.01, 1.5), rx: clampNum(Math.abs(p.x - shape.radial.cx), 0.01, 1.5),
ry: clampNum(Math.abs(p.y - layer.radial.cy), 0.01, 1.5), ry: clampNum(Math.abs(p.y - shape.radial.cy), 0.01, 1.5),
}, },
}, },
'Resize local mask', 'Resize local mask',
); );
} else if (drag.mode === 'start') { } else if (drag.mode === 'start') {
patchLocal(layer.id, { linear: { ...layer.linear, x1: p.x, y1: p.y } }, 'Move local gradient'); patchComponent(layer.id, shape.id, { linear: { ...shape.linear, x1: p.x, y1: p.y } }, 'Move local gradient');
} else if (drag.mode === 'end') { } else if (drag.mode === 'end') {
patchLocal(layer.id, { linear: { ...layer.linear, x2: p.x, y2: p.y } }, 'Move local gradient'); patchComponent(layer.id, shape.id, { linear: { ...shape.linear, x2: p.x, y2: p.y } }, 'Move local gradient');
} }
}; };
const endLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => { const endLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
const drag = localDrag.current; const drag = localDrag.current;
if (drag?.mode === 'brush' && drag.stroke?.points.length) { if (drag?.mode === 'brush' && drag.stroke?.points.length) {
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.id); const layer = (photo.edits.local ?? []).find((item) => item.id === drag.layerId);
if (layer) { const shape = layer?.components.find((item) => item.id === drag.componentId);
patchLocal( if (layer && shape) {
patchComponent(
layer.id, layer.id,
{ brush: { strokes: [...layer.brush.strokes, drag.stroke].slice(-300) } }, shape.id,
{ brush: { strokes: [...shape.brush.strokes, drag.stroke].slice(-300) } },
drag.stroke.erase ? 'Erase local mask' : 'Paint local mask', drag.stroke.erase ? 'Erase local mask' : 'Paint local mask',
); );
} }
@@ -1281,18 +1392,35 @@ export default function Develop({
useEffect(() => { useEffect(() => {
setLocalSelected(null); setLocalSelected(null);
setLocalComponentSelected(null);
setLocalMode(false); setLocalMode(false);
setLocalDraft(null); setLocalDraft(null);
setLocalErase(false);
localDrag.current = null; localDrag.current = null;
}, [photo.id]); }, [photo.id]);
// Leaving the mask tool drops the erase mode, so the next visit starts by
// painting rather than cutting holes into the mask.
useEffect(() => {
if (!localMode) setLocalErase(false);
}, [localMode]);
useEffect(() => { useEffect(() => {
if (!(edits.local ?? []).some((layer) => layer.id === localSelected)) { if (!(edits.local ?? []).some((layer) => layer.id === localSelected)) {
setLocalSelected(null); setLocalSelected(null);
setLocalComponentSelected(null);
setLocalMode(false); setLocalMode(false);
} }
}, [edits.local, localSelected]); }, [edits.local, localSelected]);
// Keep a shape selected, so Edit mask always has something to route the
// pointer to after a layer switch or a shape delete.
useEffect(() => {
if (!activeLocal) return;
if (activeLocal.components.some((component) => component.id === localComponentSelected)) return;
setLocalComponentSelected(activeLocal.components[0]?.id ?? null);
}, [activeLocal, localComponentSelected]);
// Escape cancels the picker without touching the edit. // Escape cancels the picker without touching the edit.
useEffect(() => { useEffect(() => {
if (!picking) return; if (!picking) return;
@@ -1422,6 +1550,13 @@ export default function Develop({
toggleLocalMode(); toggleLocalMode();
e.preventDefault(); e.preventDefault();
} }
} else if (e.key.toLowerCase() === 'o' && !e.metaKey && !e.ctrlKey && !e.altKey) {
// The mask tint is a view, so it can be hidden while painting or
// checking the photo underneath without leaving the mask tool.
if (localMode) {
setMaskOverlay((v) => !v);
e.preventDefault();
}
} else if (e.key === 'Enter' && cropMode) { } else if (e.key === 'Enter' && cropMode) {
setCropMode(false); setCropMode(false);
} else if (e.key === 'Escape') { } else if (e.key === 'Escape') {
@@ -1528,6 +1663,10 @@ export default function Develop({
set={setEdits} set={setEdits}
activeId={localSelected} activeId={localSelected}
onSelect={(id) => setLocalSelected(id)} onSelect={(id) => setLocalSelected(id)}
componentId={localComponentSelected}
onSelectComponent={setLocalComponentSelected}
onAddComponent={addLocalComponent}
onDeleteComponent={deleteLocalComponent}
onAdd={addLocalLayer} onAdd={addLocalLayer}
onDelete={deleteLocalLayer} onDelete={deleteLocalLayer}
onDuplicate={duplicateLocalLayer} onDuplicate={duplicateLocalLayer}
@@ -2074,7 +2213,7 @@ export default function Develop({
</svg> </svg>
); );
})()} })()}
{localMode && bitmap && activeLocal && (() => { {localMode && bitmap && activeComponent && (() => {
const geo = geoRef.current; const geo = geoRef.current;
const view = geo.view; const view = geo.view;
const marker = (p: { x: number; y: number }) => { const marker = (p: { x: number; y: number }) => {
@@ -2098,47 +2237,66 @@ export default function Develop({
y: ((f.y - view.y) / view.h) * 100, y: ((f.y - view.y) / view.h) * 100,
}; };
}; };
const xScale = bitmap.width / (frame.w * view.w);
const canvasEl = canvasRef.current; const canvasEl = canvasRef.current;
const canvasW = canvasEl?.clientWidth || 1; const canvasW = canvasEl?.clientWidth || 1;
const canvasH = canvasEl?.clientHeight || 1; // A brush radius is a fraction of the source width, but the
const strokes = localDraft // overlay's 100×100 box is stretched over the canvas, so the
? [...activeLocal.brush.strokes, localDraft] // two axes are converted separately. Using one frame term for
: activeLocal.brush.strokes; // both (or the canvas aspect) turns the circle into an oval as
// soon as the photo is cropped or zoomed.
const radiusU = (r: number) => (r * bitmap.width * 100) / (frame.w * view.w);
const radiusV = (r: number) => (r * bitmap.width * 100) / (frame.h * view.h);
/** Brush diameter in canvas pixels, for the stroke preview. */
const diameterPx = (r: number) => (r * 2 * bitmap.width * canvasW) / (frame.w * view.w);
const feather = Math.max(0, Math.min(1, activeComponent.feather / 100));
// Committed strokes are not redrawn here: the shader tints the
// baked mask, which is the real feathered shape. Only the stroke
// in progress is drawn, as a preview of what will be baked.
const draft = localDraft && localDraft.points.length ? localDraft : null;
return ( return (
<svg className="local-layer" viewBox="0 0 100 100" preserveAspectRatio="none"> <svg className="local-layer" viewBox="0 0 100 100" preserveAspectRatio="none">
{activeLocal.kind === 'brush' && {activeComponent.kind === 'brush' &&
strokes.map((stroke, i) => { (() => {
if (!stroke.points.length) return null; if (!draft) return null;
const points = stroke.points.map(marker).map((p) => `${p.x},${p.y}`).join(' '); const points = draft.points.map(marker).map((p) => `${p.x},${p.y}`).join(' ');
const width = Math.max(1, stroke.size * 2 * canvasW); const width = Math.max(1, diameterPx(draft.size));
const core = Math.max(1, width * (1 - feather));
return ( return (
<polyline <g>
key={i} {core < width - 0.5 && (
points={points} <polyline
className={`local-brush ${stroke.erase ? 'erase' : ''}`} points={points}
strokeWidth={width} className={`local-brush band ${draft.erase ? 'erase' : ''}`}
vectorEffect="non-scaling-stroke" strokeWidth={width}
/> vectorEffect="non-scaling-stroke"
/>
)}
<polyline
points={points}
className={`local-brush ${draft.erase ? 'erase' : ''}`}
strokeWidth={core}
vectorEffect="non-scaling-stroke"
/>
</g>
); );
})} })()}
{activeLocal.kind === 'radial' && (() => { {activeComponent.kind === 'radial' && (() => {
const c = marker({ x: activeLocal.radial.cx, y: activeLocal.radial.cy }); const c = marker({ x: activeComponent.radial.cx, y: activeComponent.radial.cy });
const edge = marker({ const edge = marker({
x: activeLocal.radial.cx + activeLocal.radial.rx, x: activeComponent.radial.cx + activeComponent.radial.rx,
y: activeLocal.radial.cy, y: activeComponent.radial.cy,
}); });
const edgeY = marker({ const edgeY = marker({
x: activeLocal.radial.cx, x: activeComponent.radial.cx,
y: activeLocal.radial.cy + activeLocal.radial.ry, y: activeComponent.radial.cy + activeComponent.radial.ry,
}); });
// Sample the perimeter so the guide follows the same warp // Sample the perimeter so the guide follows the same warp
// as the picture instead of staying a screen-space ellipse. // as the picture instead of staying a screen-space ellipse.
const ring = Array.from({ length: 72 }, (_, i) => { const ring = Array.from({ length: 72 }, (_, i) => {
const angle = (i / 72) * Math.PI * 2; const angle = (i / 72) * Math.PI * 2;
const p = marker({ const p = marker({
x: activeLocal.radial.cx + Math.cos(angle) * activeLocal.radial.rx, x: activeComponent.radial.cx + Math.cos(angle) * activeComponent.radial.rx,
y: activeLocal.radial.cy + Math.sin(angle) * activeLocal.radial.ry, y: activeComponent.radial.cy + Math.sin(angle) * activeComponent.radial.ry,
}); });
return `${p.x},${p.y}`; return `${p.x},${p.y}`;
}).join(' '); }).join(' ');
@@ -2155,9 +2313,9 @@ export default function Develop({
</g> </g>
); );
})()} })()}
{activeLocal.kind === 'linear' && (() => { {activeComponent.kind === 'linear' && (() => {
const a = marker({ x: activeLocal.linear.x1, y: activeLocal.linear.y1 }); const a = marker({ x: activeComponent.linear.x1, y: activeComponent.linear.y1 });
const b = marker({ x: activeLocal.linear.x2, y: activeLocal.linear.y2 }); const b = marker({ x: activeComponent.linear.x2, y: activeComponent.linear.y2 });
return ( return (
<g> <g>
<line x1={a.x} y1={a.y} x2={b.x} y2={b.y} className="local-line" vectorEffect="non-scaling-stroke" /> <line x1={a.x} y1={a.y} x2={b.x} y2={b.y} className="local-line" vectorEffect="non-scaling-stroke" />
@@ -2166,16 +2324,34 @@ export default function Develop({
</g> </g>
); );
})()} })()}
{activeLocal.kind === 'brush' && localHover && !localDrag.current && ( {activeComponent.kind === 'brush' && localHover && !localDrag.current && (() => {
<ellipse const c = marker(localHover);
cx={marker(localHover).x} const r = localRadius();
cy={marker(localHover).y} // Feather is the soft band inside the rim, so the inner
rx={localRadius() * xScale * 100} // ring marks where the dab is still at full strength.
ry={localRadius() * 100 * (canvasW / canvasH)} return (
className="local-cursor" <g>
vectorEffect="non-scaling-stroke" <ellipse
/> cx={c.x}
)} cy={c.y}
rx={radiusU(r)}
ry={radiusV(r)}
className="local-cursor"
vectorEffect="non-scaling-stroke"
/>
{feather > 0.02 && (
<ellipse
cx={c.x}
cy={c.y}
rx={radiusU(r * (1 - feather))}
ry={radiusV(r * (1 - feather))}
className="local-cursor inner"
vectorEffect="non-scaling-stroke"
/>
)}
</g>
);
})()}
</svg> </svg>
); );
})()} })()}
@@ -2192,10 +2368,10 @@ export default function Develop({
)} )}
</div> </div>
)} )}
{localMode && activeLocal && !error && ( {localMode && activeLocal && activeComponent && !error && (
<div className="heal-hud local-hud"> <div className="heal-hud local-hud">
<span className="heal-hud-title">Local · {activeLocal.kind}</span> <span className="heal-hud-title">Local · {activeComponent.kind}</span>
{activeLocal.kind === 'brush' && ( {activeComponent.kind === 'brush' && (
<> <>
<label className="heal-field"> <label className="heal-field">
Size Size
@@ -2211,7 +2387,7 @@ export default function Develop({
<span className="heal-read">{Math.round(localBrush)}px</span> <span className="heal-read">{Math.round(localBrush)}px</span>
</> </>
)} )}
{activeLocal.kind !== 'linear' && ( {activeComponent.kind !== 'linear' && (
<> <>
<label className="heal-field"> <label className="heal-field">
Feather Feather
@@ -2220,27 +2396,77 @@ export default function Develop({
min={0} min={0}
max={100} max={100}
step={1} step={1}
value={activeLocal.feather} value={activeComponent.feather}
onChange={(e) => patchLocal(activeLocal.id, { feather: Number(e.target.value) }, 'Local feather')} onChange={(e) =>
patchComponent(
activeLocal.id,
activeComponent.id,
{ feather: Number(e.target.value) },
'Local feather',
)
}
/> />
</label> </label>
<span className="heal-read">{Math.round(activeLocal.feather)}%</span> <span className="heal-read">{Math.round(activeComponent.feather)}%</span>
</> </>
)} )}
<button
className={`heal-act ${(activeComponent.kind === 'brush' ? !localErase : activeComponent.mode !== 'subtract') ? 'on' : ''}`}
onClick={() => {
if (activeComponent.kind === 'brush') {
setLocalErase(false);
} else if (activeComponent.mode === 'subtract') {
patchComponent(activeLocal.id, activeComponent.id, { mode: 'add' }, 'Shape add');
}
}}
title="Add to the mask (+)"
>
+
</button>
<button
className={`heal-act ${(activeComponent.kind === 'brush' ? localErase : activeComponent.mode === 'subtract') ? 'on' : ''}`}
onClick={() => {
if (activeComponent.kind === 'brush') {
setLocalErase(true);
} else {
patchComponent(activeLocal.id, activeComponent.id, { mode: 'subtract' }, 'Shape subtract');
}
}}
disabled={
activeComponent.kind !== 'brush' &&
activeLocal.components[0]?.id === activeComponent.id
}
title={
activeComponent.kind === 'brush'
? 'Erase from the mask (−)'
: activeLocal.components[0]?.id === activeComponent.id
? 'The first shape starts the mask, so it always adds'
: 'Subtract this shape from the mask (−)'
}
>
−
</button>
<button <button
className="heal-act" className="heal-act"
onClick={() => { onClick={() => {
if (activeLocal.kind === 'brush') { if (activeComponent.kind === 'brush') {
patchLocal(activeLocal.id, { brush: { strokes: [] } }, 'Clear local mask'); patchComponent(
} else if (activeLocal.kind === 'radial') {
patchLocal(
activeLocal.id, activeLocal.id,
activeComponent.id,
{ brush: { strokes: [] } },
'Clear local mask',
);
} else if (activeComponent.kind === 'radial') {
patchComponent(
activeLocal.id,
activeComponent.id,
{ radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 } }, { radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 } },
'Reset local mask', 'Reset local mask',
); );
} else { } else {
patchLocal( patchComponent(
activeLocal.id, activeLocal.id,
activeComponent.id,
{ linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 } }, { linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 } },
'Reset local mask', 'Reset local mask',
); );
@@ -2249,13 +2475,36 @@ export default function Develop({
> >
Clear Clear
</button> </button>
<button
className={`heal-act ${maskOverlay ? 'on' : ''}`}
onClick={() => setMaskOverlay((v) => !v)}
title="Show or hide the mask tint (O)"
>
Mask
</button>
{maskOverlay && (
<>
<label className="heal-field">
Tint
<input
type="range"
min={10}
max={100}
step={1}
value={maskStrength}
onChange={(e) => setMaskStrength(Number(e.target.value))}
/>
</label>
<span className="heal-read">{Math.round(maskStrength)}%</span>
</>
)}
<button className="heal-act on" onClick={() => setLocalMode(false)}> <button className="heal-act on" onClick={() => setLocalMode(false)}>
Done Done
</button> </button>
<span className="heal-tip"> <span className="heal-tip">
{activeLocal.kind === 'brush' {activeComponent.kind === 'brush'
? 'Paint the mask · Alt paints an erase stroke · wheel sizes the brush' ? 'Paint the mask · − erases · Alt erases one stroke · wheel sizes the brush'
: activeLocal.kind === 'radial' : activeComponent.kind === 'radial'
? 'Drag the centre or the edge handle · wheel zooms' ? 'Drag the centre or the edge handle · wheel zooms'
: 'Drag either end of the gradient'} : 'Drag either end of the gradient'}
</span> </span>
@@ -2381,13 +2630,29 @@ export default function Develop({
</button> </button>
</div> </div>
)} )}
{clipPreview && ( {(clipPreview || clipping === 'shadows') && (
<div className="clip-legend"> <div className="clip-legend">
<span className="clip-dot r" /> red {clipPreview ? (
<span className="clip-dot g" /> green <>
<span className="clip-dot b" /> blue <span className="clip-dot r" /> red
<span className="clip-dot y" /> two channels <span className="clip-dot g" /> green
<span className="clip-dot w" /> all three <span className="clip-dot b" /> blue
<span className="clip-dot y" /> two channels
<span className="clip-dot w" /> all three
</>
) : (
<>
<span className="clip-dot r" />
<span className="clip-dot g" />
<span className="clip-dot b" />
<span className="clip-label">one channel</span>
<span className="clip-dot y" />
<span className="clip-dot m" />
<span className="clip-dot c" />
<span className="clip-label">two channels</span>
<span className="clip-dot w" /> all three
</>
)}
</div> </div>
)} )}
{loupe && !adjustOpen && ( {loupe && !adjustOpen && (
+162 -22
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react'; import { useEffect, useMemo, useRef, useState } from 'react';
import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_LAYERS } from '../lib/edits'; import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_COMPONENTS, MAX_LOCAL_LAYERS } from '../lib/edits';
import { computeAutoEdits, computeAutoWhiteBalance } from '../lib/auto'; import { computeAutoEdits, computeAutoWhiteBalance } from '../lib/auto';
import { autoNoiseFor } from '../lib/noiseProfile'; import { autoNoiseFor } from '../lib/noiseProfile';
import { clearDenoised, getDenoiseJob, startDenoise } from '../lib/api'; import { clearDenoised, getDenoiseJob, startDenoise } from '../lib/api';
@@ -9,6 +9,7 @@ import type {
Edits, Edits,
EventRecord, EventRecord,
HistoryEntry, HistoryEntry,
LocalComponent,
LocalLayer, LocalLayer,
LocalMaskKind, LocalMaskKind,
MetadataPreset, MetadataPreset,
@@ -94,10 +95,15 @@ export function BasicPanel({
const [autoBusy, setAutoBusy] = useState(false); const [autoBusy, setAutoBusy] = useState(false);
const [wbBusy, setWbBusy] = useState(false); const [wbBusy, setWbBusy] = useState(false);
// Raws carry their pixels as a URL, with `thumb` empty; handing the empty
// string to the analysis made the decode fail and both Auto buttons quietly
// come back with neutral values, so Auto WB matched As shot exactly.
const thumbSrc = photo.thumbUrl ?? photo.thumb;
const auto = async () => { const auto = async () => {
setAutoBusy(true); setAutoBusy(true);
try { try {
const partial = await computeAutoEdits(photo.thumb); const partial = await computeAutoEdits(thumbSrc);
set(partial, 'Auto tone'); set(partial, 'Auto tone');
} finally { } finally {
setAutoBusy(false); setAutoBusy(false);
@@ -107,7 +113,7 @@ export function BasicPanel({
const autoWb = async () => { const autoWb = async () => {
setWbBusy(true); setWbBusy(true);
try { try {
set(await computeAutoWhiteBalance(photo.thumb), 'Auto white balance'); set(await computeAutoWhiteBalance(thumbSrc), 'Auto white balance');
} finally { } finally {
setWbBusy(false); setWbBusy(false);
} }
@@ -1475,7 +1481,13 @@ export function NavigatorPanel({
{photo.name} {photo.name}
</div> </div>
<div className="muted small navigator-meta"> <div className="muted small navigator-meta">
{photo.raw ? (photo.decode === 'embedded' ? 'Raw · camera preview' : 'Raw · demosaiced') : 'JPEG/PNG'}{' '} {photo.raw
? photo.decode === 'embedded'
? 'Raw · camera preview'
: 'Raw · demosaiced'
: photo.decode === 'sharp'
? 'TIFF · server JPEG'
: 'JPEG/PNG'}{' '}
· {photo.width}×{photo.height} · {photo.width}×{photo.height}
</div> </div>
</div> </div>
@@ -1489,6 +1501,10 @@ export function LocalPanel({
set, set,
activeId, activeId,
onSelect, onSelect,
componentId,
onSelectComponent,
onAddComponent,
onDeleteComponent,
onAdd, onAdd,
onDelete, onDelete,
onDuplicate, onDuplicate,
@@ -1505,6 +1521,11 @@ export function LocalPanel({
}: PanelSetProps & { }: PanelSetProps & {
activeId: string | null; activeId: string | null;
onSelect: (id: string) => void; onSelect: (id: string) => void;
/** Shape inside the active layer that the mask controls edit. */
componentId: string | null;
onSelectComponent: (id: string) => void;
onAddComponent: (kind: LocalMaskKind) => void;
onDeleteComponent: (id: string) => void;
onAdd: (kind: LocalMaskKind) => void; onAdd: (kind: LocalMaskKind) => void;
onDelete: (id: string) => void; onDelete: (id: string) => void;
onDuplicate: (id: string) => void; onDuplicate: (id: string) => void;
@@ -1522,11 +1543,31 @@ export function LocalPanel({
}) { }) {
const layers = edits.local ?? []; const layers = edits.local ?? [];
const active = layers.find((layer) => layer.id === activeId) ?? null; const active = layers.find((layer) => layer.id === activeId) ?? null;
const shapes = active?.components ?? [];
const shape = shapes.find((component) => component.id === componentId) ?? shapes[0] ?? null;
const patch = (next: Partial<LocalLayer>, label: string) => { const patch = (next: Partial<LocalLayer>, label: string) => {
if (!active) return; if (!active) return;
set({ local: layers.map((layer) => (layer.id === active.id ? { ...layer, ...next } : layer)) }, label); set({ local: layers.map((layer) => (layer.id === active.id ? { ...layer, ...next } : layer)) }, label);
}; };
const patchShape = (next: Partial<LocalComponent>, label: string) => {
if (!active || !shape) return;
set(
{
local: layers.map((layer) =>
layer.id === active.id
? {
...layer,
components: layer.components.map((component) =>
component.id === shape.id ? { ...component, ...next } : component,
),
}
: layer,
),
},
label,
);
};
const adjust = (key: keyof LocalLayer['adjust'], value: number) => const adjust = (key: keyof LocalLayer['adjust'], value: number) =>
active && patch({ adjust: { ...active.adjust, [key]: value } }, `Local ${key}`); active && patch({ adjust: { ...active.adjust, [key]: value } }, `Local ${key}`);
const range = (key: keyof LocalLayer['range'], value: number | boolean) => const range = (key: keyof LocalLayer['range'], value: number | boolean) =>
@@ -1589,21 +1630,55 @@ export function LocalPanel({
className={`local-item ${layer.id === activeId ? 'on' : ''}`} className={`local-item ${layer.id === activeId ? 'on' : ''}`}
onClick={() => onSelect(layer.id)} onClick={() => onSelect(layer.id)}
> >
<span className="local-icon">{LOCAL_ICON[layer.kind]}</span> <span className="local-icon">{LOCAL_ICON[layer.components[0]?.kind ?? 'brush']}</span>
<span className="local-name">{layer.name}</span> <span className="local-name">{layer.name}</span>
<span className="local-kind">{layer.kind}</span> <span className="local-kind">
{layer.components.length > 1
? `${layer.components.length} shapes`
: (layer.components[0]?.kind ?? 'mask')}
</span>
</button> </button>
))} ))}
</div> </div>
{active && ( <div className="local-subhead">Mask shapes</div>
<div className="local-list shapes">
{shapes.map((component, index) => (
<button
key={component.id}
className={`local-item ${component.id === shape?.id ? 'on' : ''}`}
onClick={() => onSelectComponent(component.id)}
>
<span className="local-icon">{LOCAL_ICON[component.kind]}</span>
<span className="local-name">Shape {index + 1}</span>
<span className="local-kind">
{component.mode === 'add' ? component.kind : `${component.kind} · ${component.mode}`}
</span>
</button>
))}
</div>
<div className="btn-row local-add">
{(['brush', 'linear', 'radial'] as const).map((kind) => (
<button
key={kind}
className="btn ghost small"
onClick={() => onAddComponent(kind)}
disabled={shapes.length >= MAX_LOCAL_COMPONENTS}
title="Add a shape to this mask group"
>
+ {LOCAL_ICON[kind]} {kind}
</button>
))}
</div>
{active && shape && (
<> <>
<div className="btn-row local-actions"> <div className="btn-row local-actions">
<button <button
className={`btn ghost small ${maskMode ? 'on' : ''}`} className={`btn ghost small ${maskMode ? 'on' : ''}`}
onClick={onEditMask} onClick={onEditMask}
disabled={active.kind === 'raster'} disabled={shape.kind === 'raster'}
title={active.kind === 'raster' ? 'Auto masks are generated, not painted' : undefined} title={shape.kind === 'raster' ? 'Auto masks are generated, not painted' : undefined}
> >
{maskMode ? 'Done mask' : 'Edit mask'} {maskMode ? 'Done mask' : 'Edit mask'}
</button> </button>
@@ -1615,13 +1690,13 @@ export function LocalPanel({
</button> </button>
</div> </div>
{active.kind === 'raster' && ( {shape.kind === 'raster' && (
<p className="muted small panel-hint"> <p className="muted small panel-hint">
Auto mask · adjust the feather, invert it, paint it away by adding a brush layer, or regenerate from the buttons above. Auto mask · adjust the feather, invert it, paint it away by adding a brush layer, or regenerate from the buttons above.
</p> </p>
)} )}
{active.kind === 'brush' && ( {shape.kind === 'brush' && (
<Slider <Slider
label="Brush size" label="Brush size"
min={8} min={8}
@@ -1633,19 +1708,56 @@ export function LocalPanel({
/> />
)} )}
{active.kind !== 'linear' && ( {shape.kind !== 'linear' && (
<Slider <Slider
label="Feather" label="Feather"
min={0} min={0}
max={100} max={100}
value={active.feather} value={shape.feather}
def={50} def={50}
onChange={(v) => patch({ feather: v }, 'Local feather')} onChange={(v) => patchShape({ feather: v }, 'Local feather')}
format={(v) => `${Math.round(v)}%`} format={(v) => `${Math.round(v)}%`}
/> />
)} )}
<div className="local-subhead">Combine</div> <div className="local-subhead">Shape blend</div>
<div className="btn-row local-modes">
{(['add', 'subtract', 'intersect'] as const).map((mode) => (
<button
key={mode}
className={`chip tiny ${shape.mode === mode ? 'on' : ''}`}
disabled={shapes[0]?.id === shape.id && mode !== 'add'}
title={
shapes[0]?.id === shape.id
? 'The first shape starts the group, so it always adds'
: mode === 'add'
? 'Union this shape into the group'
: mode === 'subtract'
? 'Cut this shape out of the shapes before it'
: 'Keep only where this shape overlaps the shapes before it'
}
onClick={() => patchShape({ mode }, `Shape ${mode}`)}
>
{mode === 'add' ? 'Add' : mode === 'subtract' ? 'Subtract' : 'Intersect'}
</button>
))}
</div>
<div className="btn-row">
<button
className="btn ghost small danger"
onClick={() => onDeleteComponent(shape.id)}
disabled={shapes.length <= 1}
title={
shapes.length <= 1
? 'A layer needs one shape; delete the layer instead'
: 'Remove this shape from the group'
}
>
Delete shape
</button>
</div>
<div className="local-subhead">Layer blend</div>
<div className="btn-row local-modes"> <div className="btn-row local-modes">
{(['add', 'subtract', 'intersect'] as const).map((mode) => ( {(['add', 'subtract', 'intersect'] as const).map((mode) => (
<button <button
@@ -1653,18 +1765,25 @@ export function LocalPanel({
className={`chip tiny ${active.mode === mode ? 'on' : ''}`} className={`chip tiny ${active.mode === mode ? 'on' : ''}`}
title={ title={
mode === 'add' mode === 'add'
? 'Apply this adjustment inside the mask' ? 'Apply this layer inside its mask'
: mode === 'subtract' : mode === 'subtract'
? 'Apply it outside this mask, within the layer above' ? 'Apply it outside its mask, within the layer above'
: 'Apply it only where this mask overlaps the layer above' : 'Apply it only where the mask overlaps the layer above'
} }
onClick={() => patch({ mode }, `Mask ${mode}`)} onClick={() => patch({ mode }, `Layer ${mode}`)}
> >
{mode === 'add' ? 'Add' : mode === 'subtract' ? 'Subtract' : 'Intersect'} {mode === 'add' ? 'Add' : mode === 'subtract' ? 'Subtract' : 'Intersect'}
</button> </button>
))} ))}
</div> </div>
<div className="local-subhead">Mask curve</div>
<CurveEditor
points={active.curve}
onChange={(points) => patch({ curve: points }, 'Mask curve')}
color="#f2f4f8"
/>
<div className="local-subhead">Light</div> <div className="local-subhead">Light</div>
<Slider <Slider
label="Exposure" label="Exposure"
@@ -1811,8 +1930,8 @@ export function LocalPanel({
<div className="btn-row"> <div className="btn-row">
<button <button
className={`btn ghost small ${active.inverted ? 'on' : ''}`} className={`btn ghost small ${shape.inverted ? 'on' : ''}`}
onClick={() => patch({ inverted: !active.inverted }, 'Invert mask')} onClick={() => patchShape({ inverted: !shape.inverted }, 'Invert mask')}
> >
Invert mask Invert mask
</button> </button>
@@ -1915,7 +2034,10 @@ export function OpticsPanel({
model: result.model, model: result.model,
crop: result.crop, crop: result.crop,
cameraModel: photo.meta.camera ?? undefined, cameraModel: photo.meta.camera ?? undefined,
corrections: { distortion: true, tca: true, vignetting: true }, // Geometry and CA are safe to correct on their own; the vignetting gain
// lifts the corners above the frame centre, so it is left for the user to
// enable on the profile they applied.
corrections: { distortion: true, tca: true, vignetting: false },
distance: 1000, distance: 1000,
}; };
set({ lens: next }, 'Lens profile'); set({ lens: next }, 'Lens profile');
@@ -2110,6 +2232,12 @@ export function OpticsPanel({
</label> </label>
); );
})} })}
{!profile.corrections.vignetting && (
<p className="muted small lens-msg">
Vignetting correction is off, so the corners keep the lens's own falloff.
Tick Vignetting to lift them back to the centre.
</p>
)}
{lensState?.loading && <p className="muted small lens-msg">Building correction maps…</p>} {lensState?.loading && <p className="muted small lens-msg">Building correction maps…</p>}
{lensState?.error && <p className="small lens-error">{lensState.error}</p>} {lensState?.error && <p className="small lens-error">{lensState.error}</p>}
{onLensSplit && ( {onLensSplit && (
@@ -2487,10 +2615,22 @@ export function MetadataPanel({
const event = events.find((e) => e.id === photo.eventId); const event = events.find((e) => e.id === photo.eventId);
const [keyword, setKeyword] = useState(''); const [keyword, setKeyword] = useState('');
const [presetId, setPresetId] = useState(''); const [presetId, setPresetId] = useState('');
const decodeLabel = photo.raw
? photo.decode === 'embedded'
? 'LibRaw · camera preview fallback'
: 'LibRaw demosaic'
: photo.decode === 'sharp'
? 'sharp JPEG proxy'
: 'Browser';
const proxyLabel = `${photo.width} × ${photo.height}${
photo.proxyBytes ? ` · ${(photo.proxyBytes / (1024 * 1024)).toFixed(1)} MB` : ''
}`;
const rows: [string, string][] = [ const rows: [string, string][] = [
['File', photo.name], ['File', photo.name],
['Dimensions', `${photo.width} × ${photo.height}`], ['Dimensions', `${photo.width} × ${photo.height}`],
['Size', `${(photo.size / (1024 * 1024)).toFixed(2)} MB`], ['Size', `${(photo.size / (1024 * 1024)).toFixed(2)} MB`],
['Decode', decodeLabel],
['Proxy', proxyLabel],
['Camera', photo.meta.camera ?? '—'], ['Camera', photo.meta.camera ?? '—'],
['Lens', photo.meta.lens ?? '—'], ['Lens', photo.meta.lens ?? '—'],
['ISO', photo.meta.iso ? String(photo.meta.iso) : '—'], ['ISO', photo.meta.iso ? String(photo.meta.iso) : '—'],
+1
View File
@@ -36,6 +36,7 @@ const GROUPS: { title: string; rows: [string, string][] }[] = [
['C', 'Crop & straighten'], ['C', 'Crop & straighten'],
['Q', 'Spot healing brush'], ['Q', 'Spot healing brush'],
['M', 'Edit the selected local mask'], ['M', 'Edit the selected local mask'],
['O', 'Show or hide the mask tint'],
['Enter', 'Apply the crop'], ['Enter', 'Apply the crop'],
['\\ (hold)', 'Before / after'], ['\\ (hold)', 'Before / after'],
['1 – 5', 'Star rating'], ['1 – 5', 'Star rating'],
+19 -6
View File
@@ -7,11 +7,14 @@ interface Props {
selectedCount: number; selectedCount: number;
cloudLabel: string; cloudLabel: string;
cloudOn: boolean; cloudOn: boolean;
/** Desktop mode has no account, so the team-server button is not shown. */
localMode?: boolean;
onViewChange: (view: ViewMode) => void; onViewChange: (view: ViewMode) => void;
onImport: () => void; onImport: () => void;
onExport: () => void; onExport: () => void;
onCloud: () => void; onCloud: () => void;
onHelp: () => void; onHelp: () => void;
onAbout: () => void;
onSearch: () => void; onSearch: () => void;
onCatalog: () => void; onCatalog: () => void;
canShare: boolean; canShare: boolean;
@@ -25,11 +28,13 @@ export default function TopBar({
selectedCount, selectedCount,
cloudLabel, cloudLabel,
cloudOn, cloudOn,
localMode = false,
onViewChange, onViewChange,
onImport, onImport,
onExport, onExport,
onCloud, onCloud,
onHelp, onHelp,
onAbout,
onSearch, onSearch,
onCatalog, onCatalog,
canShare, canShare,
@@ -37,10 +42,16 @@ export default function TopBar({
}: Props) { }: Props) {
return ( return (
<header className="topbar"> <header className="topbar">
<div className="brand"> <button
type="button"
className="brand brand-btn"
onClick={onAbout}
title="About Luminary"
aria-label="About Luminary"
>
<img className="brand-mark" src="/logo.png" alt="" height={20} /> <img className="brand-mark" src="/logo.png" alt="" height={20} />
Luminary Luminary
</div> </button>
<button <button
type="button" type="button"
className="icon-btn mobile-only catalog-btn" className="icon-btn mobile-only catalog-btn"
@@ -70,10 +81,12 @@ export default function TopBar({
</nav> </nav>
<div className="topbar-actions"> <div className="topbar-actions">
<button className={`cloud-pill ${cloudOn ? 'on' : ''}`} onClick={onCloud} title="Team server"> {!localMode && (
<span className="cloud-dot" /> <button className={`cloud-pill ${cloudOn ? 'on' : ''}`} onClick={onCloud} title="Team server">
{cloudLabel} <span className="cloud-dot" />
</button> {cloudLabel}
</button>
)}
{canShare && ( {canShare && (
<button className="btn ghost" onClick={onShare} title="Share this event for client proofing"> <button className="btn ghost" onClick={onShare} title="Share this event for client proofing">
Share Share
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from 'vitest';
import { blendCoverage, maskSize } from './masks';
/** Coverage values are 0–1 inside the baker, which this keeps readable. */
describe('mask texture size', () => {
it('keeps square mask pixels so a round brush stays round', () => {
const tall = maskSize(3000, 9000);
expect(tall.h).toBeLessThanOrEqual(1400);
expect(tall.w / tall.h).toBeCloseTo(1 / 3, 2);
const wide = maskSize(15000, 1000);
expect(wide.h).toBeGreaterThanOrEqual(120);
expect(wide.w / wide.h).toBeCloseTo(15, 1);
});
it('uses the full width for a normal photo', () => {
expect(maskSize(3464, 5202)).toEqual({ w: 800, h: 1201 });
});
});
describe('mask group compositing', () => {
it('starts a group with the first shape whatever its mode says', () => {
expect(blendCoverage(0, 0.6, 'subtract', true)).toBe(0.6);
expect(blendCoverage(0, 0.6, 'intersect', true)).toBe(0.6);
});
it('unions added shapes instead of stacking them', () => {
expect(blendCoverage(0.4, 0.7, 'add', false)).toBe(0.7);
expect(blendCoverage(0.7, 0.4, 'add', false)).toBe(0.7);
});
it('subtracts coverage from the group', () => {
expect(blendCoverage(1, 0.25, 'subtract', false)).toBeCloseTo(0.75, 6);
expect(blendCoverage(1, 1, 'subtract', false)).toBe(0);
});
it('keeps only the overlap for an intersect shape', () => {
expect(blendCoverage(0.8, 0.5, 'intersect', false)).toBeCloseTo(0.4, 6);
expect(blendCoverage(0.8, 0, 'intersect', false)).toBe(0);
});
});
+140 -70
View File
@@ -1,11 +1,13 @@
import type { LocalLayer } from '../types'; import type { LocalComponent, LocalLayer } from '../types';
import { MAX_LOCAL_LAYERS } from '../lib/edits'; import { MAX_LOCAL_LAYERS } from '../lib/edits';
/** /**
* Local masks are baked on the CPU into two RGBA textures, one layer per * Local masks are baked on the CPU into two RGBA textures, one layer per
* channel, so the grade shader can apply up to eight adjustments in a single * channel, so the grade shader can apply up to eight adjustments in a single
* pass. The mask is source-space, which keeps brushes and gradients attached to * pass. A layer's mask is a group of shapes composited in order: add unions,
* the picture through crops, straightening, zoom and lens correction. * subtract cuts a hole, intersect keeps the overlap. The mask is source-space,
* which keeps brushes and gradients attached to the picture through crops,
* straightening, zoom and lens correction.
*/ */
export interface PackedMasks { export interface PackedMasks {
@@ -23,19 +25,22 @@ export function maskSignature(layers: LocalLayer[], srcW: number, srcH: number)
srcW, srcW,
srcH, srcH,
layers: layers.slice(0, MAX_LOCAL_LAYERS).map((layer) => ({ layers: layers.slice(0, MAX_LOCAL_LAYERS).map((layer) => ({
kind: layer.kind, components: (layer.components ?? []).map((component) => ({
inverted: layer.inverted, kind: component.kind,
feather: layer.feather, mode: component.mode,
brush: layer.brush, inverted: component.inverted,
linear: layer.linear, feather: component.feather,
radial: layer.radial, brush: component.brush,
raster: layer.raster linear: component.linear,
? { radial: component.radial,
width: layer.raster.width, raster: component.raster
height: layer.raster.height, ? {
hash: rasterHash(layer.raster.data), width: component.raster.width,
} height: component.raster.height,
: null, hash: rasterHash(component.raster.data),
}
: null,
})),
})), })),
}); });
} }
@@ -49,8 +54,8 @@ function rasterHash(data: string) {
return `${data.length}:${hash >>> 0}`; return `${data.length}:${hash >>> 0}`;
} }
function drawRaster(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) { function drawRaster(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
const mask = layer.raster; const mask = component.raster;
if (!mask) return; if (!mask) return;
try { try {
const binary = atob(mask.data); const binary = atob(mask.data);
@@ -82,13 +87,13 @@ function makeCanvas(w: number, h: number) {
return canvas; return canvas;
} }
function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) { function drawRadial(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
const { cx, cy, rx, ry } = layer.radial; const { cx, cy, rx, ry } = component.radial;
ctx.save(); ctx.save();
ctx.translate(cx * w, cy * h); ctx.translate(cx * w, cy * h);
ctx.scale(Math.max(1, rx * w), Math.max(1, ry * h)); ctx.scale(Math.max(1, rx * w), Math.max(1, ry * h));
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1); const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
const inner = Math.max(0, Math.min(0.98, 1 - layer.feather / 100)); const inner = Math.max(0, Math.min(0.98, 1 - component.feather / 100));
gradient.addColorStop(0, 'rgba(255,255,255,1)'); gradient.addColorStop(0, 'rgba(255,255,255,1)');
if (inner > 0.001) gradient.addColorStop(inner, 'rgba(255,255,255,1)'); if (inner > 0.001) gradient.addColorStop(inner, 'rgba(255,255,255,1)');
gradient.addColorStop(1, 'rgba(255,255,255,0)'); gradient.addColorStop(1, 'rgba(255,255,255,0)');
@@ -99,8 +104,8 @@ function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
ctx.restore(); ctx.restore();
} }
function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) { function drawLinear(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
const { x1, y1, x2, y2 } = layer.linear; const { x1, y1, x2, y2 } = component.linear;
const gradient = ctx.createLinearGradient(x1 * w, y1 * h, x2 * w, y2 * h); const gradient = ctx.createLinearGradient(x1 * w, y1 * h, x2 * w, y2 * h);
gradient.addColorStop(0, 'rgba(255,255,255,1)'); gradient.addColorStop(0, 'rgba(255,255,255,1)');
gradient.addColorStop(1, 'rgba(255,255,255,0)'); gradient.addColorStop(1, 'rgba(255,255,255,0)');
@@ -108,32 +113,66 @@ function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
ctx.fillRect(0, 0, w, h); ctx.fillRect(0, 0, w, h);
} }
function drawBrush(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) { /**
ctx.lineCap = 'round'; * One brush dab: white, solid out to `1 - feather` of the radius and fading to
ctx.lineJoin = 'round'; * nothing at the rim. Feather is the width of that band, so a stroke softens
for (const stroke of layer.brush.strokes) { * inside the brush outline instead of spreading a halo past it.
*/
function brushDab(feather: number) {
const size = 64;
const canvas = makeCanvas(size, size);
const ctx = canvas.getContext('2d');
if (!ctx) return canvas;
const r = size / 2;
// A hair of softness even at 0 keeps the rim from aliasing on screen.
const soft = Math.max(0.02, Math.min(1, feather / 100));
const gradient = ctx.createRadialGradient(r, r, r * (1 - soft), r, r, r);
gradient.addColorStop(0, 'rgba(255,255,255,1)');
gradient.addColorStop(0.45, 'rgba(255,255,255,0.88)');
gradient.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, size, size);
return canvas;
}
/**
* Stamps the dab along the path. A stroked line can only have a hard edge, so
* the stroke is drawn as overlapping dabs: the rim is the dab's falloff, which
* keeps the mask inside the brush circle and smooth at every size.
*/
function drawBrush(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
const dab = brushDab(component.feather);
for (const stroke of component.brush.strokes) {
if (!stroke.points.length) continue; if (!stroke.points.length) continue;
const width = Math.max(1, stroke.size * 2 * w); const radius = Math.max(1, stroke.size * w);
const stamp = (x: number, y: number) =>
ctx.drawImage(dab, x - radius, y - radius, radius * 2, radius * 2);
ctx.globalCompositeOperation = stroke.erase ? 'destination-out' : 'source-over'; ctx.globalCompositeOperation = stroke.erase ? 'destination-out' : 'source-over';
ctx.strokeStyle = 'rgba(255,255,255,1)'; const first = stroke.points[0];
ctx.fillStyle = 'rgba(255,255,255,1)'; stamp(first.x * w, first.y * h);
ctx.lineWidth = width; // Close enough that consecutive dabs overlap well inside the soft band.
if (stroke.points.length === 1) { const spacing = Math.max(0.75, radius * 0.35);
ctx.beginPath();
ctx.arc(stroke.points[0].x * w, stroke.points[0].y * h, width / 2, 0, Math.PI * 2);
ctx.fill();
continue;
}
ctx.beginPath();
ctx.moveTo(stroke.points[0].x * w, stroke.points[0].y * h);
for (let i = 1; i < stroke.points.length; i++) { for (let i = 1; i < stroke.points.length; i++) {
ctx.lineTo(stroke.points[i].x * w, stroke.points[i].y * h); const a = stroke.points[i - 1];
const b = stroke.points[i];
const dx = (b.x - a.x) * w;
const dy = (b.y - a.y) * h;
const steps = Math.max(1, Math.ceil(Math.hypot(dx, dy) / spacing));
for (let step = 1; step <= steps; step++) {
stamp(a.x * w + (dx * step) / steps, a.y * h + (dy * step) / steps);
}
} }
ctx.stroke();
} }
ctx.globalCompositeOperation = 'source-over'; ctx.globalCompositeOperation = 'source-over';
} }
function drawComponent(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
if (component.kind === 'radial') drawRadial(ctx, component, w, h);
else if (component.kind === 'linear') drawLinear(ctx, component, w, h);
else if (component.kind === 'raster') drawRaster(ctx, component, w, h);
else drawBrush(ctx, component, w, h);
}
/** /**
* Softens a mask rim without thinning what was painted. A plain blur pulls the * Softens a mask rim without thinning what was painted. A plain blur pulls the
* stroke edge inward and drops thin strokes below full coverage, which reads as * stroke edge inward and drops thin strokes below full coverage, which reads as
@@ -155,9 +194,43 @@ function featherMask(canvas: HTMLCanvasElement, radius: number) {
return out; return out;
} }
/**
* How one shape's coverage joins the accumulated mask inside its layer. The
* first shape starts the group, so its mode is ignored: there is nothing to
* subtract from or intersect with yet.
*/
export function blendCoverage(
acc: number,
value: number,
mode: LocalComponent['mode'],
first: boolean,
) {
if (first) return value;
if (mode === 'subtract') return acc * (1 - value);
if (mode === 'intersect') return acc * value;
return Math.max(acc, value);
}
/**
* Mask texture size. Pixels are square, so both dimensions scale together with
* the source: clamping only the height would squeeze every round dab into an
* ellipse on tall or wide frames, so the width shrinks instead.
*/
export function maskSize(srcW: number, srcH: number) {
const safeW = Math.max(1, srcW);
const safeH = Math.max(1, srcH);
let w = 800;
let h = Math.round((w * safeH) / safeW);
const limit = h > 1400 ? 1400 : h < 120 ? 120 : 0;
if (limit) {
h = limit;
w = Math.max(160, Math.round((h * safeW) / safeH));
}
return { w, h: Math.max(1, h) };
}
export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks { export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks {
const w = 800; const { w, h } = maskSize(srcW, srcH);
const h = Math.max(120, Math.min(1400, Math.round((w * Math.max(1, srcH)) / Math.max(1, srcW))));
const out = new Uint8Array(w * h * 4); const out = new Uint8Array(w * h * 4);
const out2 = new Uint8Array(w * h * 4); const out2 = new Uint8Array(w * h * 4);
const count = Math.min(MAX_LOCAL_LAYERS, layers.length); const count = Math.min(MAX_LOCAL_LAYERS, layers.length);
@@ -165,40 +238,37 @@ export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number
for (let index = 0; index < count; index++) { for (let index = 0; index < count; index++) {
const layer = layers[index]; const layer = layers[index];
const canvas = makeCanvas(w, h); const components = layer.components ?? [];
const ctx = canvas.getContext('2d'); const acc = new Uint8Array(w * h);
if (!ctx) continue; let first = true;
ctx.clearRect(0, 0, w, h);
if (layer.kind === 'radial') drawRadial(ctx, layer, w, h); for (const component of components) {
else if (layer.kind === 'linear') drawLinear(ctx, layer, w, h); const canvas = makeCanvas(w, h);
else if (layer.kind === 'raster') drawRaster(ctx, layer, w, h); const ctx = canvas.getContext('2d');
else drawBrush(ctx, layer, w, h); if (!ctx) continue;
ctx.clearRect(0, 0, w, h);
drawComponent(ctx, component, w, h);
let source = canvas; let source = canvas;
if (layer.kind === 'brush') { if (component.kind === 'raster') {
// Feather follows the brush, not the frame: 100% softens the edge by // Generated masks are low-resolution coverage, so their feather is tied
// roughly three quarters of the stroke's half width, so a small dab and a // to the frame width and only ever loosens the outside edge.
// wide sweep both feel the same under the slider. source = featherMask(canvas, ((component.feather / 100) * w) / 16);
let widest = 0;
for (const stroke of layer.brush.strokes) {
widest = Math.max(widest, stroke.size * 2 * w);
} }
source = featherMask(canvas, (layer.feather / 100) * widest * 0.75);
} else if (layer.kind === 'raster') { const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
// Generated masks are low-resolution coverage, so their feather is tied if (!pixels) continue;
// to the frame width and only ever loosens the outside edge. for (let p = 0, o = 0; p < pixels.length; p += 4, o++) {
source = featherMask(canvas, ((layer.feather / 100) * w) / 16); let value = pixels[p + 3] / 255;
if (component.inverted) value = 1 - value;
acc[o] = Math.round(blendCoverage(acc[o] / 255, value, component.mode, first) * 255);
}
first = false;
} }
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
if (!pixels) continue;
const channel = index % 4; const channel = index % 4;
const target = index < 4 ? out : out2; const target = index < 4 ? out : out2;
for (let p = 0, o = 0; p < pixels.length; p += 4, o += 4) { for (let o = 0; o < acc.length; o++) target[o * 4 + channel] = acc[o];
const alpha = pixels[p + 3];
target[o + channel] = layer.inverted ? 255 - alpha : alpha;
}
} }
return { data: out, data2: out2, w, h }; return { data: out, data2: out2, w, h };
+229 -41
View File
@@ -1,6 +1,6 @@
import type { LensCorrection } from '../lib/lensEngine'; import type { LensCorrection } from '../lib/lensEngine';
import type { Preview16 } from '../lib/preview16'; import type { Preview16 } from '../lib/preview16';
import type { Edits, GeometryEdits } from '../types'; import type { CurvePoint, Edits, GeometryEdits, LocalLayer } from '../types';
import { buildSampler, clamp01 } from '../lib/curves'; import { buildSampler, clamp01 } from '../lib/curves';
import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits'; import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits';
import { wbGainFor } from '../lib/whiteBalance'; import { wbGainFor } from '../lib/whiteBalance';
@@ -18,7 +18,11 @@ void main(){
const GRADE_FRAG = `#version 300 es const GRADE_FRAG = `#version 300 es
precision highp float; precision highp float;
in vec2 v_uv; in vec2 v_uv;
out vec4 outColor; layout(location = 0) out vec4 outColor;
// Source coordinate that produced this pixel, written alongside the picture so
// later passes can read the source-space masks at the right place. Alpha is 1
// when the pixel is inside the cropped image and 0 on the letterbox.
layout(location = 1) out vec4 outMap;
uniform sampler2D u_src; uniform sampler2D u_src;
uniform sampler2D u_curve; uniform sampler2D u_curve;
@@ -77,11 +81,18 @@ uniform vec2 u_healSize[24];
uniform sampler2D u_masks; // layers 1-4 uniform sampler2D u_masks; // layers 1-4
uniform sampler2D u_masks2; // layers 5-8 uniform sampler2D u_masks2; // layers 5-8
uniform int u_localCount; uniform int u_localCount;
// Local mask overlay: index of the layer tinted over the picture, -1 = off.
uniform float u_maskView;
// Opacity of that tint, 0-1.
uniform float u_maskStrength;
uniform vec4 u_localAdj[8]; // exposure, contrast, temp, tint uniform vec4 u_localAdj[8]; // exposure, contrast, temp, tint
uniform vec4 u_localAdj2[8]; // saturation, highlights, shadows, unused uniform vec4 u_localAdj2[8]; // saturation, highlights, shadows, unused
uniform vec4 u_localAdj3[8]; // whites, blacks, vibrance, hue degrees uniform vec4 u_localAdj3[8]; // whites, blacks, vibrance, hue degrees
uniform vec4 u_localRange[8]; // lumaMin, lumaMax, hue, hueRange uniform vec4 u_localRange[8]; // lumaMin, lumaMax, hue, hueRange
uniform vec4 u_localRange2[8]; // satMin, enabled, unused, unused uniform vec4 u_localRange2[8]; // satMin, enabled, unused, unused
// 256×8 LUT, one row per layer: the per-mask tone curve, applied to the masked
// pixels only so a burnt sky can hold its own contrast independently.
uniform sampler2D u_localCurves;
// Lens/perspective correction: distortion, vertical, horizontal, rotation. // Lens/perspective correction: distortion, vertical, horizontal, rotation.
uniform vec4 u_geom; uniform vec4 u_geom;
@@ -275,6 +286,7 @@ vec2 warpGeometry(vec2 s){
} }
void main(){ void main(){
outMap = vec4(0.0);
// The eyedropper renders one pixel at an arbitrary point, so the mapping below // The eyedropper renders one pixel at an arbitrary point, so the mapping below
// takes its coordinate from the uniform instead of the fragment position. // takes its coordinate from the uniform instead of the fragment position.
vec2 outUv = u_pick > 0.5 ? u_pickUv : v_uv; vec2 outUv = u_pick > 0.5 ? u_pickUv : v_uv;
@@ -317,6 +329,9 @@ void main(){
: lensQ; : lensQ;
} }
vec2 uv = lensCoord; vec2 uv = lensCoord;
// Hand the source coordinate to the passes that need source-space data (the
// local detail masks) instead of making them repeat this warp.
outMap = vec4(uv, 0.0, 1.0);
vec3 src; vec3 src;
if (showLens && (u_lensFlags & 2) != 0) { if (showLens && (u_lensFlags & 2) != 0) {
vec4 t = lensSample(u_lensTca, u_lensTcaSize, lensCoord); vec4 t = lensSample(u_lensTca, u_lensTcaSize, lensCoord);
@@ -330,10 +345,6 @@ void main(){
? sampleBicubic(u_src, uv, u_srcSize) ? sampleBicubic(u_src, uv, u_srcSize)
: textureLod(u_src, uv, u_srcLod).rgb; : textureLod(u_src, uv, u_srcLod).rgb;
} }
if (showLens && (u_lensFlags & 4) != 0) {
src *= lensSample(u_lensVig, u_lensVigSize, lensQ).rgb;
}
// Camera-native proxies are converted once, before the source is read any // Camera-native proxies are converted once, before the source is read any
// further: the frame, the healed patches and the eyedropper all work on the // further: the frame, the healed patches and the eyedropper all work on the
// same sRGB values whatever the camera matrix was. // same sRGB values whatever the camera matrix was.
@@ -366,9 +377,15 @@ void main(){
} }
} }
// Eyedropper: hand back the untouched source colour at the sampled point. // Eyedropper: hand back the source colour at the sampled point, with the lens
// gain applied the same way the frame is, so a corner sample reads the
// brightness on screen.
if (u_pick > 0.5) { if (u_pick > 0.5) {
outColor = vec4(src, 1.0); vec3 picked = toLinear(clamp(src, 0.0, 1.0));
if (showLens && (u_lensFlags & 4) != 0) {
picked *= lensSample(u_lensVig, u_lensVigSize, lensQ).rgb;
}
outColor = vec4(clamp(toSRGB(picked), 0.0, 1.0), 1.0);
return; return;
} }
@@ -382,6 +399,13 @@ void main(){
vec3 col = toLinear(clamp(src, 0.0, 1.0)); vec3 col = toLinear(clamp(src, 0.0, 1.0));
// Lens vignetting is a flat-field gain from Lensfun's linear-light
// transmission model, so it belongs after the sRGB decode. Multiplying it into
// the encoded values brightened the corners far more than the lens lost.
if (showLens && (u_lensFlags & 4) != 0) {
col *= lensSample(u_lensVig, u_lensVigSize, lensQ).rgb;
}
// White balance gains, solved on the CPU: either the relative Temp offset or // White balance gains, solved on the CPU: either the relative Temp offset or
// the absolute Kelvin control, both normalised so exposure is unchanged. // the absolute Kelvin control, both normalised so exposure is unchanged.
col *= u_wbGain; col *= u_wbGain;
@@ -543,16 +567,34 @@ void main(){
1.0, 1.0,
adj3.z adj3.z
); );
// Per-mask curve, looked up in this layer's LUT row before the mask blend.
float curveRow = (float(i) + 0.5) / 8.0;
local = vec3(
texture(u_localCurves, vec2(clamp(local.r, 0.0, 1.0), curveRow)).r,
texture(u_localCurves, vec2(clamp(local.g, 0.0, 1.0), curveRow)).g,
texture(u_localCurves, vec2(clamp(local.b, 0.0, 1.0), curveRow)).b
);
srgb = mix(srgb, clamp(local, 0.0, 1.0), m); srgb = mix(srgb, clamp(local, 0.0, 1.0), m);
} }
} }
// Alpha carries the *source* clipping state to the finish pass, so the // Mask overlay: tint the baked shape, not a redrawn brush band. Reading the
// warning reflects the pixels the sensor/proxy had, not the graded result. // same source uv the adjustments use keeps the preview on the picture through
float clipFlag = 0.0; // crops, straightening, zoom and lens correction, and it shows the feather
if (max(src.r, max(src.g, src.b)) >= 0.996) clipFlag += 0.5; // exactly as the mask stores it.
if (min(src.r, min(src.g, src.b)) <= 0.004) clipFlag += 0.25; if (u_maskView >= 0.0 && u_localCount > 0) {
outColor = vec4(clamp(srgb, 0.0, 1.0), clipFlag); int mv = int(u_maskView + 0.5);
int mk = mv < 4 ? mv : mv - 4;
vec4 mtex = mv < 4 ? texture(u_masks, uv) : texture(u_masks2, uv);
float cov = mk == 0 ? mtex.r : mk == 1 ? mtex.g : mk == 2 ? mtex.b : mtex.a;
srgb = mix(
srgb,
vec3(0.98, 0.72, 0.35),
clamp(cov, 0.0, 1.0) * clamp(u_maskStrength, 0.0, 1.0)
);
}
outColor = vec4(clamp(srgb, 0.0, 1.0), 1.0);
}`; }`;
const BLUR_FRAG = `#version 300 es const BLUR_FRAG = `#version 300 es
@@ -581,6 +623,8 @@ uniform sampler2D u_blurBig;
// grade pass. Amounts are added to the global sliders per pixel. // grade pass. Amounts are added to the global sliders per pixel.
uniform sampler2D u_masks; uniform sampler2D u_masks;
uniform sampler2D u_masks2; uniform sampler2D u_masks2;
// Source coordinate of this output pixel, from the grade pass.
uniform sampler2D u_maskUv;
uniform int u_localCount; uniform int u_localCount;
uniform vec4 u_localDetail[8]; // texture, clarity, dehaze, sharpen uniform vec4 u_localDetail[8]; // texture, clarity, dehaze, sharpen
uniform vec4 u_localModes[8]; // x = add / subtract / intersect uniform vec4 u_localModes[8]; // x = add / subtract / intersect
@@ -665,9 +709,14 @@ void main(){
float localClarity = 0.0; float localClarity = 0.0;
float localDehaze = 0.0; float localDehaze = 0.0;
float localSharpen = 0.0; float localSharpen = 0.0;
if (u_localCount > 0) { // The masks are baked in source space, so read them through the source
vec4 maskA = texture(u_masks, v_uv); // coordinate the grade pass wrote for this pixel: crop, straightening, zoom
vec4 maskB = texture(u_masks2, v_uv); // and lens correction all move the mask along with the picture.
vec4 maskMap = texture(u_maskUv, v_uv);
if (u_localCount > 0 && maskMap.a > 0.5) {
vec2 maskUv = maskMap.rg;
vec4 maskA = texture(u_masks, maskUv);
vec4 maskB = texture(u_masks2, maskUv);
float prevMask = 1.0; float prevMask = 1.0;
for (int i = 0; i < 8; i++) { for (int i = 0; i < 8; i++) {
if (i >= u_localCount) break; if (i >= u_localCount) break;
@@ -856,16 +905,42 @@ void main(){
vec3 finalCol = clamp(col, 0.0, 1.0); vec3 finalCol = clamp(col, 0.0, 1.0);
// Clipping overlay: which channels have run out of headroom. Red/green/blue // Clipping overlay: which channels have run out of headroom. Red/green/blue
// mean one channel clipped, yellow means two, white means all three — the // mean one channel clipped, yellow means two, white means all three — the
// same reading Aperture's exposure warnings gave while you dragged. // same reading Aperture's exposure warnings gave while you dragged. It reads
// The grade pass wrote the untouched source's clipping state into alpha: // the finished frame rather than the source, so holding Ctrl while moving
// 0.25 shadow, 0.50 highlight, 0.75 both. Warning about the source means it // Exposure or Recovery shows the warnings appear and clear as you go.
// still tells the truth after a curve or a shadow lift.
float srcClip = texture(u_graded, v_uv).a;
if (u_clip > 1.5) { if (u_clip > 1.5) {
if (srcClip >= 0.2 && srcClip < 0.5) finalCol = vec3(0.15, 0.4, 1.0); // Shadow clipping: which channels have fallen to the bottom of the range.
else if (srcClip >= 0.7) finalCol = vec3(0.15, 0.4, 1.0); // The palette mirrors the highlight one, so red/green/blue mean one channel
// and the secondary colours name the pair that ran out of shadow detail:
// yellow red+green, magenta red+blue, cyan green+blue.
vec3 k = 1.0 - step(vec3(0.021), finalCol);
float n = k.r + k.g + k.b;
if (n > 0.5) {
vec3 mark = vec3(1.0);
if (n < 2.5) {
if (n > 1.5) {
if (k.r > 0.5 && k.g > 0.5) mark = vec3(1.0, 0.9, 0.1);
else if (k.r > 0.5) mark = vec3(1.0, 0.15, 0.85);
else mark = vec3(0.1, 0.85, 1.0);
} else if (k.r > 0.5) mark = vec3(1.0, 0.12, 0.12);
else if (k.g > 0.5) mark = vec3(0.1, 1.0, 0.2);
else mark = vec3(0.15, 0.4, 1.0);
}
finalCol = mark;
}
} else if (u_clip > 0.5) { } else if (u_clip > 0.5) {
if (srcClip >= 0.5) finalCol = vec3(1.0); vec3 k = step(0.985, finalCol);
float n = k.r + k.g + k.b;
if (n > 0.5) {
vec3 mark = vec3(1.0);
if (n < 2.5) {
if (n > 1.5) mark = vec3(1.0, 0.9, 0.1);
else if (k.r > 0.5) mark = vec3(1.0, 0.12, 0.12);
else if (k.g > 0.5) mark = vec3(0.1, 1.0, 0.2);
else mark = vec3(0.15, 0.4, 1.0);
}
finalCol = mark;
}
} }
outColor = vec4(finalCol, 1.0); outColor = vec4(finalCol, 1.0);
}`; }`;
@@ -884,6 +959,8 @@ interface Target {
h: number; h: number;
/** Half-float pixels keep subtle gradients from banding between passes. */ /** Half-float pixels keep subtle gradients from banding between passes. */
float: boolean; float: boolean;
/** Second colour attachment, e.g. the source-coordinate map of the grade. */
aux?: WebGLTexture;
} }
function makeHistogram(): Histogram { function makeHistogram(): Histogram {
@@ -1116,6 +1193,28 @@ export function buildCurveLUT(edits: Edits): Uint8Array {
return data; return data;
} }
/**
* Per-mask curve LUT: 256 samples per row, eight rows (one per layer), RGB in
* the colour channels. The running maximum keeps the curve monotonic for the
* same reason the global one does — a folded mask curve posterises the area.
*/
export function buildLocalCurveLUT(layers: { curve?: CurvePoint[] }[]): Uint8Array {
const data = new Uint8Array(256 * 8 * 4);
for (let row = 0; row < 8; row++) {
const points = layers[row]?.curve;
const sampler = points && points.length >= 2 ? buildSampler(points) : (x: number) => x;
let previous = 0;
for (let i = 0; i < 256; i++) {
const value = Math.max(previous, Math.min(1, sampler(i / 255)));
previous = value;
const o = (row * 256 + i) * 4;
data[o] = data[o + 1] = data[o + 2] = Math.round(value * 255);
data[o + 3] = 255;
}
}
return data;
}
class Prog { class Prog {
private cache = new Map<string, WebGLUniformLocation | null>(); private cache = new Map<string, WebGLUniformLocation | null>();
constructor(private gl: WebGL2RenderingContext, public program: WebGLProgram) {} constructor(private gl: WebGL2RenderingContext, public program: WebGLProgram) {}
@@ -1256,6 +1355,8 @@ export class Renderer {
private denMix = 0; private denMix = 0;
private denBitmap: ImageBitmap | null = null; private denBitmap: ImageBitmap | null = null;
private curveTex: WebGLTexture; private curveTex: WebGLTexture;
/** 256×8 LUT of per-mask curves; created on first use. */
private localCurveTex: WebGLTexture | null = null;
private targets: { graded?: Target; smallA?: Target; smallB?: Target; bigA?: Target; bigB?: Target } = {}; private targets: { graded?: Target; smallA?: Target; smallB?: Target; bigA?: Target; bigB?: Target } = {};
private histTarget: Target | null = null; private histTarget: Target | null = null;
private pickTarget: Target | null = null; private pickTarget: Target | null = null;
@@ -1437,6 +1538,9 @@ export class Renderer {
this.srcW = bitmap.width; this.srcW = bitmap.width;
this.srcH = bitmap.height; this.srcH = bitmap.height;
gl.bindTexture(gl.TEXTURE_2D, this.srcTex); gl.bindTexture(gl.TEXTURE_2D, this.srcTex);
// The flag is honoured for the ArrayBufferView sidecar but ignored for the
// ImageBitmap proxy, so the sidecar arrives already in the proxy's row order
// and must be uploaded unflipped.
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
const usable = hdr && hdr.width === bitmap.width && hdr.height === bitmap.height ? hdr : null; const usable = hdr && hdr.width === bitmap.width && hdr.height === bitmap.height ? hdr : null;
let half = false; let half = false;
@@ -1575,36 +1679,48 @@ export class Renderer {
this.proofLutOn = 1; this.proofLutOn = 1;
} }
private makeTarget(w: number, h: number, float = this.floatTargets): Target { private makeTarget(w: number, h: number, float = this.floatTargets, aux = false): Target {
const gl = this.gl; const gl = this.gl;
const tex = gl.createTexture(); const tex = gl.createTexture();
const fbo = gl.createFramebuffer(); const fbo = gl.createFramebuffer();
if (!tex || !fbo) throw new Error('Unable to allocate render target'); if (!tex || !fbo) throw new Error('Unable to allocate render target');
gl.bindTexture(gl.TEXTURE_2D, tex); const alloc = (texture: WebGLTexture) => {
if (float) { gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null); if (float) {
} else { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } else {
} gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); }
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
};
alloc(tex);
const auxTex = aux ? gl.createTexture() : null;
if (aux && !auxTex) throw new Error('Unable to allocate render target');
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
if (auxTex) {
alloc(auxTex);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.TEXTURE_2D, auxTex, 0);
gl.drawBuffers([gl.COLOR_ATTACHMENT0, gl.COLOR_ATTACHMENT1]);
}
if (float && gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) { if (float && gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.deleteTexture(tex); gl.deleteTexture(tex);
if (auxTex) gl.deleteTexture(auxTex);
gl.deleteFramebuffer(fbo); gl.deleteFramebuffer(fbo);
throw new Error('Half-float render targets are unavailable'); throw new Error('Half-float render targets are unavailable');
} }
gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null);
return { tex, fbo, w, h, float }; return { tex, fbo, w, h, float, aux: auxTex ?? undefined };
} }
private freeTarget(target?: Target) { private freeTarget(target?: Target) {
if (!target) return; if (!target) return;
this.gl.deleteTexture(target.tex); this.gl.deleteTexture(target.tex);
if (target.aux) this.gl.deleteTexture(target.aux);
this.gl.deleteFramebuffer(target.fbo); this.gl.deleteFramebuffer(target.fbo);
} }
@@ -1627,13 +1743,14 @@ export class Renderer {
for (const useFloat of modes) { for (const useFloat of modes) {
const made: Target[] = []; const made: Target[] = [];
try { try {
const mk = (mw: number, mh: number) => { const mk = (mw: number, mh: number, extra = false) => {
const target = this.makeTarget(mw, mh, useFloat); const target = this.makeTarget(mw, mh, useFloat, extra);
made.push(target); made.push(target);
return target; return target;
}; };
this.targets = { this.targets = {
graded: mk(w, h), // The grade also writes the source-coordinate map for the finish pass.
graded: mk(w, h, true),
smallA: mk(sw, sh), smallA: mk(sw, sh),
smallB: mk(sw, sh), smallB: mk(sw, sh),
bigA: mk(bw, bh), bigA: mk(bw, bh),
@@ -1682,6 +1799,26 @@ export class Renderer {
return layers.length; return layers.length;
} }
/** One 256×8 texture carries every layer's mask curve, so no extra units. */
private uploadLocalCurves(layers: LocalLayer[]): WebGLTexture {
const gl = this.gl;
let tex = this.localCurveTex;
if (!tex) {
tex = gl.createTexture();
this.localCurveTex = tex;
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
const data = buildLocalCurveLUT(layers);
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 256, 8, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
return tex;
}
private uploadLensMaps() { private uploadLensMaps() {
const gl = this.gl; const gl = this.gl;
const correction = this.lensCorrection; const correction = this.lensCorrection;
@@ -1705,6 +1842,8 @@ export class Renderer {
bounds: { w: number; h: number }, bounds: { w: number; h: number },
upscale: boolean, upscale: boolean,
srcLod = 0, srcLod = 0,
maskView = -1,
maskStrength = 0.5,
) { ) {
const g = this.grade; const g = this.grade;
this.gl.useProgram(g.program); this.gl.useProgram(g.program);
@@ -1786,9 +1925,14 @@ export class Renderer {
g.f('u_lensScale', lens?.scale ?? 1); g.f('u_lensScale', lens?.scale ?? 1);
g.f('u_lensSplit', this.lensSplit); g.f('u_lensSplit', this.lensSplit);
const curveTex = this.uploadLocalCurves(edits.local ?? []);
g.tex('u_masks', this.maskTex, 2); g.tex('u_masks', this.maskTex, 2);
g.tex('u_masks2', this.maskTex2, 7); g.tex('u_masks2', this.maskTex2, 7);
g.tex('u_localCurves', curveTex, 8);
g.i('u_localCount', localCount); g.i('u_localCount', localCount);
// Only tint a layer that this edit actually has; -1 leaves the picture alone.
g.f('u_maskView', maskView >= 0 && maskView < localCount ? maskView : -1);
g.f('u_maskStrength', clamp01(maskStrength));
for (let i = 0; i < localCount; i++) { for (let i = 0; i < localCount; i++) {
const layer = edits.local[i]; const layer = edits.local[i];
g.v4i('u_localAdj', i, layer.adjust.exposure, layer.adjust.contrast, layer.adjust.temp, layer.adjust.tint); g.v4i('u_localAdj', i, layer.adjust.exposure, layer.adjust.contrast, layer.adjust.temp, layer.adjust.tint);
@@ -1831,6 +1975,7 @@ export class Renderer {
// shows the Optics split. // shows the Optics split.
const split = this.lensSplit; const split = this.lensSplit;
this.lensSplit = -1; this.lensSplit = -1;
// No mask overlay here: the eyedropper must read the photo, not the tint.
this.bindGrade(edits, crop, valid, bounds, !!opts.upscale); this.bindGrade(edits, crop, valid, bounds, !!opts.upscale);
this.lensSplit = split; this.lensSplit = split;
this.grade.f('u_pick', 1); this.grade.f('u_pick', 1);
@@ -1872,6 +2017,10 @@ export class Renderer {
clipPreview?: boolean; clipPreview?: boolean;
/** paint blown highlights or crushed shadows outside the range */ /** paint blown highlights or crushed shadows outside the range */
clipping?: 'highlights' | 'shadows'; clipping?: 'highlights' | 'shadows';
/** tint this local layer's baked mask over the picture; -1 or omitted = off */
maskView?: number;
/** opacity of the mask tint, 0-1 (default 0.5) */
maskStrength?: number;
/** return the finished image as linear-space floats instead of drawing the canvas */ /** return the finished image as linear-space floats instead of drawing the canvas */
floatOut?: boolean; floatOut?: boolean;
}, },
@@ -1916,7 +2065,16 @@ export class Renderer {
const cropPxW = Math.max(1, bounds.w * crop.w); const cropPxW = Math.max(1, bounds.w * crop.w);
const cropPxH = Math.max(1, bounds.h * crop.h); const cropPxH = Math.max(1, bounds.h * crop.h);
const srcLod = Math.max(0, Math.log2(Math.max(cropPxW / w, cropPxH / h))); const srcLod = Math.max(0, Math.log2(Math.max(cropPxW / w, cropPxH / h)));
this.bindGrade(edits, crop, valid, bounds, !!opts.upscale, srcLod); this.bindGrade(
edits,
crop,
valid,
bounds,
!!opts.upscale,
srcLod,
opts.maskView ?? -1,
opts.maskStrength ?? 0.5,
);
this.drawQuad(); this.drawQuad();
// Passes 2-3: small blur (detail) and large blur (clarity) from the graded image // Passes 2-3: small blur (detail) and large blur (clarity) from the graded image
@@ -2000,6 +2158,9 @@ export class Renderer {
this.finish.f('u_detailScale', detailScale); this.finish.f('u_detailScale', detailScale);
this.finish.tex('u_masks', this.maskTex, 3); this.finish.tex('u_masks', this.maskTex, 3);
this.finish.tex('u_masks2', this.maskTex2, 4); this.finish.tex('u_masks2', this.maskTex2, 4);
// Source coordinate per pixel, written by the grade pass. The masks are
// source-space, so local detail reads them through this instead of v_uv.
if (t.graded!.aux) this.finish.tex('u_maskUv', t.graded!.aux, 5);
const innerLayers = (edits.local ?? []).slice(0, MAX_LOCAL_LAYERS); const innerLayers = (edits.local ?? []).slice(0, MAX_LOCAL_LAYERS);
this.finish.i('u_localCount', innerLayers.length); this.finish.i('u_localCount', innerLayers.length);
for (let i = 0; i < innerLayers.length; i++) { for (let i = 0; i < innerLayers.length; i++) {
@@ -2076,6 +2237,7 @@ export class Renderer {
const data = new Float32Array(w * h * 4); const data = new Float32Array(w * h * 4);
gl.readPixels(0, 0, w, h, gl.RGBA, gl.FLOAT, data); gl.readPixels(0, 0, w, h, gl.RGBA, gl.FLOAT, data);
gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null);
this.checkDrawError();
return data; return data;
} }
@@ -2103,9 +2265,35 @@ export class Renderer {
} }
} }
this.checkDrawError();
return null; return null;
} }
/**
* A rejected draw leaves the canvas untouched, which the editor shows as a
* black photo with nothing to explain it. Poll the error queue once per
* frame, after the draws are queued, and let the caller report a real
* failure instead of painting black.
*/
private checkDrawError() {
const gl = this.gl;
const err = gl.getError();
if (err === gl.NO_ERROR) return;
const name =
err === gl.INVALID_OPERATION
? 'INVALID_OPERATION'
: err === gl.INVALID_VALUE
? 'INVALID_VALUE'
: err === gl.INVALID_FRAMEBUFFER_OPERATION
? 'INVALID_FRAMEBUFFER_OPERATION'
: err === gl.OUT_OF_MEMORY
? 'OUT_OF_MEMORY'
: `0x${err.toString(16)}`;
throw new Error(
`The photo could not be drawn on this GPU (WebGL ${name}). Reload the page, and if it keeps happening update your graphics driver.`,
);
}
/** Wait for queued GPU work, e.g. before the canvas is encoded to a file. */ /** Wait for queued GPU work, e.g. before the canvas is encoded to a file. */
finishGpu() { finishGpu() {
this.gl.finish(); this.gl.finish();
+7
View File
@@ -0,0 +1,7 @@
/**
* Versions shown in the About panel. APP_VERSION mirrors package.json; the
* guide values are bumped when docs/user-guide/guide.html is republished.
*/
export const APP_VERSION = '0.5.1';
export const GUIDE_VERSION = '0.5';
export const GUIDE_UPDATED = 'November 2026';
+6 -2
View File
@@ -6,6 +6,8 @@ export interface Health {
version: string; version: string;
needsSetup: boolean; needsSetup: boolean;
registrationOpen: boolean; registrationOpen: boolean;
/** Single-user desktop mode (LUMINARY_LOCAL=1): no accounts to manage. */
local?: boolean;
photos: number; photos: number;
bytes: number; bytes: number;
storage?: { root: string; custom: boolean }; storage?: { root: string; custom: boolean };
@@ -21,13 +23,15 @@ export interface SessionUser {
export interface UploadResult { export interface UploadResult {
raw: boolean; raw: boolean;
engine?: 'libraw' | 'embedded'; engine?: 'libraw' | 'embedded' | 'sharp';
width?: number; width?: number;
height?: number; height?: number;
mime?: string; mime?: string;
size?: number; size?: number;
previewUrl?: string; previewUrl?: string;
thumbUrl?: string; thumbUrl?: string;
/** Size of the JPEG proxy the server wrote, when it decoded this file. */
previewBytes?: number;
note?: string | null; note?: string | null;
} }
@@ -151,7 +155,7 @@ export function reprocessRawPhoto(
): Promise<{ ): Promise<{
width: number; width: number;
height: number; height: number;
engine?: 'libraw' | 'embedded'; engine?: 'libraw' | 'embedded' | 'sharp';
note?: string | null; note?: string | null;
previewVersion?: number; previewVersion?: number;
previewUrl?: string; previewUrl?: string;
+54
View File
@@ -68,6 +68,60 @@ describe('segmentation', () => {
expect(background[32 * width + 32]).toBe(0); expect(background[32 * width + 32]).toBe(0);
}); });
it('leaves a saturated object that runs off the frame out of the subject', () => {
// Grass around a red mat that spans the whole bottom edge, with the person
// sitting in the middle: the mat touches three borders, the person none.
const width = 96;
const height = 64;
const data = new Uint8Array(width * height * 4);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const o = (y * width + x) * 4;
const mat = y > height * 0.6;
const person = x > width * 0.42 && x < width * 0.58 && y > height * 0.35 && y < height * 0.68;
if (person) {
data[o] = 40;
data[o + 1] = 70;
data[o + 2] = 180;
} else if (mat) {
data[o] = 200;
data[o + 1] = 30;
data[o + 2] = 40;
} else {
data[o] = 90;
data[o + 1] = 130;
data[o + 2] = 70;
}
data[o + 3] = 255;
}
}
const mask = segmentMask(data, width, height, 'subject');
const at = (x: number, y: number) => mask[Math.round(y) * width + Math.round(x)];
expect(at(width * 0.5, height * 0.5)).toBe(255);
expect(at(4, height * 0.9)).toBe(0);
expect(at(width * 0.5, height * 0.95)).toBe(0);
});
it('does not swallow a dark scene with no clear subject', () => {
const width = 64;
const height = 64;
const data = new Uint8Array(width * height * 4);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const o = (y * width + x) * 4;
const streak = y > 30 && y < 33 && x > 8 && x < 52;
data[o] = streak ? 220 : 18;
data[o + 1] = streak ? 90 : 22;
data[o + 2] = streak ? 40 : 34;
data[o + 3] = 255;
}
}
const mask = segmentMask(data, width, height, 'subject');
let inside = 0;
for (const value of mask) if (value) inside++;
expect(inside / mask.length).toBeLessThan(0.6);
});
it('splits a bimodal score map', () => { it('splits a bimodal score map', () => {
const values = new Float32Array(1000); const values = new Float32Array(1000);
for (let i = 0; i < 500; i++) values[i] = 0.1; for (let i = 0; i < 500; i++) values[i] = 0.1;
+24 -2
View File
@@ -1,7 +1,8 @@
import type { EventRecord, PhotoRecord } from '../types'; import type { EventRecord, PhotoRecord } from '../types';
import { withoutLensVignetting } from './edits';
const DB_NAME = 'lumenroom'; const DB_NAME = 'lumenroom';
const DB_VERSION = 1; const DB_VERSION = 2;
let dbPromise: Promise<IDBDatabase> | null = null; let dbPromise: Promise<IDBDatabase> | null = null;
@@ -9,7 +10,7 @@ export function openDB(): Promise<IDBDatabase> {
if (dbPromise) return dbPromise; if (dbPromise) return dbPromise;
dbPromise = new Promise((resolve, reject) => { dbPromise = new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION); const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = () => { req.onupgradeneeded = (event) => {
const db = req.result; const db = req.result;
if (!db.objectStoreNames.contains('photos')) { if (!db.objectStoreNames.contains('photos')) {
const store = db.createObjectStore('photos', { keyPath: 'id' }); const store = db.createObjectStore('photos', { keyPath: 'id' });
@@ -18,6 +19,11 @@ export function openDB(): Promise<IDBDatabase> {
if (!db.objectStoreNames.contains('assets')) db.createObjectStore('assets'); if (!db.objectStoreNames.contains('assets')) db.createObjectStore('assets');
if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { keyPath: 'id' }); if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { keyPath: 'id' });
if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv'); if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv');
// v2: applying a lens profile used to enable its vignetting correction,
// and the corner gain over-exposed the edges. Clear that flag once, here,
// instead of on every load, so a profile the user enables afterwards stays
// enabled.
if (event.oldVersion < 2) clearStoredLensVignetting(req.transaction);
}; };
req.onsuccess = () => resolve(req.result); req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error('Unable to open database')); req.onerror = () => reject(req.error ?? new Error('Unable to open database'));
@@ -25,6 +31,22 @@ export function openDB(): Promise<IDBDatabase> {
return dbPromise; return dbPromise;
} }
/**
* Walks the photo store inside the version-change transaction and clears any
* stored lens vignetting flag. Runs once, on the database upgrade.
*/
function clearStoredLensVignetting(tx: IDBTransaction | null) {
if (!tx) return;
const cursorRequest = tx.objectStore('photos').openCursor();
cursorRequest.onsuccess = () => {
const cursor = cursorRequest.result;
if (!cursor) return;
const cleared = withoutLensVignetting(cursor.value as PhotoRecord);
if (cleared) cursor.update(cleared);
cursor.continue();
};
}
function wrap<T>(request: IDBRequest<T>): Promise<T> { function wrap<T>(request: IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result); request.onsuccess = () => resolve(request.result);
+123 -27
View File
@@ -6,6 +6,7 @@ import type {
Edits, Edits,
Flag, Flag,
HealSpot, HealSpot,
LocalComponent,
LocalLayer, LocalLayer,
LocalMaskKind, LocalMaskKind,
LocalPoint, LocalPoint,
@@ -99,6 +100,9 @@ export const MAX_HEAL_SPOTS = 24;
/** Eight masks are packed into two RGBA textures. */ /** Eight masks are packed into two RGBA textures. */
export const MAX_LOCAL_LAYERS = 8; export const MAX_LOCAL_LAYERS = 8;
/** More shapes than this in one group stops being quicker than a second layer. */
export const MAX_LOCAL_COMPONENTS = 8;
export function defaultLocalAdjust(): LocalLayer['adjust'] { export function defaultLocalAdjust(): LocalLayer['adjust'] {
return { return {
exposure: 0, exposure: 0,
@@ -119,10 +123,9 @@ export function defaultLocalAdjust(): LocalLayer['adjust'] {
}; };
} }
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer { export function defaultLocalComponent(kind: LocalMaskKind): LocalComponent {
return { return {
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`, id: `shape-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
name: `Local ${index + 1}`,
kind, kind,
mode: 'add', mode: 'add',
inverted: false, inverted: false,
@@ -130,7 +133,17 @@ export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLaye
brush: { strokes: [] }, brush: { strokes: [] },
linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 }, linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 },
radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 }, radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 },
};
}
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
return {
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
name: `Local ${index + 1}`,
mode: 'add',
components: [defaultLocalComponent(kind)],
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 }, range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
curve: identityCurve(),
adjust: defaultLocalAdjust(), adjust: defaultLocalAdjust(),
}; };
} }
@@ -269,40 +282,84 @@ function rasterMask(input: unknown): RasterMask | undefined {
return { data: raw.data, width, height }; return { data: raw.data, width, height };
} }
/**
* Per-mask curve points. Masks saved before the field existed have none, and
* they must come back as the identity rather than leaving the shader LUT row
* undefined.
*/
function localCurve(input: unknown): CurvePoint[] {
if (!Array.isArray(input)) return identityCurve();
const points: CurvePoint[] = [];
for (const raw of input.slice(0, 16)) {
if (!raw || typeof raw !== 'object') continue;
const point = raw as Partial<CurvePoint>;
points.push({ x: clamp01(num(point.x, 0, 0, 1)), y: clamp01(num(point.y, 0, 0, 1)) });
}
points.sort((a, b) => a.x - b.x);
return points.length >= 2 ? points : identityCurve();
}
/**
* One shape from stored edits. It also reads the pre-group flat layout, where
* the layer itself carried kind/feather/brush/...: that is how every mask saved
* before mask groups existed migrates into `components[0]`.
*/
function localComponent(input: unknown, index: number): LocalComponent | null {
if (!input || typeof input !== 'object') return null;
const shape = input as Partial<LocalComponent> & { kind?: unknown };
const kind: LocalMaskKind =
shape.kind === 'linear' || shape.kind === 'radial' || shape.kind === 'raster' ? shape.kind : 'brush';
const linear = (shape.linear ?? {}) as Partial<LocalComponent['linear']>;
const radial = (shape.radial ?? {}) as Partial<LocalComponent['radial']>;
const raster = kind === 'raster' ? rasterMask(shape.raster) : undefined;
// A raster shape without its coverage would composite an empty hole, so it
// falls back to a brush shape that can at least be painted over.
const resolved: LocalMaskKind = kind === 'raster' && !raster ? 'brush' : kind;
return {
id: typeof shape.id === 'string' && shape.id ? shape.id.slice(0, 60) : `shape-${index}`,
kind: resolved,
mode: shape.mode === 'subtract' || shape.mode === 'intersect' ? shape.mode : 'add',
inverted: !!shape.inverted,
feather: num(shape.feather, 50, 0, 100),
brush: { strokes: localStrokes(shape.brush?.strokes) },
raster: resolved === 'raster' ? raster : undefined,
linear: {
x1: clamp01(num(linear.x1, 0.5, 0, 1)),
y1: clamp01(num(linear.y1, 0.2, 0, 1)),
x2: clamp01(num(linear.x2, 0.5, 0, 1)),
y2: clamp01(num(linear.y2, 0.8, 0, 1)),
},
radial: {
cx: clamp01(num(radial.cx, 0.5, 0, 1)),
cy: clamp01(num(radial.cy, 0.5, 0, 1)),
rx: num(radial.rx, 0.25, 0.01, 1.5),
ry: num(radial.ry, 0.3, 0.01, 1.5),
},
};
}
function localLayers(input: unknown): LocalLayer[] { function localLayers(input: unknown): LocalLayer[] {
if (!Array.isArray(input)) return []; if (!Array.isArray(input)) return [];
const out: LocalLayer[] = []; const out: LocalLayer[] = [];
for (const raw of input.slice(0, MAX_LOCAL_LAYERS)) { for (const raw of input.slice(0, MAX_LOCAL_LAYERS)) {
if (!raw || typeof raw !== 'object') continue; if (!raw || typeof raw !== 'object') continue;
const layer = raw as Partial<LocalLayer>; const layer = raw as Partial<LocalLayer>;
const kind: LocalMaskKind =
layer.kind === 'linear' || layer.kind === 'radial' || layer.kind === 'raster' ? layer.kind : 'brush';
const adjust = (layer.adjust ?? {}) as Partial<LocalLayer['adjust']>; const adjust = (layer.adjust ?? {}) as Partial<LocalLayer['adjust']>;
const range = (layer.range ?? {}) as Partial<LocalLayer['range']>; const range = (layer.range ?? {}) as Partial<LocalLayer['range']>;
const linear = (layer.linear ?? {}) as Partial<LocalLayer['linear']>; const stored = Array.isArray(layer.components) && layer.components.length ? layer.components : [layer];
const radial = (layer.radial ?? {}) as Partial<LocalLayer['radial']>; const components: LocalComponent[] = [];
for (const entry of stored.slice(0, MAX_LOCAL_COMPONENTS)) {
const component = localComponent(entry, components.length);
if (component) components.push(component);
}
// A layer must keep at least one shape, or it would adjust nothing with no
// way to tell why from the panel.
if (!components.length) components.push(defaultLocalComponent('brush'));
out.push({ out.push({
id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`, id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`,
name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`, name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`,
kind, mode: layer.mode === 'subtract' || layer.mode === 'intersect' ? layer.mode : 'add',
mode: components,
layer.mode === 'subtract' || layer.mode === 'intersect' ? layer.mode : 'add',
inverted: !!layer.inverted,
feather: num(layer.feather, 50, 0, 100),
brush: { strokes: localStrokes(layer.brush?.strokes) },
raster: kind === 'raster' ? rasterMask(layer.raster) : undefined,
linear: {
x1: clamp01(num(linear.x1, 0.5, 0, 1)),
y1: clamp01(num(linear.y1, 0.2, 0, 1)),
x2: clamp01(num(linear.x2, 0.5, 0, 1)),
y2: clamp01(num(linear.y2, 0.8, 0, 1)),
},
radial: {
cx: clamp01(num(radial.cx, 0.5, 0, 1)),
cy: clamp01(num(radial.cy, 0.5, 0, 1)),
rx: num(radial.rx, 0.25, 0.01, 1.5),
ry: num(radial.ry, 0.3, 0.01, 1.5),
},
range: { range: {
enabled: !!range.enabled, enabled: !!range.enabled,
lumaMin: num(range.lumaMin, 0, 0, 100), lumaMin: num(range.lumaMin, 0, 0, 100),
@@ -311,6 +368,7 @@ function localLayers(input: unknown): LocalLayer[] {
hueRange: num(range.hueRange, 180, 0, 180), hueRange: num(range.hueRange, 180, 0, 180),
satMin: num(range.satMin, 0, 0, 100), satMin: num(range.satMin, 0, 0, 100),
}, },
curve: localCurve(layer.curve),
adjust: { adjust: {
exposure: num(adjust.exposure, 0, -4, 4), exposure: num(adjust.exposure, 0, -4, 4),
contrast: num(adjust.contrast, 0, -100, 100), contrast: num(adjust.contrast, 0, -100, 100),
@@ -363,12 +421,46 @@ function lensProfile(input: unknown): LensProfile | undefined {
corrections: { corrections: {
distortion: corrections?.distortion !== false, distortion: corrections?.distortion !== false,
tca: corrections?.tca !== false, tca: corrections?.tca !== false,
vignetting: corrections?.vignetting !== false, // The vignetting map is a flat-field gain applied to the already
// tone-mapped proxy, which pushes the corners brighter than the frame
// centre and over-exposes the edges. It stays opt-in, so a profile saved
// without an explicit flag never brightens the corners.
vignetting: corrections?.vignetting === true,
}, },
distance: num(raw.distance, 1000, 0.1, 100000), distance: num(raw.distance, 1000, 0.1, 100000),
}; };
} }
/**
* One-off cleanup for records saved while applying a lens profile enabled all
* three corrections. The vignetting gain over-exposed the edges on the tone
* mapped proxy, so it is opt-in now; this clears the flag old edits stored,
* including snapshots and history, and returns null when nothing needed doing.
*/
export function withoutLensVignetting(photo: PhotoRecord): PhotoRecord | null {
let changed = false;
const strip = (edits: Edits): Edits => {
const lens = edits.lens;
if (!lens || lens.corrections.vignetting !== true) return edits;
changed = true;
return {
...edits,
lens: { ...lens, corrections: { ...lens.corrections, vignetting: false } },
};
};
const edits = strip(photo.edits);
const snapshots = photo.snapshots?.map((snapshot) => ({
...snapshot,
edits: strip(snapshot.edits),
}));
const history = photo.history?.map((entry) => ({ ...entry, edits: strip(entry.edits) }));
if (!changed) return null;
const next: PhotoRecord = { ...photo, edits };
if (snapshots) next.snapshots = snapshots;
if (history) next.history = history;
return next;
}
/** /**
* Keeps a stored camera profile usable: a profile with a missing or non-finite * Keeps a stored camera profile usable: a profile with a missing or non-finite
* matrix would black out the photo, so it is dropped instead. * matrix would black out the photo, so it is dropped instead.
@@ -560,6 +652,10 @@ export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): Ph
typeof input.previewVersion === 'number' && Number.isFinite(input.previewVersion) typeof input.previewVersion === 'number' && Number.isFinite(input.previewVersion)
? input.previewVersion ? input.previewVersion
: undefined, : undefined,
proxyBytes:
typeof input.proxyBytes === 'number' && Number.isFinite(input.proxyBytes)
? input.proxyBytes
: undefined,
proofAt: typeof input.proofAt === 'number' && Number.isFinite(input.proofAt) ? input.proofAt : undefined, proofAt: typeof input.proofAt === 'number' && Number.isFinite(input.proofAt) ? input.proofAt : undefined,
name: input.name ?? 'Untitled', name: input.name ?? 'Untitled',
width: input.width ?? 0, width: input.width ?? 0,
+5 -1
View File
@@ -7,7 +7,11 @@ const cache = new Map<string, ImageBitmap>();
/** Where to fetch the original (or raw proxy) when it is not cached on this device. */ /** Where to fetch the original (or raw proxy) when it is not cached on this device. */
export function remoteAssetUrl(photo: PhotoRecord): string { export function remoteAssetUrl(photo: PhotoRecord): string {
if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`; // Server-decoded formats (TIFF today) keep a browser-readable JPEG proxy just
// like raws; their original cannot be decoded by createImageBitmap.
if (photo.raw || photo.decode === 'sharp') {
return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`;
}
return `/api/photos/${encodeURIComponent(photo.id)}/original`; return `/api/photos/${encodeURIComponent(photo.id)}/original`;
} }
+12 -5
View File
@@ -4,7 +4,7 @@ import type { PhotoMeta, PhotoRecord } from '../types';
import { putAsset, putPhoto } from './db'; import { putAsset, putPhoto } from './db';
import { defaultEdits, normalizePhoto } from './edits'; import { defaultEdits, normalizePhoto } from './edits';
import { defaultForMeta, loadCameraLensDefaults, type CameraLensDefault } from './lensDefaults'; import { defaultForMeta, loadCameraLensDefaults, type CameraLensDefault } from './lensDefaults';
import { isRawFile, RAW_EXTENSIONS } from './raw'; import { isRawFile, isTiffFile, RAW_EXTENSIONS } from './raw';
export interface ImportProgress { export interface ImportProgress {
done: number; done: number;
@@ -85,7 +85,10 @@ function editsForImport(meta: PhotoMeta, defaults: CameraLensDefault[]) {
if (match) { if (match) {
edits.lens = { edits.lens = {
...match.profile, ...match.profile,
corrections: { ...match.profile.corrections }, // A saved default still carries whatever the profile had when it was
// stored. Applying it on import must not switch the vignetting gain back
// on and over-expose the corners, so that correction stays opt-in.
corrections: { ...match.profile.corrections, vignetting: false },
}; };
} }
return edits; return edits;
@@ -122,6 +125,8 @@ async function importRaw(
keywords: string[], keywords: string[],
cloud: CloudImport, cloud: CloudImport,
defaults: CameraLensDefault[], defaults: CameraLensDefault[],
/** TIFF goes through the same proxy path but is not a raw container. */
raw = true,
): Promise<PhotoRecord> { ): Promise<PhotoRecord> {
const id = uid(); const id = uid();
const upload = await cloud.uploadOriginal(id, file, file.name); const upload = await cloud.uploadOriginal(id, file, file.name);
@@ -155,8 +160,9 @@ async function importRaw(
keywords, keywords,
edits, edits,
history: [{ label: 'Import', ts: Date.now(), edits }], history: [{ label: 'Import', ts: Date.now(), edits }],
raw: true, raw,
decode: upload.engine, decode: upload.engine,
proxyBytes: upload.previewBytes,
previewUrl, previewUrl,
}); });
@@ -239,9 +245,10 @@ export async function importFiles(
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => { await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
if (signal?.aborted) return; if (signal?.aborted) return;
try { try {
const photo = isRawFile(file) const viaServer = isRawFile(file) || isTiffFile(file);
const photo = viaServer
? cloud ? cloud
? await importRaw(file, eventId, keywords, cloud, defaults) ? await importRaw(file, eventId, keywords, cloud, defaults, isRawFile(file))
: (() => { : (() => {
throw new Error('Raw files need the Luminary server. Sign in, then import again.'); throw new Error('Raw files need the Luminary server. Sign in, then import again.');
})() })()
+45 -1
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { normalizeEdits, withoutLensVignetting } from './edits';
import { defaultForMeta, type CameraLensDefault } from './lensDefaults'; import { defaultForMeta, type CameraLensDefault } from './lensDefaults';
import type { LensProfile } from '../types'; import type { LensProfile, PhotoRecord } from '../types';
const profile = (model: string): LensProfile => ({ const profile = (model: string): LensProfile => ({
maker: 'Nikon', maker: 'Nikon',
@@ -64,4 +65,47 @@ describe('camera-lens default selection', () => {
).toBe(newer); ).toBe(newer);
}); });
it('leaves the vignetting correction off unless the profile asked for it', () => {
// Older saved profiles carry no corrections block at all; the flat-field
// gain would brighten the corners past the frame centre if it defaulted on.
const legacy = normalizeEdits({ lens: { maker: 'Nikon', model: 'Nikkor 50mm', crop: 1 } } as never);
expect(legacy.lens?.corrections).toEqual({ distortion: true, tca: true, vignetting: false });
const optedIn = normalizeEdits({
lens: {
maker: 'Nikon',
model: 'Nikkor 50mm',
crop: 1,
corrections: { distortion: true, tca: true, vignetting: true },
},
} as never);
expect(optedIn.lens?.corrections.vignetting).toBe(true);
});
it('clears a stored vignetting flag once, in edits, snapshots and history', () => {
const profile: LensProfile = {
maker: 'Canon',
model: 'EF 50mm',
crop: 1,
corrections: { distortion: true, tca: true, vignetting: true },
};
const photo = {
id: 'p1',
edits: { lens: profile },
snapshots: [{ id: 's1', name: 'Before', ts: 1, edits: { lens: profile } }],
history: [
{ label: 'Import', ts: 1, edits: { lens: profile } },
{ label: 'Exposure', ts: 2, edits: {} },
],
} as unknown as PhotoRecord;
const cleared = withoutLensVignetting(photo);
expect(cleared?.edits.lens?.corrections.vignetting).toBe(false);
expect(cleared?.snapshots?.[0].edits.lens?.corrections.vignetting).toBe(false);
expect(cleared?.history?.[0].edits.lens?.corrections.vignetting).toBe(false);
// Geometry and CA stay on: only the corner gain was the problem.
expect(cleared?.edits.lens?.corrections.distortion).toBe(true);
// Nothing left to do the second time, so the upgrade is idempotent.
expect(withoutLensVignetting(cleared as PhotoRecord)).toBeNull();
});
}); });
+5 -1
View File
@@ -140,7 +140,11 @@ export interface MapSet {
geometry: Float32Array; geometry: Float32Array;
/** 6 floats per point: red x/y, input x/y, blue x/y. */ /** 6 floats per point: red x/y, input x/y, blue x/y. */
tca?: Float32Array; tca?: Float32Array;
/** 3 floats per point: the same gain for R, G and B. */ /**
* 3 floats per point: the same gain for R, G and B. Lensfun's vignetting
* model describes linear light, so the renderer must apply this after the
* sRGB decode rather than to encoded code values.
*/
vignetting?: Float32Array; vignetting?: Float32Array;
} }
+106
View File
@@ -0,0 +1,106 @@
import { describe, expect, it } from 'vitest';
import { defaultLocalLayer, MAX_LOCAL_COMPONENTS, normalizeEdits } from './edits';
/** Stored edits as they look before mask groups: geometry on the layer itself. */
function legacyLayer() {
return {
id: 'local-1',
name: 'Sky',
kind: 'gradientish' as unknown as string,
mode: 'subtract',
inverted: true,
feather: 20,
brush: { strokes: [] },
linear: { x1: 0.1, y1: 0.2, x2: 0.3, y2: 0.9 },
radial: { cx: 0.4, cy: 0.6, rx: 0.2, ry: 0.3 },
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
curve: [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
],
adjust: {},
};
}
describe('mask groups', () => {
it('migrates a flat layer into a single component without changing the mask', () => {
const edits = normalizeEdits({ local: [legacyLayer()] as never });
const layer = edits.local[0];
expect(layer.components).toHaveLength(1);
const shape = layer.components[0];
// An unknown kind is a brush, as it always was; geometry and the layer's
// combine mode move onto the shape, layer mode stays for blending layers.
expect(shape.kind).toBe('brush');
expect(shape.mode).toBe('subtract');
expect(shape.inverted).toBe(true);
expect(shape.feather).toBe(20);
expect(shape.linear.x2).toBe(0.3);
expect(shape.radial.ry).toBe(0.3);
expect(layer.mode).toBe('subtract');
expect(layer.name).toBe('Sky');
});
it('keeps a stored component list in order with its own modes', () => {
const edit = normalizeEdits({
local: [
{
id: 'local-a',
name: 'Group',
mode: 'add',
components: [
{ id: 's1', kind: 'radial', mode: 'add', radial: { cx: 0.5, cy: 0.5, rx: 0.4, ry: 0.4 } },
{ id: 's2', kind: 'linear', mode: 'subtract', feather: 0, linear: { x1: 0, y1: 0, x2: 1, y2: 1 } },
{ id: 's3', kind: 'brush', mode: 'intersect', brush: { strokes: [] } },
],
curve: [],
adjust: {},
},
],
} as never);
const shapes = edit.local[0].components;
expect(shapes.map((shape) => shape.id)).toEqual(['s1', 's2', 's3']);
expect(shapes.map((shape) => shape.mode)).toEqual(['add', 'subtract', 'intersect']);
expect(shapes[1].kind).toBe('linear');
expect(shapes[2].kind).toBe('brush');
});
it('drops a raster component that lost its coverage instead of baking an empty mask', () => {
const edit = normalizeEdits({
local: [
{
id: 'local-r',
name: 'Raster',
mode: 'add',
components: [{ id: 's1', kind: 'raster', mode: 'add' }],
curve: [],
adjust: {},
},
],
} as never);
expect(edit.local[0].components[0].kind).toBe('brush');
expect(edit.local[0].components[0].raster).toBeUndefined();
});
it('always leaves a layer with at least one shape and caps the group', () => {
const many = Array.from({ length: MAX_LOCAL_COMPONENTS + 4 }, (_, i) => ({
id: `s${i}`,
kind: 'radial',
mode: 'add',
}));
const edit = normalizeEdits({
local: [
{ id: 'local-m', name: 'Many', mode: 'add', components: many, curve: [], adjust: {} },
{ id: 'local-e', name: 'Empty', mode: 'add', components: [], curve: [], adjust: {} },
],
} as never);
expect(edit.local[0].components).toHaveLength(MAX_LOCAL_COMPONENTS);
expect(edit.local[1].components).toHaveLength(1);
});
it('creates new layers with one shape so the panel always has something to edit', () => {
const layer = defaultLocalLayer('linear', 0);
expect(layer.components).toHaveLength(1);
expect(layer.components[0].kind).toBe('linear');
expect(layer.components[0].mode).toBe('add');
});
});
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from 'vitest';
import { buildLocalCurveLUT } from '../gl/renderer';
/** Bytes of one LUT row (red channel; R/G/B are written identically). */
function row(data: Uint8Array, index: number) {
return Array.from(data.slice(index * 256 * 4, (index + 1) * 256 * 4)).filter((_, i) => i % 4 === 0);
}
describe('mask curve LUT', () => {
it('is the identity for a mask without a curve', () => {
const values = row(buildLocalCurveLUT([{}]), 0);
expect(values[0]).toBe(0);
expect(values[64]).toBeGreaterThan(60);
expect(values[64]).toBeLessThan(69);
expect(values[255]).toBe(255);
});
it('lifts only the row belonging to that mask', () => {
const data = buildLocalCurveLUT([{}, { curve: [{ x: 0, y: 0.25 }, { x: 1, y: 1 }] }]);
expect(row(data, 0)[64]).toBeLessThan(80);
expect(row(data, 1)[64]).toBeGreaterThan(100);
});
it('keeps an inverted curve monotonic instead of folding', () => {
// A curve that dips and rises again would posterise the masked area.
const values = row(
buildLocalCurveLUT([
{ curve: [{ x: 0, y: 0 }, { x: 0.3, y: 0.8 }, { x: 0.7, y: 0.2 }, { x: 1, y: 1 }] },
]),
0,
);
for (let i = 1; i < values.length; i++) expect(values[i]).toBeGreaterThanOrEqual(values[i - 1]);
});
it('fills all eight rows so a ninth mask cannot read stale data', () => {
const data = buildLocalCurveLUT([{ curve: [{ x: 0, y: 0 }, { x: 1, y: 0.5 }] }]);
expect(data.length).toBe(256 * 8 * 4);
expect(row(data, 7)[255]).toBe(255);
});
});
+6 -4
View File
@@ -149,7 +149,7 @@ describe('parsePreview16', () => {
expect(Array.from(parsed!.rgba.slice(4, 8))).toEqual([0x3c00, 0, 0x3800, 0x3c00]); expect(Array.from(parsed!.rgba.slice(4, 8))).toEqual([0x3c00, 0, 0x3800, 0x3c00]);
}); });
it('flips the rows so upload needs no UNPACK_FLIP_Y', async () => { it('keeps the PNG row order so the sidecar matches the JPEG texture', async () => {
const parsed = await parsePreview16( const parsed = await parsePreview16(
encodePng16( encodePng16(
[ [
@@ -161,9 +161,11 @@ describe('parsePreview16', () => {
), ),
); );
expect(parsed).not.toBeNull(); expect(parsed).not.toBeNull();
// Row 0 of the returned buffer is the last image row. // Chrome ignores UNPACK_FLIP_Y_WEBGL for ImageBitmap uploads, so the JPEG
expect(parsed!.rgba[0]).toBe(0); // proxy is top-down in the texture. Flipping here put the 16-bit sidecar
expect(parsed!.rgba[4]).toBe(0x3c00); // upside down once it replaced the proxy a few seconds after load.
expect(parsed!.rgba[0]).toBe(0x3c00);
expect(parsed!.rgba[4]).toBe(0);
}); });
it('reads the camera matrix out of the sidecar text chunk', async () => { it('reads the camera matrix out of the sidecar text chunk', async () => {
+8 -5
View File
@@ -8,14 +8,16 @@
* always optional. * always optional.
* *
* The parser only accepts what the encoder writes (16-bit, non-interlaced, * The parser only accepts what the encoder writes (16-bit, non-interlaced,
* RGB or RGBA) and returns the samples as half-float RGBA with the rows already * RGB or RGBA) and returns the samples as half-float RGBA in the PNG's own
* flipped, because `UNPACK_FLIP_Y_WEBGL` is ignored for ArrayBufferView uploads. * top-down row order. That is the order the JPEG proxy already lands in: an
* ImageBitmap upload ignores `UNPACK_FLIP_Y_WEBGL`, so the sidecar has to match
* it row for row or the picture jumps upside down when it swaps in.
*/ */
export interface Preview16 { export interface Preview16 {
width: number; width: number;
height: number; height: number;
/** RGBA half-float, rows bottom-up, ready for `texImage2D` without a flip. */ /** RGBA half-float, top-down like the proxy, ready for `texImage2D` unflipped. */
rgba: Uint16Array; rgba: Uint16Array;
/** /**
* Camera-to-sRGB matrix, row major, when the samples are camera native. * Camera-to-sRGB matrix, row major, when the samples are camera native.
@@ -195,8 +197,9 @@ export async function parsePreview16(buffer: ArrayBuffer): Promise<Preview16 | n
const rgba = new Uint16Array(width * height * 4); const rgba = new Uint16Array(width * height * 4);
const opaque = table[65535]; const opaque = table[65535];
let out = 0; let out = 0;
for (let y = height - 1; y >= 0; y--) { for (let y = 0; y < height; y++) {
// Bottom-up: the texture upload cannot flip an ArrayBufferView. // Top-down: the JPEG texture is uploaded from an ImageBitmap, which ignores
// UNPACK_FLIP_Y_WEBGL, so both sources must hand the GPU the same row order.
let src = y * (stride + 1) + 1; let src = y * (stride + 1) + 1;
for (let x = 0; x < width; x++) { for (let x = 0; x < width; x++) {
rgba[out++] = table[(raw[src] << 8) | raw[src + 1]]; rgba[out++] = table[(raw[src] << 8) | raw[src + 1]];
+46
View File
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest';
import {
RAW_ACCEPT,
RAW_EXTENSIONS,
SERVER_IMAGE_EXTENSIONS,
isRawFile,
isTiffFile,
} from './raw';
import { isSupportedFile } from './import';
/** isRawFile/isTiffFile only read the name; isSupportedFile also reads type. */
function fakeFile(name: string, type = ''): File {
return { name, type } as File;
}
describe('import format routing', () => {
it.each(['CR2', 'NEF', 'CR3', 'DNG'])('sends .%s to the server raw decoder', (ext) => {
const file = fakeFile(`IMG_0001.${ext}`, 'application/octet-stream');
expect(RAW_EXTENSIONS.has(ext.toLowerCase())).toBe(true);
expect(isRawFile(file)).toBe(true);
expect(isTiffFile(file)).toBe(false);
expect(isSupportedFile(file)).toBe(true);
});
it.each(['TIF', 'TIFF'])('sends .%s to the server still decoder', (ext) => {
const file = fakeFile(`scan.${ext}`, 'image/tiff');
expect(SERVER_IMAGE_EXTENSIONS.has(ext.toLowerCase())).toBe(true);
expect(isTiffFile(file)).toBe(true);
expect(isRawFile(file)).toBe(false);
expect(isSupportedFile(file)).toBe(true);
});
it('still accepts the browser-decoded formats', () => {
expect(isSupportedFile(fakeFile('photo.jpg', 'image/jpeg'))).toBe(true);
expect(isSupportedFile(fakeFile('photo.png', 'image/png'))).toBe(true);
expect(isSupportedFile(fakeFile('photo.webp', 'image/webp'))).toBe(true);
expect(isSupportedFile(fakeFile('photo.avif', 'image/avif'))).toBe(true);
expect(isSupportedFile(fakeFile('notes.txt', 'text/plain'))).toBe(false);
});
it('offers every supported extension in the file picker', () => {
for (const ext of ['cr2', 'nef', 'cr3', 'dng', 'tif', 'tiff', 'sraw']) {
expect(RAW_ACCEPT.split(',')).toContain(`.${ext}`);
}
});
});
+17 -2
View File
@@ -7,12 +7,27 @@ export const RAW_EXTENSIONS = new Set([
'rw2', 'raw', 'rwl', 'rw2', 'raw', 'rwl',
'raf', 'raf',
'pef', 'dng', 'pef', 'dng',
'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef', 'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef', 'sraw',
]); ]);
/**
* Standard images the browser cannot decode itself. They take the same server
* path as raws: the original is stored and the server writes a JPEG proxy.
* Chrome and Firefox have no TIFF decoder, so a TIFF left to the browser is a
* silent import failure.
*/
export const SERVER_IMAGE_EXTENSIONS = new Set(['tif', 'tiff']);
export function isTiffFile(file: File): boolean {
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
return SERVER_IMAGE_EXTENSIONS.has(ext);
}
export function isRawFile(file: File): boolean { export function isRawFile(file: File): boolean {
const ext = file.name.split('.').pop()?.toLowerCase() ?? ''; const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
return RAW_EXTENSIONS.has(ext); return RAW_EXTENSIONS.has(ext);
} }
export const RAW_ACCEPT = [...RAW_EXTENSIONS].map((e) => `.${e}`).join(','); export const RAW_ACCEPT = [...RAW_EXTENSIONS, ...SERVER_IMAGE_EXTENSIONS]
.map((e) => `.${e}`)
.join(',');
+4 -8
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { defaultEdits, normalizeEdits } from './edits'; import { defaultEdits, defaultLocalLayer, normalizeEdits } from './edits';
import { editsToXmp, xmpFileName, xmpToEdits } from './xmp'; import { editsToXmp, xmpFileName, xmpToEdits } from './xmp';
describe('xmp sidecars', () => { describe('xmp sidecars', () => {
@@ -12,13 +12,9 @@ describe('xmp sidecars', () => {
edits.parametric.darks = -17; edits.parametric.darks = -17;
edits.hsl.hue[3] = 12; edits.hsl.hue[3] = 12;
edits.grain.roughness = 71; edits.grain.roughness = 71;
edits.local = [ const mask = defaultLocalLayer('linear', 0);
{ if (mask.components[0]) mask.components[0].linear = { x1: 0.1, y1: 0.2, x2: 0.8, y2: 0.9 };
...defaultEdits().local[0], edits.local = [mask];
kind: 'linear',
linear: { x1: 0.1, y1: 0.2, x2: 0.8, y2: 0.9 },
},
];
const xml = editsToXmp(edits); const xml = editsToXmp(edits);
const back = xmpToEdits(xml, defaultEdits()); const back = xmpToEdits(xml, defaultEdits());
+54
View File
@@ -3057,6 +3057,24 @@ figcaption {
} }
/* Sits beside the ? button: opens the printable guide in a new tab. */ /* Sits beside the ? button: opens the printable guide in a new tab. */
/* The brand doubles as the About button; the reset keeps the header metrics. */
.brand-btn {
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
letter-spacing: inherit;
cursor: pointer;
border-radius: 6px;
}
.brand-btn:hover { color: var(--text); }
.brand-btn:focus-visible { outline: 2px solid var(--accent, #4c8dff); outline-offset: 3px; }
.about-brand { display: flex; align-items: center; gap: 12px; }
.about-brand strong { display: block; font-size: 16px; }
.about-facts { margin: 0; }
.guide-btn { .guide-btn {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -3435,10 +3453,21 @@ figcaption {
.clip-dot.y { .clip-dot.y {
background: #ffe61a; background: #ffe61a;
} }
.clip-dot.m {
background: #ff26d9;
}
.clip-dot.c {
background: #1ad9ff;
}
.clip-dot.w { .clip-dot.w {
background: #ffffff; background: #ffffff;
} }
/* Groups the shadow palette dots so "one channel" reads with its own colours. */
.clip-legend .clip-label {
margin-right: 5px;
}
@media (max-width: 760px) { @media (max-width: 760px) {
.admin-create-grid { .admin-create-grid {
grid-template-columns: 1fr 1fr; grid-template-columns: 1fr 1fr;
@@ -4650,6 +4679,15 @@ figcaption {
stroke: rgba(255, 92, 92, 0.4); stroke: rgba(255, 92, 92, 0.4);
} }
/* The soft band of the feather, drawn under the solid core. */
.local-brush.band {
stroke: rgba(240, 170, 80, 0.14);
}
.local-brush.band.erase {
stroke: rgba(255, 92, 92, 0.13);
}
.local-outline, .local-outline,
.local-line { .local-line {
fill: none; fill: none;
@@ -4675,6 +4713,12 @@ figcaption {
stroke-dasharray: 3 3; stroke-dasharray: 3 3;
} }
/* Marks where the feather band starts, mirroring the baked mask. */
.local-cursor.inner {
stroke: rgba(240, 174, 85, 0.5);
stroke-dasharray: 2 4;
}
.local-list { .local-list {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -4682,6 +4726,16 @@ figcaption {
margin-bottom: 7px; margin-bottom: 7px;
} }
/* Shapes sit under their layer, indented so the group reads as a child list. */
.local-list.shapes {
margin-bottom: 4px;
padding-left: 8px;
}
.local-list.shapes .local-item {
font-size: 11px;
}
.local-item { .local-item {
display: flex; display: flex;
align-items: center; align-items: center;
+22 -6
View File
@@ -63,12 +63,11 @@ export interface LocalStroke {
erase?: boolean; erase?: boolean;
} }
/** One non-destructive local adjustment layer. Mask geometry is in source uv. */ /** One shape inside a local adjustment layer's mask group. */
export interface LocalLayer { export interface LocalComponent {
id: string; id: string;
name: string;
kind: LocalMaskKind; kind: LocalMaskKind;
/** How this mask combines with the layer above it in the list. */ /** How this shape combines with the shapes before it inside the layer. */
mode: 'add' | 'subtract' | 'intersect'; mode: 'add' | 'subtract' | 'intersect';
inverted: boolean; inverted: boolean;
/** softness of the mask edge, 0–100 */ /** softness of the mask edge, 0–100 */
@@ -77,7 +76,17 @@ export interface LocalLayer {
linear: { x1: number; y1: number; x2: number; y2: number }; linear: { x1: number; y1: number; x2: number; y2: number };
radial: { cx: number; cy: number; rx: number; ry: number }; radial: { cx: number; cy: number; rx: number; ry: number };
raster?: RasterMask; raster?: RasterMask;
/** luminance and colour limits applied on top of the shape */ }
/** One non-destructive local adjustment layer. Mask geometry is in source uv. */
export interface LocalLayer {
id: string;
name: string;
/** How the whole layer combines with the layer above it in the list. */
mode: 'add' | 'subtract' | 'intersect';
/** Shapes composited in order into this layer's mask. */
components: LocalComponent[];
/** luminance and colour limits applied on top of the shape group */
range: { range: {
enabled: boolean; enabled: boolean;
lumaMin: number; lumaMin: number;
@@ -86,6 +95,11 @@ export interface LocalLayer {
hueRange: number; hueRange: number;
satMin: number; satMin: number;
}; };
/**
* Per-mask RGB tone curve, applied to the masked pixels only. Identity for
* masks created before this existed, so old edits keep their look.
*/
curve: CurvePoint[];
adjust: { adjust: {
exposure: number; exposure: number;
contrast: number; contrast: number;
@@ -306,13 +320,15 @@ export interface PhotoRecord {
/** true when the original is a camera raw decoded by the server */ /** true when the original is a camera raw decoded by the server */
raw?: boolean; raw?: boolean;
/** how the editable proxy was produced */ /** how the editable proxy was produced */
decode?: 'libraw' | 'embedded'; decode?: 'libraw' | 'embedded' | 'sharp';
/** server URL for the editable proxy (raw only) */ /** server URL for the editable proxy (raw only) */
previewUrl?: string; previewUrl?: string;
/** server URL for the grid thumbnail */ /** server URL for the grid thumbnail */
thumbUrl?: string; thumbUrl?: string;
/** Bumped when the stored RAW is re-decoded, to invalidate cached previews. */ /** Bumped when the stored RAW is re-decoded, to invalidate cached previews. */
previewVersion?: number; previewVersion?: number;
/** Bytes of the server-written editable proxy (raw and TIFF imports). */
proxyBytes?: number;
/** set when this photo was imported from an Immich album */ /** set when this photo was imported from an Immich album */
immich?: { albumId: string; assetId: string; checksum: string }; immich?: { albumId: string; assetId: string; checksum: string };
/** timestamp of the last rendered client proof published to the server */ /** timestamp of the last rendered client proof published to the server */
+34
View File
@@ -0,0 +1,34 @@
# syntax=docker/dockerfile:1
#
# Reproducible Windows bundle build on a Linux host.
#
# This image never touches the app's own Dockerfile or compose file; it exists
# so the optional Windows artifact (including Luminary.exe, which needs Go) can
# be produced from this machine:
#
# docker build -f windows/Dockerfile --output type=local,dest=/tmp/luminary-win .
#
# The output directory must be outside the checkout (see windows/README.md).
# BuildKit is required for --output.
#
# `--output` exports the "artifacts" stage, which is `scratch`: only the bundle
# zip, its checksum and the staged tree are copied out.
FROM node:24-bookworm AS build
COPY --from=golang:1.23-bookworm /usr/local/go /usr/local/go
ENV PATH="/usr/local/go/bin:${PATH}"
WORKDIR /src
COPY . .
# Build-time dependencies for vite and tsc; the Windows runtime dependencies are
# installed separately by build.mjs with --os=win32 --cpu=x64.
RUN npm ci --no-audit --no-fund
# --allow-dirty: the build context has no .git, so the worktree check is skipped.
# The Go toolchain makes build.mjs produce Luminary.exe instead of the .cmd/.vbs
# pair; pass --launcher ps to force the PowerShell-only launcher.
RUN node windows/build.mjs --out /out --allow-dirty
FROM scratch AS artifacts
COPY --from=build /out/ /
+11
View File
@@ -0,0 +1,11 @@
# Context for windows/Dockerfile. The app's own Dockerfile keeps using the root
# .dockerignore; this file only affects Windows bundle builds.
.git
node_modules
dist
.check
.smoke
server/data
windows/out
*.log
logo.png
+372
View File
@@ -0,0 +1,372 @@
# Windows bundle (optional)
An additive, self-contained way to produce a double-clickable Windows install of
Luminary. The server and Docker workflow stay the source of truth: this folder
only *packages* the existing `dist/` + `server/` output, and the build writes
its artifacts **outside the checkout**.
- Design of the launcher: [launcher/DESIGN.md](launcher/DESIGN.md)
- Moving this into its own repository: [SEPARATE-REPO.md](SEPARATE-REPO.md)
## Isolation guarantees
1. **The packaging tree is additive.** There is no `package.json` script for
this, and no change to `.gitignore`, `.dockerignore`, `Dockerfile`,
`docker-compose.yml` or `scripts/deploy.mjs`. Invoke it directly:
`node windows/build.mjs`. The one app-side addition is an opt-in desktop mode
in `server/config.mjs` + `server/index.mjs` (`LUMINARY_LOCAL=1`): a single
passwordless local admin. It is off unless the Windows launcher sets it, so
Docker and the shared server are unchanged.
2. **Artifacts live outside the repo** (default: `~/.cache/luminary-windows`, or
`%LOCALAPPDATA%\Luminary\build` on Windows). The script refuses an `--out`
inside the checkout, because `scripts/deploy.mjs` rsyncs the worktree to
production and `docker build` would pull a ~300 MB bundle into its context.
3. **The worktree must be clean outside `windows/`** before and after a build
(the untracked `logo.png` is tolerated). `--allow-dirty` overrides it.
4. **Nothing in the app changes at run time.** The bundle is the unchanged
`server/` + `dist/` + production `node_modules`, started with `PORT`, `HOST`,
`NODE_ENV` and `LUMINARY_DATA` — all variables the server already reads.
## What the end user needs
Nothing to install. This was audited from the shipped binaries' own PE imports,
not assumed:
| Component | What it needs on the target PC |
| --- | --- |
| `node.exe` (v24.22.2) | only Windows system DLLs (`KERNEL32`, `ADVAPI32`, `WS2_32`, `CRYPT32`, `USER32`, …) — statically linked C runtime, so **no Visual C++ Redistributable** |
| `libvips-42.dll` + `sharp` | the Universal C Runtime (`api-ms-win-crt-*`), included in Windows 10/11; older Windows needs KB2999226 |
| `libraw.wasm` | a browser with WebAssembly |
| launcher (`.cmd`/`.vbs`) | Windows PowerShell 5.1, included in Windows 10/11 |
| Develop module | a current browser with WebGL2 (Edge, Chrome, Firefox) |
So: a clean Windows 10/11 x64 machine, a browser, and ~250 MB where the data
folder lives. No VC++ redist, no .NET, no admin prompt. The setup exe installs
for the current user only; the portable zip needs no installer at all.
What the launcher checks on every start (and `-Status` prints):
- Windows build ≥ 10240, `PROCESSOR_ARCHITECTURE` of `AMD64`/`ARM64`, UCRT
present, and free space on the data drive. Windows older than 10 is refused
with a specific message and link, exit code `4`.
- Missing `node.exe` → offers to download it from nodejs.org and verifies the
SHA-256 in `version.txt` before installing (same code as `-Repair`).
- Missing `node.exe` but a system Node 24+ exists → starts on it, says which
one, and points at `-Repair`.
Official links, shown in the dialogs when relevant:
[Windows 10/11](https://www.microsoft.com/software-download/windows11) ·
[Universal C Runtime / KB2999226](https://support.microsoft.com/help/2999226) ·
[Microsoft Edge](https://www.microsoft.com/edge).
## Requirements (build host)
| Need | Why |
| --- | --- |
| Node.js 24 | the builder itself, and `npm run build` for `dist/` |
| `npm` with `--os`/`--cpu` support (npm ≥ 10) | installs the `sharp` **win32-x64** prebuild from Linux |
| Network | `node.exe` from nodejs.org (SHA-256 checked) and the npm registry |
| Optional: Go 1.21+ | builds `Luminary.exe`; without it the PowerShell launcher ships |
| Optional: Docker + BuildKit | the reproducible path, and the only way to get the Go exe on Linux |
| Optional: NSIS 3 | builds the setup exe; `--installer` unpacks a private copy on Linux when `makensis` is absent |
No Windows machine is required for either the portable zip or the setup exe:
NSIS cross-compiles the installer on Linux and macOS.
## Build
```bash
node windows/build.mjs # npm run build, then the bundle
node windows/build.mjs --skip-build # reuse the existing dist/
node windows/build.mjs --out /srv/builds/luminary-win
node windows/build.mjs --launcher go # fail unless Go is installed
node windows/build.mjs --installer # also build the setup exe (NSIS)
node windows/build.mjs --skip-build --publish # copy the zip and setup to windows/releases
```
Output:
```
<out>/
Luminary-0.5.1-win-x64.zip the portable deliverable
installer/Luminary-0.5.1-win-x64-setup.exe the per-user installer
stage/Luminary/ the unpacked bundle (kept for inspection)
cache/node-v24.22.2-win-x64.exe pinned runtime, reused next time
cache/SHASUMS256-v24.22.2.txt
```
The build prints each artifact's size and SHA-256, the Node version, the
launcher kind and the staged folder. The setup exe is built whenever `makensis`
is found (or with `--installer`, which fetches NSIS on Linux); otherwise the zip
is built alone with a warning.
### Transferring it to Windows
`--publish` copies the finished zip and a `SHA256SUMS.txt` into
[`releases/`](releases/), which is the hand-off folder for a USB stick, network
share or release upload:
```bash
node windows/build.mjs --skip-build --publish
```
It is the only write the builder makes inside the checkout; staging and zipping
still happen outside it. On the Windows PC: extract the zip, then run
`Luminary.cmd` or `Luminary.vbs` from the extracted `Luminary` folder. Note that
`scripts/deploy.mjs` rsyncs the worktree, so remove the zip from `releases/`
after transferring if you do not want it on the server.
### Reproducible path with Docker
```bash
docker build -f windows/Dockerfile --output type=local,dest=/srv/builds/luminary-win .
```
The image has Node 24 **and** Go, so it produces `Luminary.exe`. The final stage
is `scratch`, so `--output` exports only the zip, checksum and staged bundle.
`windows/Dockerfile.dockerignore` keeps `.git`, `node_modules` and `dist` out of
the context; the app's own `Dockerfile` is unaffected.
### Installer
`windows/installer.nsi` wraps the same staged bundle in an NSIS setup exe. NSIS
is a cross-compiler, so this builds on the Linux host as well as on Windows:
```bash
node windows/build.mjs --installer # or --skip-build --installer
```
`--installer` uses `makensis` from `PATH` or `$MAKENSIS`; if neither exists on
Linux it downloads the two Ubuntu `nsis` packages into `<out>/tools/nsis` and
runs them from there, so no root install is needed. Install it yourself with
`sudo apt install nsis`, `brew install makensis`, or the Windows installer from
<https://nsis.sourceforge.io>. Compile by hand with:
```bash
makensis -DAPP_VERSION=0.5.1 -DAPP_VERSION4=0.5.1.0 \
-DSOURCE_DIR="$PWD/stage/Luminary" windows/installer.nsi
```
The setup is per-user: **no UAC prompt**, nothing in Program Files. It installs
to `%LOCALAPPDATA%\Programs\Luminary`, creates Start-menu shortcuts (Luminary,
Stop Luminary, the data folder), an optional desktop shortcut and an optional
"start at login" (`HKCU\…\Run`), registers an uninstaller in Apps & features,
and **keeps** `%LOCALAPPDATA%\Luminary\data` when uninstalled. Before replacing
files it runs the bundle's own `Luminary.ps1 -Stop`, so an upgrade over a
running copy works without killing every `node.exe` on the machine.
Silent install and uninstall, for a script or a school lab image:
```bat
Luminary-0.5.1-win-x64-setup.exe /S
"%LOCALAPPDATA%\Programs\Luminary\Uninstall.exe" /S
```
`/D=C:\path` overrides the install folder (last argument, unquoted, as NSIS
requires). The installer refuses 32-bit Windows and anything before Windows 10,
the same limits as the launcher, but says so before copying 250 MB.
## What is in the bundle
```
Luminary/
node.exe Node 24 win-x64, verified against nodejs.org
Luminary.ps1 start / -Stop / -Status / -Verify / -Repair / -Browser
Luminary.cmd visible-console entry point
Luminary.vbs no-console entry point
Stop Luminary.cmd
Luminary.exe only with a Go toolchain
LuminaryWindow.exe optional native WebView2 window (--webview2)
Luminary.ico icon for shortcuts and the installer
version.txt version, commit, launcher, and the Node pin (version, SHA-256, size)
README-windows.txt end-user instructions
LICENSE, THIRD_PARTY_NOTICES.md, licenses/
app/
server/ unchanged, minus server/data and *.test.mjs
dist/ the normal Vite build (UI, lens db, guide PDF)
package.json provenance
package-lock.json
node_modules/ production deps installed with --os=win32 --cpu=x64
runtime.json created on first start
logs/ created on first start
```
`sharp` is installed from the repository's own lockfile, so the Windows native
package (`@img/sharp-win32-x64`) matches the version the app was tested with.
The build verifies that its `.node` binary is present and only warns if not —
the server degrades to PNG proxies rather than failing to boot.
## Running it
Double-click `Luminary.cmd` (brief console) or `Luminary.vbs` (silent). The
launcher picks a free loopback port starting at 8787, sets
`LUMINARY_DATA=%LOCALAPPDATA%\Luminary\data`, starts `node.exe` hidden, waits for
`/api/health`, then opens the browser. `Stop Luminary.cmd` stops it;
`Luminary.ps1 -Status` reports PID, URL, runtime and data folder.
### Single-user desktop mode
The launcher starts the server with `LUMINARY_LOCAL=1`:
- one admin (`local@luminary`) is created on first start and reused afterwards;
- `/api/auth/me` answers without a cookie, so the UI never shows signup or
sign-in, and registration returns 403;
- the account is an admin, so every panel works; it cannot be renamed, disabled
or deleted from the UI (403), and there is no password to remember;
- the password is random and never shown, and the server binds `127.0.0.1`, so
this is not reachable from the network. Starting with `HOST=0.0.0.0` and
`LUMINARY_LOCAL=1` logs a warning at boot.
Without the variable, accounts, invites and email behave exactly as before —
Docker and the shared server are untouched.
### App window
Instead of a tab, the launcher opens a chromeless window from the browser that
is already installed:
```
msedge.exe --app=http://127.0.0.1:8787 --user-data-dir=%LOCALAPPDATA%\Luminary\data\window-profile
```
No tabs, no address bar, its own profile, and it remembers its window size.
Edge ships with Windows 10/11, so nothing is installed; Chrome is the fallback
and the default browser is the last resort. `Luminary.cmd -Browser` (or
`LUMINARY_WINDOW=browser`) opens a normal tab instead.
A fully native window is available too: `windows/launcher/webview2` is a small
WinForms host around WebView2 that owns its title bar, taskbar icon and window
state. When the bundle contains `LuminaryWindow.exe`, the launcher uses it
ahead of the browser window. Build it once (self-contained, no .NET needed on
the target machine):
```bash
mkdir -p /tmp/wv
docker run --rm -v "$PWD/windows/launcher:/src" -v /tmp/wv:/out \
-w /src/webview2 mcr.microsoft.com/dotnet/sdk:8.0 \
dotnet publish -c Release -o /out
node windows/build.mjs --webview2 /tmp/wv/LuminaryWindow.exe --publish
```
It needs the Microsoft Edge **WebView2 runtime**, which ships with Windows
10/11 alongside Edge; if it is ever missing, the window says so and links the
Evergreen installer. The exe adds roughly 70 MB to the zip, which is why it is
opt-in rather than always shipped.
Double-clicking `LuminaryWindow.exe` directly is safe too. Without `--url` it
starts the bundle launcher and exits; the launcher then starts desktop mode and
reopens the window with `--url`. It uses `Luminary.exe` when the Go build ships
one, otherwise it runs `Luminary.ps1` through a hidden PowerShell process. That
avoids `Luminary.vbs` and Windows Script Host, which some machines disable by
policy. If the exe is copied out of a complete bundle, it explains that it is
only the window rather than showing a signed-out page.
`Luminary.cmd -Verify` checks the bundle. `Luminary.cmd -Repair` re-downloads
`node.exe` from nodejs.org and installs it only after the SHA-256 matches
`version.txt` — the fix for an antivirus that quarantined the runtime. If
the bundled `node.exe` is gone and a system Node 24+ exists, the app still
starts on that runtime (with a warning) while you decide to repair.
Full behaviour, edge cases and the test checklist: [launcher/DESIGN.md](launcher/DESIGN.md).
## Data, updates and backups
- Catalog, originals, previews and `secret.key` live in
`%LOCALAPPDATA%\Luminary\data` — never under `app\`, so an update cannot lose
them.
- Update: stop Luminary, replace `app\` (and `node.exe` when it changes) from a
newer bundle, start again. The SQLite schema migrates on boot.
- Back up: copy the whole data folder while Luminary is stopped, including
`lumenroom.db`, `lumenroom.db-wal`, `lumenroom.db-shm`.
## Verifying a build
```bash
cd <out>
sha256sum Luminary-0.5.1-win-x64.zip
unzip -t Luminary-0.5.1-win-x64.zip | tail -1
unzip -l Luminary-0.5.1-win-x64.zip | grep -E 'node.exe|Luminary\.(exe|cmd|vbs)|app/server/index.mjs'
```
On Windows, the real test is the checklist in `launcher/DESIGN.md` §15,
especially a machine with **no Node installed**. The automated first pass is
[`SMOKE-WINDOWS.ps1`](SMOKE-WINDOWS.ps1), run from the extracted bundle:
```bat
powershell -ExecutionPolicy Bypass -File .\SMOKE-WINDOWS.ps1
```
It checks the OS and WebView2 runtime, `-Verify`, a real desktop-mode boot
(`local:true`, cookieless `/api/auth/me`, `/api/sync`), the native window
launching and owning a window titled Luminary, and Stop — then writes
`smoke-report.txt` next to the bundle.
## When the launcher says the bundle is incomplete
The bundle is a folder: `node.exe`, `Luminary.*`, and `app\server`, `app\dist`,
`app\node_modules`. The launcher checks those three trees before starting and
prints which one is missing:
- **Opened from the zip preview** — Windows extracts only the file you double-
clicked into `%TEMP%`, so `node.exe` and `app\` are absent. Extract the whole
zip first (right-click → "Extract All...").
- **Antivirus/SmartScreen removed `node.exe`** — common with a freshly
downloaded, unsigned Node runtime. Restore it from quarantine, or unblock the
zip and extract again. `version.txt` carries the exact SHA-256 so a restored
copy can be checked: the build verified the same hash against
`nodejs.org/dist/<version>/SHASUMS256.txt`.
- **Running the source launcher** — `windows\launcher\Luminary.cmd` is a template
for the builder, not an install. Run `node windows/build.mjs` and use the zip.
`Luminary.cmd -Verify` prints the resolved bundle path, the size of each
required file, the pinned Node version and the Luminary version, and exits `3`
when something is missing or `node.exe` has the wrong size. The Go launcher
shows the same message in a dialog box because it has no console.
### Repairing `node.exe`
```bat
Luminary.cmd -Repair
```
Reads the version and hash from `version.txt` (falling back to the published
`SHASUMS256.txt`), downloads into a temp file, verifies the SHA-256, and only
then replaces `node.exe`. It refuses while Luminary is running. Set
`LUMINARY_NODE_URL` to use a mirror or an internal copy for air-gapped machines.
`Luminary.exe -repair` does the same.
## Limitations
- The launcher is unsigned: SmartScreen may ask once, and a strict antivirus
policy can quarantine `node.exe`; `-Repair` restores it, and the launcher can
fall back to a system Node 24+ in the meantime.
- No tray icon and no auto-update in this version (both are launcher features,
not app changes).
- Loopback only by default; set `HOST=0.0.0.0` for LAN proofing galleries.
- The PowerShell launcher cannot clean up after a server crash; a stale
`runtime.json` is simply ignored on the next start.
- The setup exe cannot be executed on the Linux build host. It is verified by
unpacking it and comparing the SHA-256 of every payload file with the staged
bundle, plus `SMOKE-WINDOWS.ps1` for the installed tree; a real install and
uninstall still needs one pass on Windows.
## Troubleshooting
| Symptom | Check |
| --- | --- |
| "node.exe is missing" / "this folder is not a complete Luminary bundle" | run `Luminary.cmd -Verify`. Usual causes: the zip was opened instead of extracted (right-click → Extract All), antivirus removed `node.exe` after extraction, or `Luminary.cmd` was run from the source `windows\launcher` folder instead of the built bundle. For the antivirus case run `Luminary.cmd -Repair` |
| Launch says it is using the system Node | the bundled `node.exe` is missing or truncated; `Luminary.cmd -Repair` restores the pinned runtime |
| `Repair failed` | no network, a proxy blocking `nodejs.org`, or a checksum mismatch (nothing is installed in that case). Point `LUMINARY_NODE_URL` at a mirror of `node.exe` |
| "Luminary needs Windows 10 or 11" (exit 4) | the launcher read `CurrentBuild` below 10240. The app targets Windows 10/11; there is no Windows 7/8 build |
| "The Universal C Runtime is missing" | Windows 8.1 without KB2999226 — install <https://support.microsoft.com/help/2999226> or use Windows 10/11 |
| "The data drive has only … GB free" | free space before starting; catalogs and previews grow in `%LOCALAPPDATA%` |
| "did not answer on /api/health" | `logs\server.err.log`; run `node app\server\index.mjs` from `app\` to see the failure |
| Browser opens an error page | the port was taken between the check and the spawn; start again |
| RAW import fails | `app\node_modules\@img\sharp-win32-x64` must contain a `.node` binary; RAW decode itself is wasm |
| `node.exe failed its SHA-256 check` | delete `<out>/cache` and rebuild (the download was truncated) |
| A sign-in screen appears | the server was started without `LUMINARY_LOCAL=1`, or it is the normal server, not the bundle |
| Opens as a normal tab | Edge/Chrome not found, or `-Browser` / `LUMINARY_WINDOW=browser` was used |
| Build refuses `--out` | the path is inside the repo; choose one outside |
| SmartScreen on first run | unsigned build: "More info" → "Run anyway" (same for the setup exe) |
| The setup exe closes immediately on 32-bit Windows | it needs a 64-bit Windows 10/11 install; use the 64-bit build |
| Installed, but no catalog after uninstall | that is intentional: `%LOCALAPPDATA%\Luminary\data` is kept |
+149
View File
@@ -0,0 +1,149 @@
# Separate packaging repository (`luminary-windows`)
This is the fallback path if the `windows/` folder in this repo ever feels too
close to the app: a second repository that builds the same bundle from a pinned
upstream tag. It is a plan, not something that exists yet.
## Why a packaging repo and not a fork
A fork duplicates the app and forces a merge of every upstream change. Nothing
in Luminary is Windows-specific — the server is plain ESM, `node:sqlite` and
`sharp`/`libraw-wasm` ship Windows builds, and the only POSIX-ism
(`secret.key` mode `0o600`) is ignored by Windows. The Windows work is
therefore *packaging*: a fixed folder layout, a Node runtime, a launcher and an
artifact. A packaging repo keeps that work under a separate review and release
process while consuming the app unchanged.
A fork remains justified only if a Windows build ever needs an app patch
(behaviour, not packaging). If that happens, the change belongs upstream in the
main repo first.
## Repository layout
```
luminary-windows/
upstream.txt # pinned tag + commit + expected package version
build.mjs # same script as windows/build.mjs, one copy
launcher/ # Luminary.ps1, .cmd, .vbs, Stop, go/
installer.nsi # NSIS, builds on Linux
Dockerfile # Go + Node 24 image for the exe build
README.md
CHANGELOG.md # per-release: upstream tag, node version, hashes
```
`build.mjs` is copied verbatim from the main repo when it changes; there is no
second implementation to drift.
## Pinning
`upstream.txt`:
```
repo=https://git.maple-street.net/bhursey/luminary.git
tag=v0.5.1
commit=fb43ca8f1c2d… # full sha
version=0.5.1 # package.json version, checked after fetch
node=v24.22.2
```
The build clones the upstream repository at the pinned commit (shallow clone of
the tag, then `git rev-parse HEAD` must equal `commit`) into a work directory
outside both repos, for example:
```
$TMP/luminary-upstream/
```
If the tag moves or the commit does not match, the build fails rather than
silently shipping something else. A `--upstream-ref <sha>` flag allows a
one-off build from a newer commit before the pin is updated.
## Build flow
```
fetch pinned upstream (clone/verify)
→ npm ci (dev deps, needed for vite)
→ npm run build (typecheck + dist/)
→ stage: dist, server, production node_modules (--os=win32 --cpu=x64),
node.exe (SHA-256 verified), launcher, licences
→ zip + sha256
→ optional: iscc installer
```
Exactly the same steps as `windows/build.mjs`; the only difference is where
`dist/`, `server/` and `package.json` come from (a work tree, not `../`).
## CI (Gitea Actions, since the remote is Gitea)
`.gitea/workflows/windows.yml` in the packaging repo:
```yaml
name: windows-bundle
on:
workflow_dispatch:
push:
tags: ['v*']
jobs:
build:
runs-on: ubuntu-latest # or a Windows runner for the installer
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 24 }
- run: node build.mjs --out "$RUNNER_TEMP/out"
- run: sha256sum Luminary-*.zip >> "$RUNNER_TEMP/out/SHA256SUMS"
working-directory: ${{ runner.temp }}/out
- uses: actions/upload-artifact@v4
with:
name: luminary-windows-${{ github.ref_name }}
path: ${{ runner.temp }}/out/*
```
Optional later steps: `softprops/action-gh-release` to attach the zip and setup
exe to a Gitea release. NSIS runs on the Linux runner too (`--installer`), so a
Windows runner is not needed for the installer.
## Release and version policy
- One packaging release per upstream tag that should be installable on Windows;
the artifacts are `Luminary-<version>-win-x64-setup.exe` and the portable
`Luminary-<version>-win-x64.zip`.
- `CHANGELOG.md` records upstream tag/commit, bundled Node version, artifact
SHA-256 and any launcher change.
- Security fixes: when upstream ships one, the pin moves, the packaging tag
increments (`v1.0.1-win.1` style if needed) and the artifact is rebuilt.
- Windows-only changes (launcher, installer) release independently — they do not
require an upstream bump, because they never touch `app/`.
## Updating users
The bundle is portable: replacing `app\` and `node.exe` is the update. Keep the
data folder (`%LOCALAPPDATA%\Luminary\data`) untouched. A future auto-updater
would read a small JSON manifest beside the release and download the zip; that
is a packaging-repo feature, not an app change.
## Migration from the in-repo `windows/` folder
1. Create the new repo.
2. Copy `windows/` to its root (`build.mjs`, `launcher/`, `installer.nsi`,
`Dockerfile`, this plan and `README.md`), adjusting the input paths in
`build.mjs` to the fetched upstream work tree.
3. Add `upstream.txt`, the CI workflow, `CHANGELOG.md`.
4. Build once from the pinned tag and compare the zip contents with the
in-repo build (same files, same launcher) before publishing.
5. Optionally delete `windows/` from the main repo afterwards; nothing in the
app depends on it.
## Trade-offs
| | In-repo `windows/` (current) | Separate repo |
| --- | --- | --- |
| Upstream awareness | always the local checkout | explicit pin, can lag |
| Review/CI noise | one extra folder | separate pipeline |
| Release discipline | none required | tag + changelog per artifact |
| Risk to the app | none (folder only) | none (no files in the app repo) |
| Effort | zero extra repos | one more repo and workflow |
Stay with the in-repo folder while the Windows build changes infrequently;
move to this layout when it needs its own release cadence or a second
maintainer.
+179
View File
@@ -0,0 +1,179 @@
<#
One-command smoke test for an extracted Luminary bundle on Windows.
Run it from the extracted bundle folder (or pass -Bundle):
powershell -ExecutionPolicy Bypass -File .\SMOKE-WINDOWS.ps1
It writes smoke-report.txt next to the bundle and prints the same lines.
Exit code 0 means every check passed.
What it covers without a human clicking:
- OS version and architecture, and whether the WebView2 runtime is present
- the bundle files the launcher needs, and -Verify's own result
- a real server boot in desktop mode: /api/health local:true,
/api/auth/me 200 without a cookie, /api/sync 200
- LuminaryWindow.exe launching, staying alive and owning a window titled
Luminary (the native WebView2 path)
- Stop actually stopping the server
It is deliberately conservative: it uses a throwaway data folder under
%TEMP% and a port that is unlikely to collide, so it never touches a real
catalog.
#>
[CmdletBinding()]
param(
[string]$Bundle = (Split-Path -Parent $MyInvocation.MyCommand.Path),
[int]$Port = 8912,
[int]$WindowSeconds = 8
)
$ErrorActionPreference = 'Stop'
$script:lines = @()
$script:failed = 0
function Say([string]$text) {
$script:lines += $text
Write-Host $text
}
function Check([string]$name, [bool]$ok, [string]$detail = '') {
if ($ok) {
Say (" PASS {0}{1}" -f $name, $(if ($detail) { " — $detail" } else { '' }))
} else {
$script:failed += 1
Say (" FAIL {0}{1}" -f $name, $(if ($detail) { " — $detail" } else { '' }))
}
return $ok
}
function Get-WebView2Version {
$keys = @(
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}',
'HKLM:\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}',
'HKCU:\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}'
)
foreach ($key in $keys) {
try {
$value = (Get-ItemProperty -Path $key -Name pv -ErrorAction Stop).pv
if ($value) { return $value }
} catch { }
}
return $null
}
$nodeExe = Join-Path $Bundle 'node.exe'
$appDir = Join-Path $Bundle 'app'
$entry = Join-Path $appDir 'server\index.mjs'
$windowExe = Join-Path $Bundle 'LuminaryWindow.exe'
$launcher = Join-Path $Bundle 'Luminary.ps1'
$dataDir = Join-Path $env:TEMP ('luminary-smoke-{0}' -f [guid]::NewGuid().ToString('N'))
$url = "http://127.0.0.1:$Port"
$server = $null
$window = $null
Say 'Luminary Windows smoke test'
Say (" bundle {0}" -f $Bundle)
Say (" time {0}" -f (Get-Date).ToString('s'))
try {
$os = Get-CimInstance Win32_OperatingSystem
Say ''
Say 'Environment'
Say (" OS {0} (build {1})" -f $os.Caption, $os.BuildNumber)
Say (" arch {0}" -f $env:PROCESSOR_ARCHITECTURE)
$webview2 = Get-WebView2Version
Say (" webview {0}" -f $(if ($webview2) { "runtime $webview2" } else { 'NOT INSTALLED' }))
Say ''
Say 'Bundle'
Check 'node.exe present' (Test-Path -LiteralPath $nodeExe) $nodeExe
Check 'app\server\index.mjs present' (Test-Path -LiteralPath $entry) $entry
Check 'Luminary.ps1 present' (Test-Path -LiteralPath $launcher) $launcher
Check 'LuminaryWindow.exe present' (Test-Path -LiteralPath $windowExe) $windowExe
if (Test-Path -LiteralPath $launcher) {
$verify = Start-Process -FilePath 'powershell.exe' -ArgumentList @(
'-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $launcher, '-Verify'
) -Wait -PassThru -WindowStyle Hidden
Check '-Verify exits 0' ($verify.ExitCode -eq 0) ("exit {0}" -f $verify.ExitCode)
}
if (-not (Test-Path -LiteralPath $nodeExe)) { throw 'node.exe is missing, cannot start the server' }
if (-not (Test-Path -LiteralPath $entry)) { throw 'app\server\index.mjs is missing, cannot start the server' }
New-Item -ItemType Directory -Force -Path $dataDir | Out-Null
$env:PORT = "$Port"
$env:HOST = '127.0.0.1'
$env:NODE_ENV = 'production'
$env:LUMINARY_DATA = $dataDir
$env:LUMINARY_LOCAL = '1'
Say ''
Say 'Server (desktop mode)'
$server = Start-Process -FilePath $nodeExe -ArgumentList @('"' + $entry + '"') `
-WorkingDirectory $appDir -WindowStyle Hidden -PassThru `
-RedirectStandardOutput (Join-Path $dataDir 'out.log') `
-RedirectStandardError (Join-Path $dataDir 'err.log')
$deadline = (Get-Date).AddSeconds(90)
$health = $null
while ((Get-Date) -lt $deadline) {
try {
$response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 2 -Uri "$url/api/health"
if ($response.StatusCode -eq 200) { $health = $response.Content | ConvertFrom-Json; break }
} catch { }
Start-Sleep -Milliseconds 500
}
Check 'health answers' ($null -ne $health)
if ($health) {
Check 'local mode advertised' ($health.local -eq $true) ("local={0}" -f $health.local)
Check 'no setup prompt' ($health.needsSetup -eq $false)
Check 'registration closed' ($health.registrationOpen -eq $false)
}
try {
$me = Invoke-WebRequest -UseBasicParsing -TimeoutSec 5 -Uri "$url/api/auth/me"
$who = $me.Content | ConvertFrom-Json
Check 'signed in without a cookie' ($me.StatusCode -eq 200) ("{0} ({1})" -f $who.user.email, $who.user.role)
} catch {
Check 'signed in without a cookie' $false $_.Exception.Message
}
try {
$sync = Invoke-WebRequest -UseBasicParsing -TimeoutSec 15 -Uri "$url/api/sync"
Check '/api/sync answers' ($sync.StatusCode -eq 200)
} catch {
Check '/api/sync answers' $false $_.Exception.Message
}
Say ''
Say 'Window (WebView2)'
if (-not (Test-Path -LiteralPath $windowExe)) {
Say ' SKIP LuminaryWindow.exe is not in this bundle'
} else {
$window = Start-Process -FilePath $windowExe -ArgumentList @('--url', $url) -PassThru
Start-Sleep -Seconds $WindowSeconds
$window.Refresh()
$alive = -not $window.HasExited
Check 'window process alive' $alive $(if ($alive) { 'pid ' + $window.Id } else { 'exited early' })
if ($alive) {
$title = $window.MainWindowTitle
Check 'window titled Luminary' ($title -eq 'Luminary') ("title '{0}'" -f $title)
}
if (-not $window.HasExited) { Stop-Process -Id $window.Id -Force }
}
} catch {
Say (" ERROR {0}" -f $_.Exception.Message)
$script:failed += 1
} finally {
if ($window -and -not $window.HasExited) { Stop-Process -Id $window.Id -Force -ErrorAction SilentlyContinue }
if ($server -and -not $server.HasExited) { Stop-Process -Id $server.Id -Force -ErrorAction SilentlyContinue }
Remove-Item -LiteralPath $dataDir -Recurse -Force -ErrorAction SilentlyContinue
Say ''
if ($script:failed -eq 0) {
Say 'RESULT: PASS'
} else {
Say ("RESULT: FAIL ({0} check(s))" -f $script:failed)
}
try { $script:lines | Set-Content -LiteralPath (Join-Path $Bundle 'smoke-report.txt') -Encoding UTF8 } catch { }
exit $(if ($script:failed -eq 0) { 0 } else { 1 })
}
+856
View File
@@ -0,0 +1,856 @@
#!/usr/bin/env node
/**
* Build the optional Windows bundle for Luminary.
*
* This is deliberately *outside* the main build: it only reads the repository
* (`dist/`, `server/`, `package.json`) and writes everything into a directory
* outside the checkout. Nothing in `src/`, `server/`, `package.json`, the
* Dockerfile, the deploy script or `dist/` is modified by this file, and no npm
* script is added for it. Run it directly:
*
* node windows/build.mjs # build dist/ then the bundle
* node windows/build.mjs --skip-build # reuse the existing dist/
* node windows/build.mjs --out D:\lum # choose the output directory
*
* The bundle keeps the layout the server expects (it derives `DIST_DIR` from
* the parent of `server/`), so it is a plain folder plus a launcher:
*
* <out>/Luminary/
* node.exe official Node 24 win-x64, SHA-256 checked
* Luminary.cmd / .vbs PowerShell launcher (start, health wait, browser)
* Luminary.exe only when a Go toolchain builds it
* Stop Luminary.cmd
* Luminary.ps1 start/stop/status logic shared by both launchers
* app/ unchanged server/, dist/, production node_modules/
* README-windows.txt
* version.txt
*/
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import {
cpSync,
existsSync,
mkdirSync,
readFileSync,
readdirSync,
renameSync,
rmSync,
statSync,
writeFileSync,
} from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import zlib from 'node:zlib';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..');
const LAUNCHER_FILES = path.join(HERE, 'launcher');
const RELEASES_DIR = path.join(HERE, 'releases');
const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const DEFAULT_NODE = 'v24.22.2';
const HELP = `Luminary Windows bundle
Usage: node windows/build.mjs [options]
--out <dir> output directory (default: <cache>/luminary-windows).
Must be outside this repository; the bundle is staged in
<out>/stage and zipped to <out>/Luminary-<ver>-win-x64.zip.
--skip-build reuse the existing dist/ instead of running npm run build
--node <version> bundled Node version, e.g. v24.22.2 (must be >= 24)
--launcher <kind> auto (default), ps or go. "go" needs a Go toolchain and
produces Luminary.exe; "ps" always works.
--allow-dirty skip the check that the checkout is clean outside windows/
--installer also build Luminary-<ver>-win-x64-setup.exe with NSIS
(fetches a private NSIS copy on Linux if makensis is absent)
--no-installer skip the setup exe even when makensis is installed
--publish copy the finished zip and setup exe to windows/releases
(plus a SHA256SUMS.txt) so they can be transferred to a PC
--webview2 <exe> ship a prebuilt LuminaryWindow.exe (native WebView2 window).
Build it with:
docker run --rm -v $PWD/windows/launcher:/src \\
-v /tmp/wv:/out -w /src/webview2 \\
mcr.microsoft.com/dotnet/sdk:8.0 \\
dotnet publish -c Release -o /out
--help print this text
Nothing in the repository is modified: the only writes outside the output
directory are the ones npm and nodejs.org make for their own caches.
`;
function fail(message) {
process.stderr.write(`windows: FAILED: ${message}\n`);
process.exit(1);
}
function log(step, message) {
process.stdout.write(`windows: ${step.padEnd(9)} ${message}\n`);
}
function warn(message) {
process.stderr.write(`windows: warning: ${message}\n`);
}
function defaultOutDir() {
if (process.platform === 'win32') {
const base = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
return path.join(base, 'Luminary', 'build');
}
return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-windows');
}
function parseArgs(argv) {
const options = {
out: defaultOutDir(),
node: DEFAULT_NODE,
launcher: 'auto',
build: true,
allowDirty: false,
installer: 'auto',
publish: false,
webview2: null,
help: false,
};
const value = (index, flag) => {
const next = argv[index + 1];
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
return next;
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--out') {
options.out = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--node') {
const version = value(i, arg);
options.node = version.startsWith('v') ? version : `v${version}`;
i += 1;
} else if (arg === '--launcher') {
options.launcher = value(i, arg);
i += 1;
} else if (arg === '--skip-build') {
options.build = false;
} else if (arg === '--installer') {
options.installer = 'yes';
} else if (arg === '--no-installer') {
options.installer = 'no';
} else if (arg === '--allow-dirty') {
options.allowDirty = true;
} else if (arg === '--publish') {
options.publish = true;
} else if (arg === '--webview2') {
options.webview2 = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--help' || arg === '-h') {
options.help = true;
} else {
fail(`unknown option ${arg} (see --help)`);
}
}
if (!['auto', 'ps', 'go'].includes(options.launcher)) {
fail(`--launcher must be auto, ps or go (got ${options.launcher})`);
}
if (!/^v\d+\.\d+\.\d+$/.test(options.node)) {
fail(`--node must look like v24.22.2 (got ${options.node})`);
}
return options;
}
function git(args, { trim = true } = {}) {
const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' });
if (result.error || result.status !== 0) return null;
return trim ? result.stdout.trim() : result.stdout;
}
/**
* The bundle must not land in the checkout: a staged Windows Node runtime and
* node_modules would otherwise be rsynced to production by scripts/deploy.mjs
* and grow the Docker build context.
*/
function assertOutsideRepo(outDir) {
const relative = path.relative(ROOT, outDir);
const inside = !relative.startsWith('..') && !path.isAbsolute(relative);
if (inside) {
fail(
`--out resolves inside the repository (${outDir}).\n` +
'The bundle is large and would be copied by the deploy rsync; pick an\n' +
'output directory outside the checkout, or omit --out to use the cache.',
);
}
}
/**
* Only this folder may be dirty. `logo.png` is a long-standing untracked asset
* in this checkout and is not part of the app, so it is tolerated.
*/
function checkRepoClean(options) {
// Not trimmed: porcelain lines start with two status columns and a space, and
// trimming the output would eat the leading space of the first line, shifting
// its path by one character.
const status = git(['status', '--porcelain'], { trim: false });
if (status === null) {
warn('git is unavailable here; skipping the worktree check');
return;
}
const unexpected = status
.split('\n')
.filter((line) => line.length > 3)
.map((line) => line.slice(3).replace(/^"|"$/g, '').replace(/^.* -> /, '').trim())
.filter((file) => file && !file.startsWith('windows/') && file !== 'logo.png');
if (!unexpected.length) return;
if (options.allowDirty) {
warn(`building from a modified checkout: ${unexpected.join(', ')}`);
return;
}
fail(
`the checkout has changes outside windows/:\n ${unexpected.join('\n ')}\n` +
'Commit or stash them, or pass --allow-dirty to build anyway.',
);
}
function readPackage() {
const file = path.join(ROOT, 'package.json');
if (!existsSync(file)) fail('run this from a Luminary checkout (package.json missing)');
return JSON.parse(readFileSync(file, 'utf8'));
}
function run(command, args, cwd, extraEnv) {
log('run', [command, ...args].join(' '));
const result = spawnSync(command, args, {
cwd,
stdio: 'inherit',
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
});
if (result.error) fail(`${command} could not start: ${result.error.message}`);
if (result.status !== 0) fail(`${command} ${args.join(' ')} exited with ${result.status}`);
}
function ensureUi(options) {
const dist = path.join(ROOT, 'dist', 'index.html');
if (options.build) {
log('ui', 'npm run build (typecheck + vite build, the normal artifact)');
run(NPM, ['run', 'build'], ROOT);
} else {
log('ui', 'reusing the existing dist/ (--skip-build)');
}
if (!existsSync(dist)) {
fail('dist/index.html is missing; drop --skip-build or run "npm run build" first');
}
return dist;
}
function copyServer(bundle) {
const server = path.join(bundle, 'app', 'server');
cpSync(path.join(ROOT, 'server'), server, {
recursive: true,
filter: (source) => {
const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/');
// The developer catalog and the test files never belong in a bundle.
if (relative === 'data' || relative.startsWith('data/')) return false;
if (/\.test\.mjs$/.test(relative)) return false;
return true;
},
});
}
function copyLegal(bundle) {
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
const source = path.join(ROOT, name);
if (existsSync(source)) cpSync(source, path.join(bundle, name));
}
const licenses = path.join(ROOT, 'licenses');
if (existsSync(licenses)) cpSync(licenses, path.join(bundle, 'licenses'), { recursive: true });
}
/** Copies a text file with CRLF endings, which cmd.exe and PowerShell expect. */
function copyText(source, dest) {
const body = readFileSync(source, 'utf8').replace(/\r?\n/g, '\r\n');
writeFileSync(dest, body);
}
function installWindowsDeps(bundle) {
const appDir = path.join(bundle, 'app');
cpSync(path.join(ROOT, 'package.json'), path.join(appDir, 'package.json'));
cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json'));
log('deps', 'npm ci --omit=dev --os=win32 --cpu=x64 (sharp win32-x64 prebuild)');
// --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the
// prebuilt binary through optionalDependencies, and running a Windows-only
// script on the build host would fail for no reason.
run(
NPM,
[
'ci',
'--omit=dev',
'--os=win32',
'--cpu=x64',
'--no-audit',
'--no-fund',
'--ignore-scripts',
],
appDir,
);
// .bin shims are for a shell, not for `node server/index.mjs`; on a Linux
// build they would also be POSIX symlinks inside the zip.
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
verifySharp(appDir);
}
function verifySharp(appDir) {
const dir = path.join(appDir, 'node_modules', '@img', 'sharp-win32-x64');
if (!existsSync(dir)) {
warn('@img/sharp-win32-x64 is missing; the server will fall back to PNG proxies');
return;
}
const binaries = [];
const walk = (current) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) walk(absolute);
else if (/\.(node|dll)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute));
}
};
walk(dir);
if (!binaries.some((file) => file.endsWith('.node'))) {
warn('@img/sharp-win32-x64 has no .node binary; check the installed package');
} else {
log('deps', `sharp win32-x64 ready (${binaries.length} native files)`);
}
}
function sha256File(file) {
return createHash('sha256').update(readFileSync(file)).digest('hex');
}
async function download(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}`);
return Buffer.from(await response.arrayBuffer());
}
async function ensureNode(outDir, version) {
const major = Number(version.slice(1).split('.')[0]);
if (major < 24) {
fail(`Node ${version} is too old: node:sqlite and type stripping need 24 LTS`);
}
const cache = path.join(outDir, 'cache');
mkdirSync(cache, { recursive: true });
const exe = path.join(cache, `node-${version}-win-x64.exe`);
const sums = path.join(cache, `SHASUMS256-${version}.txt`);
const base = `https://nodejs.org/dist/${version}`;
if (!existsSync(exe)) {
log('node', `downloading ${base}/win-x64/node.exe`);
try {
writeFileSync(exe, await download(`${base}/win-x64/node.exe`));
} catch (error) {
fail(`could not download node.exe: ${error.message}`);
}
} else {
log('node', `using cached ${path.basename(exe)}`);
}
if (!existsSync(sums)) {
try {
writeFileSync(sums, (await download(`${base}/SHASUMS256.txt`)).toString('utf8'));
} catch (error) {
warn(`could not fetch SHASUMS256.txt (${error.message}); the cached node.exe is unverified`);
}
}
const hash = sha256File(exe);
if (existsSync(sums)) {
const line = readFileSync(sums, 'utf8')
.split('\n')
.map((row) => row.trim().split(/\s+/))
.find((row) => row[1] === 'win-x64/node.exe');
if (!line) fail(`SHASUMS256.txt for ${version} has no win-x64/node.exe entry`);
if (hash !== line[0]) {
rmSync(exe, { force: true });
fail(`node.exe failed its SHA-256 check (${hash} != ${line[0]}); re-run to download again`);
}
log('node', `${version} win-x64 verified (sha256 ${hash.slice(0, 12)}…)`);
} else {
warn(`using node.exe without a published checksum (sha256 ${hash})`);
}
return { exe, hash };
}
function goAvailable() {
const result = spawnSync('go', ['version'], { encoding: 'utf8' });
return !result.error && result.status === 0;
}
function chooseLauncher(requested) {
if (requested === 'ps') return 'ps';
if (requested === 'go') {
if (!goAvailable()) {
fail(
'--launcher go needs a Go toolchain (https://go.dev/dl/), or build the exe\n' +
'in the container: docker build -f windows/Dockerfile --output type=local,dest=<dir> .',
);
}
return 'go';
}
return goAvailable() ? 'go' : 'ps';
}
function installLauncher(bundle, kind) {
const files = ['Luminary.ps1', 'Stop Luminary.cmd'];
if (kind === 'go') {
const source = path.join(LAUNCHER_FILES, 'go');
log('launcher', 'go build -trimpath -H windowsgui (Luminary.exe)');
run(
'go',
[
'build',
'-trimpath',
'-ldflags',
'-s -w -H windowsgui',
'-o',
path.join(bundle, 'Luminary.exe'),
'.',
],
source,
{ GOOS: 'windows', GOARCH: 'amd64', CGO_ENABLED: '0' },
);
} else {
files.push('Luminary.cmd', 'Luminary.vbs');
}
for (const name of files) {
copyText(path.join(LAUNCHER_FILES, name), path.join(bundle, name));
}
// Binary icon for shortcuts and the installer; no CRLF pass on this one.
const icon = path.join(LAUNCHER_FILES, 'Luminary.ico');
if (existsSync(icon)) cpSync(icon, path.join(bundle, 'Luminary.ico'));
// The PowerShell launcher is always present: it implements the shared
// start/stop/status logic and "Stop Luminary.cmd" calls it in both modes.
log('launcher', kind === 'go' ? 'Luminary.exe' : 'Luminary.cmd + Luminary.vbs');
}
function writeVersion(bundle, pkg, launcher, nodeVersion, nodeHash, nodeSize) {
const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown';
// The hash is on the node line so the launcher can quote it verbatim when
// node.exe goes missing (antivirus) and the user needs to verify a restore.
const lines = [
`Luminary ${pkg.version}`,
`commit ${commit}`,
`built ${new Date().toISOString()}`,
`node ${nodeVersion} win-x64 sha256 ${nodeHash} size ${nodeSize}`,
`launcher ${launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd / Luminary.vbs'}`,
];
const text = `${lines.join('\n')}\n`;
writeFileSync(path.join(bundle, 'version.txt'), text);
return { version: pkg.version, commit };
}
function writeBundleReadme(bundle, info) {
const start = info.launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd (or Luminary.vbs for no console window)';
const body = `Luminary ${info.version} for Windows (x64) — portable bundle
=================================================
Start: double-click ${start}
Stop: double-click "Stop Luminary.cmd"
Open: the launcher opens http://127.0.0.1:8787 (the next free port if busy)
Data: %LOCALAPPDATA%\\Luminary\\data (originals, previews, SQLite catalog)
Logs: logs\\server.out.log and logs\\server.err.log
Check: "Luminary.cmd -Verify" lists the files a complete bundle needs
Repair: "Luminary.cmd -Repair" downloads node.exe again and verifies its sha256
Sign-in: none — single-user desktop mode, no account setup
Window: opens in its own window (native when bundled, else chromeless Edge/Chrome);
"Luminary.cmd -Browser" for a normal tab
Requirements
- Windows 10 or 11, 64-bit.
- A current browser (Edge, Chrome or Firefox) with WebGL2 for the Develop
module.
- Nothing else. Node.js is included as node.exe, and no .NET, Visual C++
Redistributable, admin rights or installer is needed.
- About 250 MB free where the data folder lives.
The first launch creates the data folder and the catalog. Nothing is installed
and nothing is written next to Windows or Program Files, so you can move this
folder anywhere (including a USB drive) as long as it stays writable.
If an antivirus removes node.exe, the launcher offers to download it on the next
start (or run "Luminary.cmd -Repair"). On Windows older than 10 the launcher
says so before starting instead of failing halfway.
Back up the catalog by copying the whole data folder while Luminary is stopped,
including lumenroom.db, lumenroom.db-wal, lumenroom.db-shm and secret.key.
Updating: stop Luminary, replace app\\ and node.exe from a newer bundle, then
start it again. The data folder is outside the bundle and is untouched.
Notes
- Extract the whole zip before running anything. A file opened from inside
the zip preview is copied out on its own and will not find node.exe.
- Windows 8.1 and older also need the Universal C Runtime (KB2999226);
Windows 10 and 11 already include it.
- This build is single-user: it creates one local admin on first start and
opens signed in. It is not meant for several people sharing one Windows
login with separate accounts.
- The bundle is unsigned, so SmartScreen may ask once ("More info" -> "Run anyway").
- The server listens on 127.0.0.1 only. Set HOST=0.0.0.0 before starting if
client proofing galleries must be reachable from other devices on the LAN.
- RAW decoding uses the bundled libraw WebAssembly; sharp's Windows prebuilt
binary is included, so there is nothing else to install.
`;
writeFileSync(path.join(bundle, 'README-windows.txt'), body.replace(/\r?\n/g, '\r\n'));
}
/* ------------------------------------------------------------------ zip ---- */
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c >>> 0;
}
return table;
})();
function crc32(buffer) {
let c = 0xffffffff;
for (let i = 0; i < buffer.length; i++) c = CRC_TABLE[(c ^ buffer[i]) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function listFiles(dir) {
const files = [];
const walk = (current) => {
const entries = readdirSync(current, { withFileTypes: true }).sort((a, b) =>
a.name.localeCompare(b.name),
);
for (const entry of entries) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) walk(absolute);
else if (entry.isFile()) files.push(absolute);
}
};
walk(dir);
return files;
}
/**
* Minimal ZIP writer (deflate, no zip64). Keeping it here avoids a dependency,
* and every entry carries the same fixed timestamp instead of inheriting the
* filesystem's, so two builds differ only by the files' own content.
*/
function writeZip(sourceDir, zipPath) {
// 2020-01-01 00:00:00 in MS-DOS date/time form.
const time = 0;
const date = (40 << 9) | (1 << 5) | 1;
const parts = [];
const central = [];
let offset = 0;
for (const absolute of listFiles(sourceDir)) {
const name = path.relative(sourceDir, absolute).split(path.sep).join('/');
const data = readFileSync(absolute);
const crc = crc32(data);
const deflated = zlib.deflateRawSync(data, { level: 9 });
const useDeflate = deflated.length < data.length;
const body = useDeflate ? deflated : data;
const method = useDeflate ? 8 : 0;
const nameBytes = Buffer.from(name, 'utf8');
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0x0800, 6); // UTF-8 names
local.writeUInt16LE(method, 8);
local.writeUInt16LE(time, 10);
local.writeUInt16LE(date, 12);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(body.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(nameBytes.length, 26);
local.writeUInt16LE(0, 28);
parts.push(local, nameBytes, body);
const entry = Buffer.alloc(46);
entry.writeUInt32LE(0x02014b50, 0);
entry.writeUInt16LE(20, 4);
entry.writeUInt16LE(20, 6);
entry.writeUInt16LE(0x0800, 8);
entry.writeUInt16LE(method, 10);
entry.writeUInt16LE(time, 12);
entry.writeUInt16LE(date, 14);
entry.writeUInt32LE(crc, 16);
entry.writeUInt32LE(body.length, 20);
entry.writeUInt32LE(data.length, 24);
entry.writeUInt16LE(nameBytes.length, 28);
entry.writeUInt16LE(0, 30);
entry.writeUInt16LE(0, 32);
entry.writeUInt16LE(0, 34);
entry.writeUInt16LE(0, 36);
entry.writeUInt32LE(0, 38);
entry.writeUInt32LE(offset, 42);
central.push(entry, nameBytes);
offset += local.length + nameBytes.length + body.length;
}
const directory = Buffer.concat(central);
const end = Buffer.alloc(22);
const count = central.length / 2;
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(0, 4);
end.writeUInt16LE(0, 6);
end.writeUInt16LE(count, 8);
end.writeUInt16LE(count, 10);
end.writeUInt32LE(directory.length, 12);
end.writeUInt32LE(offset, 16);
end.writeUInt16LE(0, 20);
writeFileSync(zipPath, Buffer.concat([...parts, directory, end]));
return { files: count, bytes: statSync(zipPath).size };
}
/* ------------------------------------------------------------- installer ---- */
function dirSizeBytes(dir) {
let total = 0;
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const absolute = path.join(dir, entry.name);
total += entry.isDirectory() ? dirSizeBytes(absolute) : statSync(absolute).size;
}
return total;
}
function cachedMakensis(outDir) {
const root = path.join(outDir, 'tools', 'nsis');
const bin = path.join(root, 'usr', 'bin', 'makensis');
if (!existsSync(bin)) return null;
return { bin, nsisdir: path.join(root, 'usr', 'share', 'nsis') };
}
function findMakensis(outDir) {
if (process.env.MAKENSIS) {
return { bin: process.env.MAKENSIS, nsisdir: process.env.NSISDIR || null };
}
const cached = cachedMakensis(outDir);
if (cached) return cached;
const which = spawnSync(process.platform === 'win32' ? 'where' : 'which', ['makensis'], {
encoding: 'utf8',
});
const found = !which.error && which.status === 0 ? which.stdout.split(/\r?\n/)[0].trim() : '';
return found ? { bin: found, nsisdir: process.env.NSISDIR || null } : null;
}
/**
* NSIS is a small cross-compiler: on Linux it produces the same .exe as it
* would on Windows. Ubuntu ships it as two .debs, which unpack into the build
* cache without root, so a fresh host can build the installer unattended.
*/
async function fetchMakensis(outDir) {
if (process.platform !== 'linux' || process.arch !== 'x64') return null;
const dpkg = spawnSync('dpkg-deb', ['--version'], { stdio: 'ignore' });
if (dpkg.error || dpkg.status !== 0) return null;
const packVersion = '3.09-4ubuntu1';
const base = 'http://archive.ubuntu.com/ubuntu/pool/universe/n/nsis';
const debs = path.join(outDir, 'cache', 'nsis-debs');
const root = path.join(outDir, 'tools', 'nsis');
mkdirSync(debs, { recursive: true });
rmSync(root, { recursive: true, force: true });
for (const name of [`nsis_${packVersion}_amd64.deb`, `nsis-common_${packVersion}_all.deb`]) {
const file = path.join(debs, name);
if (!existsSync(file)) {
try {
writeFileSync(file, await download(`${base}/${name}`));
} catch (error) {
warn(`could not download ${name} (${error.message})`);
return null;
}
}
const unpack = spawnSync('dpkg-deb', ['-x', file, root], { encoding: 'utf8' });
if (unpack.error || unpack.status !== 0) {
warn(`could not unpack ${name}: ${(unpack.stderr || '').trim() || 'dpkg-deb failed'}`);
return null;
}
}
return cachedMakensis(outDir);
}
async function resolveMakensis(outDir, required) {
const found = findMakensis(outDir);
if (found) return found;
if (!required) return null;
log('nsis', 'makensis not found; unpacking a private NSIS into the build cache');
const fetched = await fetchMakensis(outDir);
if (fetched) {
log('nsis', `NSIS ${packVersionOf(fetched.bin)} ready (no root install needed)`);
return fetched;
}
fail(
'NSIS is required for --installer and was not found.\n' +
' Ubuntu/Debian: sudo apt install nsis\n' +
' macOS: brew install makensis\n' +
' Windows: https://nsis.sourceforge.io\n' +
' or set MAKENSIS=/path/to/makensis',
);
}
function packVersionOf(makensis) {
const result = spawnSync(makensis, ['-VERSION'], { encoding: 'utf8' });
return !result.error && result.status === 0 ? result.stdout.trim() : 'unknown version';
}
function buildInstaller({ outDir, bundle, pkg, makensis }) {
const script = path.join(HERE, 'installer.nsi');
if (!existsSync(script)) fail(`installer script missing: ${script}`);
const outputDir = path.join(outDir, 'installer');
mkdirSync(outputDir, { recursive: true });
const setup = path.join(outputDir, `Luminary-${pkg.version}-win-x64-setup.exe`);
rmSync(setup, { force: true });
// NSIS wants four numeric fields; 0.5.1 -> 0.5.1.0
const fields = pkg.version.split('.').map((n) => Number(n) || 0);
while (fields.length < 4) fields.push(0);
const version4 = fields.slice(0, 4).join('.');
const installKb = Math.ceil(dirSizeBytes(bundle) / 1024);
log('installer', `makensis ${path.basename(script)} (${(installKb / 1024).toFixed(0)} MB payload)`);
run(
makensis.bin,
[
'-V2',
`-DAPP_VERSION=${pkg.version}`,
`-DAPP_VERSION4=${version4}`,
`-DSOURCE_DIR=${bundle}`,
`-DOUTPUT_DIR=${outputDir}`,
`-DICON=${path.join(LAUNCHER_FILES, 'Luminary.ico')}`,
`-DINSTALL_KB=${installKb}`,
script,
],
ROOT,
makensis.nsisdir ? { NSISDIR: makensis.nsisdir } : undefined,
);
if (!existsSync(setup)) fail('makensis reported success but produced no setup exe');
return { path: setup, bytes: statSync(setup).size };
}
/* ----------------------------------------------------------------- main ---- */
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
process.stdout.write(HELP);
return 0;
}
assertOutsideRepo(options.out);
const pkg = readPackage();
log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`);
log('out', options.out);
checkRepoClean(options);
ensureUi(options);
// Settle the launcher before anything is copied: a missing Go toolchain
// should fail in a second, not after a download and an npm install.
const launcher = chooseLauncher(options.launcher);
// Build into a sibling and swap at the end, so a failed run never replaces
// the last complete bundle with a partial tree.
const stageRoot = path.join(options.out, 'stage');
const workRoot = path.join(options.out, 'stage.next');
const bundle = path.join(workRoot, 'Luminary');
rmSync(workRoot, { recursive: true, force: true });
mkdirSync(path.join(bundle, 'app'), { recursive: true });
log('stage', 'copying dist/ and server/ (unchanged layout the server expects)');
cpSync(path.join(ROOT, 'dist'), path.join(bundle, 'app', 'dist'), { recursive: true });
copyServer(bundle);
copyLegal(bundle);
installWindowsDeps(bundle);
const node = await ensureNode(options.out, options.node);
const bundledNode = path.join(bundle, 'node.exe');
cpSync(node.exe, bundledNode);
if (statSync(bundledNode).size !== statSync(node.exe).size) {
fail('node.exe was truncated while copying it into the bundle');
}
installLauncher(bundle, launcher);
if (options.webview2) {
if (!existsSync(options.webview2)) fail(`--webview2 file not found: ${options.webview2}`);
cpSync(options.webview2, path.join(bundle, 'LuminaryWindow.exe'));
log('window', `LuminaryWindow.exe (${(statSync(options.webview2).size / 1024 / 1024).toFixed(1)} MB)`);
}
const info = writeVersion(bundle, pkg, launcher, options.node, node.hash, statSync(bundledNode).size);
writeBundleReadme(bundle, { ...info, launcher });
const zipPath = path.join(options.out, `Luminary-${pkg.version}-win-x64.zip`);
rmSync(zipPath, { force: true });
log('zip', path.basename(zipPath));
const zip = writeZip(workRoot, zipPath);
rmSync(stageRoot, { recursive: true, force: true });
renameSync(workRoot, stageRoot);
const stagedBundle = path.join(stageRoot, 'Luminary');
let installer = null;
if (options.installer !== 'no') {
const makensis = await resolveMakensis(options.out, options.installer === 'yes');
if (makensis) {
installer = buildInstaller({ outDir: options.out, bundle: stagedBundle, pkg, makensis });
log('installer', `${path.basename(installer.path)} (${(installer.bytes / 1024 / 1024).toFixed(1)} MB)`);
} else {
warn('makensis is not installed; shipping the zip only (install NSIS for the setup exe)');
}
}
// The isolation contract: nothing outside windows/ may have changed.
if (!options.allowDirty) checkRepoClean(options);
// Hand-off copy. The staging and the zip stay outside the checkout; this is
// the one write into the repository, into windows/releases, for transfer to a
// Windows machine.
let published = null;
if (options.publish) {
mkdirSync(RELEASES_DIR, { recursive: true });
const artifacts = [zipPath, ...(installer ? [installer.path] : [])];
const sums = [];
for (const artifact of artifacts) {
const target = path.join(RELEASES_DIR, path.basename(artifact));
cpSync(artifact, target);
sums.push(`${sha256File(target)} ${path.basename(target)}`);
log('publish', path.relative(ROOT, target));
}
writeFileSync(path.join(RELEASES_DIR, 'SHA256SUMS.txt'), `${sums.join('\n')}\n`);
published = path.join(RELEASES_DIR, path.basename(zipPath));
}
process.stdout.write(
[
'',
'windows build PASSED',
` artifact ${zipPath}`,
` size ${(zip.bytes / 1024 / 1024).toFixed(1)} MB (${zip.files} files)`,
` sha256 ${sha256File(zipPath)}`,
...(installer
? [
` setup ${installer.path}`,
` setup MB ${(installer.bytes / 1024 / 1024).toFixed(1)}`,
` setup sha ${sha256File(installer.path)}`,
]
: []),
` node ${options.node} win-x64`,
` launcher ${launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd / Luminary.vbs'}`,
...(options.webview2 ? [` window LuminaryWindow.exe (native WebView2)`] : []),
` staged ${stagedBundle}`,
...(published ? [` publish ${path.relative(ROOT, published)}`] : []),
'',
published
? 'Only windows/ was written: the zip in windows/releases is ready to transfer.'
: 'The repository was not modified; only windows/ and the output directory were touched.',
'',
].join('\n'),
);
return 0;
}
main().then(
(code) => {
process.exitCode = code;
},
(error) => {
fail(error instanceof Error ? error.message : String(error));
},
);
+212
View File
@@ -0,0 +1,212 @@
; Per-user installer for the Luminary Windows bundle, built with NSIS 3.
;
; NSIS runs on Linux, macOS and Windows, so the same build host that produces
; the zip also produces the setup executable:
;
; node windows/build.mjs --installer --publish
;
; or by hand, from the repository root:
;
; makensis -DAPP_VERSION=0.5.1 -DAPP_VERSION4=0.5.1.0 \
; -DSOURCE_DIR="$PWD/../.cache/stage/Luminary" windows/installer.nsi
;
; Nothing is installed for all users: no UAC prompt, no Program Files. The
; program goes to %LOCALAPPDATA%\Programs\Luminary and the catalog stays in
; %LOCALAPPDATA%\Luminary\data, which the uninstaller never touches.
Unicode true
ManifestDPIAware true
ManifestSupportedOS win10
RequestExecutionLevel user
SetCompressor /SOLID lzma
SetCompressorDictSize 32
CRCCheck on
!include "MUI2.nsh"
!include "x64.nsh"
!include "WinVer.nsh"
!ifndef APP_VERSION
!define APP_VERSION "0.5.1"
!endif
; NSIS wants four numeric fields for the exe's version resource.
!ifndef APP_VERSION4
!define APP_VERSION4 "0.5.1.0"
!endif
; Forward slashes throughout: makensis is cross-platform, and this file is
; compiled on Linux as often as on Windows.
!ifndef SOURCE_DIR
!define SOURCE_DIR "${__FILEDIR__}/stage/Luminary"
!endif
!ifndef OUTPUT_DIR
!define OUTPUT_DIR "${__FILEDIR__}/installer-output"
!endif
!ifndef ICON
!define ICON "${__FILEDIR__}/launcher/Luminary.ico"
!endif
; Size of the installed tree in KB, for Add/Remove Programs. The builder
; measures the staged bundle; the fallback is roughly right for a full build.
!ifndef INSTALL_KB
!define INSTALL_KB "250000"
!endif
!define APP_NAME "Luminary"
!define APP_PUBLISHER "Maple Street"
!define APP_URL "https://git.maple-street.net/bhursey/luminary"
!define UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\Luminary"
!define APP_KEY "Software\Luminary"
!define RUN_KEY "Software\Microsoft\Windows\CurrentVersion\Run"
Name "${APP_NAME} ${APP_VERSION}"
BrandingText "${APP_NAME} ${APP_VERSION}"
OutFile "${OUTPUT_DIR}/Luminary-${APP_VERSION}-win-x64-setup.exe"
InstallDir "$LOCALAPPDATA\Programs\Luminary"
InstallDirRegKey HKCU "${APP_KEY}" "InstallDir"
VIProductVersion "${APP_VERSION4}"
VIAddVersionKey "ProductName" "${APP_NAME}"
VIAddVersionKey "ProductVersion" "${APP_VERSION}"
VIAddVersionKey "FileDescription" "${APP_NAME} setup"
VIAddVersionKey "FileVersion" "${APP_VERSION}"
VIAddVersionKey "CompanyName" "${APP_PUBLISHER}"
VIAddVersionKey "LegalCopyright" "MIT licensed"
!define MUI_ICON "${ICON}"
!define MUI_UNICON "${ICON}"
!define MUI_ABORTWARNING
!define MUI_WELCOMEPAGE_TITLE "Install ${APP_NAME} ${APP_VERSION}"
!define MUI_WELCOMEPAGE_TEXT "This installs the Luminary desktop app for your Windows account.$\r$\n$\r$\nNo administrator rights are needed: the app goes in your own AppData folder, and the catalog, previews and originals index stay in %LOCALAPPDATA%\Luminary\data. Uninstalling keeps that folder so you never lose a catalog.$\r$\n$\r$\nNode.js, .NET and the Visual C++ runtime are not required - everything Luminary needs ships inside."
!define MUI_FINISHPAGE_TEXT "${APP_NAME} is installed.$\r$\n$\r$\nYour catalog lives in %LOCALAPPDATA%\Luminary\data. Back it up by copying that folder while Luminary is stopped.$\r$\n$\r$\nUninstalling removes the app but not the catalog."
!define MUI_FINISHPAGE_SHOWREADME "$INSTDIR\README-windows.txt"
!define MUI_FINISHPAGE_SHOWREADME_TEXT "Show the Windows readme"
!define MUI_FINISHPAGE_SHOWREADME_NOTCHECKED
!if /FileExists "${SOURCE_DIR}/Luminary.vbs"
!define MUI_FINISHPAGE_RUN "$INSTDIR\Luminary.vbs"
!else
!define MUI_FINISHPAGE_RUN "$INSTDIR\Luminary.cmd"
!endif
!define MUI_FINISHPAGE_RUN_TEXT "Start ${APP_NAME}"
!insertmacro MUI_PAGE_WELCOME
!if /FileExists "${SOURCE_DIR}/LICENSE"
!insertmacro MUI_PAGE_LICENSE "${SOURCE_DIR}/LICENSE"
!endif
!insertmacro MUI_PAGE_COMPONENTS
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English"
LangString DESC_Main ${LANG_ENGLISH} "The editor, film looks, bundled Node runtime and documentation. Required."
LangString DESC_Desktop ${LANG_ENGLISH} "Put a Luminary shortcut on the desktop."
LangString DESC_Startup ${LANG_ENGLISH} "Start Luminary in the background when you sign in to Windows."
Function .onInit
; The launcher refuses these too, but the installer should say so before it
; copies 250 MB onto an unsupported PC.
${IfNot} ${RunningX64}
MessageBox MB_ICONSTOP "${APP_NAME} needs 64-bit Windows 10 or 11. This PC is running a 32-bit copy of Windows."
Abort
${EndIf}
${IfNot} ${AtLeastWin10}
MessageBox MB_ICONSTOP "${APP_NAME} needs Windows 10 or 11. Older versions are not supported."
Abort
${EndIf}
FunctionEnd
; Stop a copy started from this folder, so an upgrade can replace node.exe and
; app\ while it is not in use. Uses the launcher's own -Stop path, which reads
; runtime.json, rather than killing every node.exe on the machine.
!macro StopRunning
${If} ${FileExists} "$INSTDIR\Luminary.ps1"
DetailPrint "Stopping a running Luminary..."
nsExec::ExecToLog 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$INSTDIR\Luminary.ps1" -Stop'
Pop $0
Sleep 1200
${EndIf}
!macroend
Section "Luminary (required)" SEC_MAIN
SectionIn RO
!insertmacro StopRunning
SetOutPath "$INSTDIR"
File /r "${SOURCE_DIR}/*.*"
CreateDirectory "$LOCALAPPDATA\Luminary\data"
WriteUninstaller "$INSTDIR\Uninstall.exe"
CreateDirectory "$SMPROGRAMS\Luminary"
!if /FileExists "${SOURCE_DIR}/Luminary.vbs"
CreateShortCut "$SMPROGRAMS\Luminary\Luminary.lnk" "$INSTDIR\Luminary.vbs" "" "$INSTDIR\Luminary.ico" 0
!else
CreateShortCut "$SMPROGRAMS\Luminary\Luminary.lnk" "$INSTDIR\Luminary.cmd" "" "$INSTDIR\Luminary.ico" 0
!endif
CreateShortCut "$SMPROGRAMS\Luminary\Stop Luminary.lnk" "$INSTDIR\Stop Luminary.cmd" "" "$INSTDIR\Luminary.ico" 0
CreateShortCut "$SMPROGRAMS\Luminary\Luminary data folder.lnk" "$LOCALAPPDATA\Luminary\data" "" "$INSTDIR\Luminary.ico" 0
WriteRegStr HKCU "${APP_KEY}" "InstallDir" "$INSTDIR"
WriteRegStr HKCU "${APP_KEY}" "Version" "${APP_VERSION}"
WriteRegStr HKCU "${UNINST_KEY}" "DisplayName" "${APP_NAME}"
WriteRegStr HKCU "${UNINST_KEY}" "DisplayVersion" "${APP_VERSION}"
WriteRegStr HKCU "${UNINST_KEY}" "Publisher" "${APP_PUBLISHER}"
WriteRegStr HKCU "${UNINST_KEY}" "URLInfoAbout" "${APP_URL}"
WriteRegStr HKCU "${UNINST_KEY}" "DisplayIcon" "$INSTDIR\Luminary.ico"
WriteRegStr HKCU "${UNINST_KEY}" "InstallLocation" "$INSTDIR"
WriteRegStr HKCU "${UNINST_KEY}" "UninstallString" '"$INSTDIR\Uninstall.exe"'
WriteRegStr HKCU "${UNINST_KEY}" "QuietUninstallString" '"$INSTDIR\Uninstall.exe" /S'
WriteRegDWORD HKCU "${UNINST_KEY}" "EstimatedSize" ${INSTALL_KB}
WriteRegDWORD HKCU "${UNINST_KEY}" "NoModify" 1
WriteRegDWORD HKCU "${UNINST_KEY}" "NoRepair" 1
SectionEnd
Section "Desktop shortcut" SEC_DESKTOP
!if /FileExists "${SOURCE_DIR}/Luminary.vbs"
CreateShortCut "$DESKTOP\Luminary.lnk" "$INSTDIR\Luminary.vbs" "" "$INSTDIR\Luminary.ico" 0
!else
CreateShortCut "$DESKTOP\Luminary.lnk" "$INSTDIR\Luminary.cmd" "" "$INSTDIR\Luminary.ico" 0
!endif
SectionEnd
Section "Start Luminary when I sign in" SEC_STARTUP
!if /FileExists "${SOURCE_DIR}/Luminary.vbs"
WriteRegStr HKCU "${RUN_KEY}" "Luminary" '"$INSTDIR\Luminary.vbs"'
!else
WriteRegStr HKCU "${RUN_KEY}" "Luminary" '"$INSTDIR\Luminary.cmd"'
!endif
SectionEnd
!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_MAIN} $(DESC_Main)
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_DESKTOP} $(DESC_Desktop)
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_STARTUP} $(DESC_Startup)
!insertmacro MUI_FUNCTION_DESCRIPTION_END
Section "Uninstall"
!insertmacro StopRunning
Delete "$SMPROGRAMS\Luminary\Luminary.lnk"
Delete "$SMPROGRAMS\Luminary\Stop Luminary.lnk"
Delete "$SMPROGRAMS\Luminary\Luminary data folder.lnk"
RMDir "$SMPROGRAMS\Luminary"
Delete "$DESKTOP\Luminary.lnk"
DeleteRegValue HKCU "${RUN_KEY}" "Luminary"
DeleteRegKey HKCU "${UNINST_KEY}"
DeleteRegKey HKCU "${APP_KEY}"
; %LOCALAPPDATA%\Luminary\data is deliberately outside $INSTDIR, so this
; only removes the program, its logs and its runtime marker.
RMDir /r "$INSTDIR"
IfSilent uninstallDone
MessageBox MB_ICONINFORMATION|MB_OK "${APP_NAME} was removed.$\r$\n$\r$\nYour catalog in $LOCALAPPDATA\Luminary\data was kept: delete that folder yourself if you no longer want it."
uninstallDone:
SectionEnd
+388
View File
@@ -0,0 +1,388 @@
# Windows launcher design
The launcher is not part of the app: it only chooses a port, sets environment
variables the server already reads, starts `node.exe`, and gets the user to the
browser. Nothing here requires a change to `server/` or `src/`.
Two implementations ship from the same rules:
| File | Built when | Process lifetime | Console |
| --- | --- | --- | --- |
| `Luminary.ps1` + `Luminary.cmd` / `Luminary.vbs` | always (no toolchain) | launcher exits after the browser opens, node keeps running | none via `.vbs`, brief via `.cmd` |
| `go/main.go` → `Luminary.exe` | a Go toolchain is present (`--launcher go`, or automatically under `windows/Dockerfile`) | launcher stays alive, removes its state file when the server exits | none (`-H windowsgui`) |
`Luminary.ps1` is always included because `Stop Luminary.cmd` calls it in both
modes.
## Bundle layout the launcher assumes
```
Luminary\
node.exe
Luminary.exe | Luminary.cmd / Luminary.vbs
Luminary.ps1
Stop Luminary.cmd
runtime.json (created at run time)
logs\server.out.log
logs\server.err.log
logs\launcher.log (Go launcher only)
app\server\index.mjs
app\dist\
app\node_modules\
```
`root` is the folder containing the launcher executable/script, never the
current working directory, so shortcuts and "Run as administrator" behave the
same.
## 1. Single instance
There is no mutex and no named object. The state file `runtime.json` records
`{ pid, port, url, data, started }`, and **health is the liveness test**:
```
runtime.json exists
└─ GET http://127.0.0.1:<port>/api/health == 200 ?
yes → open the browser on that URL, exit 0 (do not start a second server)
no → stale entry: start a new server and overwrite runtime.json
```
Why not check the PID: Windows reuses PIDs, and `os.FindProcess`/`Get-Process`
can succeed for an unrelated process. A health response from the recorded port
also proves the port belongs to *this* server instance.
Why not a lock file: a crashed server must not lock the user out. The health
probe self-heals in one request.
A second launch while the first server is still booting waits for it instead of
racing:
```
runtime.json pid is alive but health is not up yet
└─ poll /api/health for up to 120 s
ok → open the browser, exit 0 (no second server, no second port)
dead → that boot crashed; fall through and start a fresh server
alive but still unhealthy after 120 s → dialog with the log location, exit 1
```
The PID is only used to ask "is a boot in progress?", never as proof of life on
its own: health still decides whether the recorded server is usable. Two
launches landing within the same millisecond can both pass the check before
either writes `runtime.json`; they then bind different ports and both serve the
same catalog (SQLite WAL tolerates that). A mutex with stale-lock recovery would
close that window, at the cost of a failure mode where a crashed boot locks the
user out; for a desktop launcher a second browser tab is the better trade.
## 2. Port policy
- Preference order: `8787`, then `8788` … `8887` (100 candidates).
- A port is taken if a `TcpListener` cannot bind it on `127.0.0.1`
(PowerShell) / `net.Listen("tcp", "127.0.0.1:<port>")` (Go).
- The chosen port is passed as `PORT`; the server already reads it
(`server/config.mjs`), and the browser URL is built from the same value.
- Ports are never inherited from the environment: a stale `PORT` exported by a
shell must not make the launcher open the wrong URL.
- **Loopback only:** `HOST=127.0.0.1` avoids the Windows Firewall prompt and the
app is a single-user desktop install. For LAN proofing galleries the user sets
`HOST=0.0.0.0` in the environment before starting, or edits `Luminary.ps1` —
documented, not the default.
## 3. Data directory
Precedence, first match wins:
1. `LUMINARY_DATA` — already exported (a power user or an installer can pin it).
2. `%LOCALAPPDATA%\Luminary\data`.
3. `%USERPROFILE%\AppData\Local\Luminary\data` if `LOCALAPPDATA` is empty.
Never inside `app\`: an update replaces `app\` wholesale, and `%ProgramFiles%`
is read-only for a non-admin user. The launcher creates the directory with
`MkdirAll`/`New-Item -Force` before starting the server; the server also creates
it, but a clear write failure from the launcher is a better error than a stack
trace in a hidden log.
The folder holds the SQLite catalog (plus `-wal`/`-shm`), `secret.key` and all
image folders. Backups copy this folder while the server is stopped.
When the bundle folder is not writable (write-protected USB, `%ProgramFiles%`
for a non-admin user) two things move into the data folder: `runtime.json` and
the `logs` folder. The launcher probes the bundle folder with a throwaway file
before choosing, so checklist case 6 still starts.
## 4. Environment contract
Only variables the server already understands are set:
| Variable | Value |
| --- | --- |
| `PORT` | chosen port |
| `HOST` | `127.0.0.1` |
| `NODE_ENV` | `production` |
| `LUMINARY_DATA` | resolved data directory |
`LUMINARY_INVITE`, SMTP, quota and bridge settings are left alone; they are
admin-editable in the UI or set by a power user in the environment.
The child inherits the rest of the environment (`Start-Process` and
`cmd.Env = append(os.Environ(), …)`).
## 5. Start and health wait
```
create data dir → create log dir → pick port → spawn node.exe (hidden)
→ write runtime.json
→ poll /api/health every 700 ms, up to 120 s
ok → open http://127.0.0.1:<port> and return
fail → print/record the last 20 lines of stderr, kill the child,
remove runtime.json, exit 1
```
- 120 s covers a Defender scan of `node.exe` plus `libraw.wasm` on a cold boot.
- The poll interval is short enough that a warm start feels instant (usually the
second or third attempt).
- The PowerShell launcher checks `$process.HasExited` first, so a crash reports
the log instead of waiting the full timeout.
- The browser is opened only after health succeeds; opening earlier shows a
connection error on slow machines.
Logs are append-only: `logs\server.out.log` and `logs\server.err.log` from the
child, `logs\launcher.log` from the Go launcher. They fall back to
`<data>\logs` when the bundle folder is read-only. Rotation is not implemented;
the files are small (startup lines plus request errors) and a support note says
they can be deleted while the server is stopped.
## 6. Stop
`Stop Luminary.cmd` → `Luminary.ps1 -Stop`:
1. Read `runtime.json`; if absent or the process is gone → "not running"
(exit 0, idempotent).
2. `taskkill /PID <pid> /T /F` — `/T` also covers any helper processes, `/F`
because the server has no shutdown hook to answer a polite close.
3. Delete `runtime.json`.
Because `runtime.json` is written only after a successful spawn, Stop never
kills an unrelated process **unless** the file is stale and the PID has been
reused. The window is tiny; the health probe in the start path avoids creating
that state, and a support note explains deleting `runtime.json` by hand.
With the Go launcher, Stop kills the child, `cmd.Wait()` returns, the launcher
removes `runtime.json` itself and exits 0. The launcher never outlives the
server.
## 7. Status
`Luminary.ps1 -Status` prints PID, URL, health state and the data directory.
Useful for support without opening Task Manager.
## 8. Upgrade flow
1. `Stop Luminary.cmd`.
2. Replace `app\` (and `node.exe` if the bundle ships a newer runtime) from the
new bundle. Keep `runtime.json`, `logs\` and the data folder.
3. Start again. The server migrates the SQLite schema on boot.
The launcher does not version-check; `version.txt` in the bundle root records
the Luminary version, commit and Node version for support.
## 9. Incomplete bundle diagnostics
The launcher is a few files next to a large `app\` tree, so the three realistic
failure modes are a zip that was opened instead of extracted, an antivirus that
quarantined `node.exe`, and a launcher copied out of the source tree. All three
look identical from the outside ("node.exe is missing"), so the launcher checks
`node.exe`, `app\server\index.mjs` and `app\dist\index.html`, treats zero-byte
files as missing, and prints the fix for each cause:
| Entry point | Behaviour |
| --- | --- |
| `Luminary.cmd -Verify` | prints the bundle path, each required file with its size, the version from `version.txt`, and exits `3` on a problem |
| `Luminary.cmd` | same diagnosis on stderr/stdout, then exits `3` instead of pretending to start |
| `Luminary.vbs` | a message box before PowerShell is even started, because a silent exit would look like nothing happened |
| `Luminary.exe` | a `MessageBoxW` dialog (it is linked with `-H windowsgui`, so there is no console) and a line in `logs\launcher.log` |
`version.txt` records `node <version> win-x64 sha256 <hash> size <bytes>`, so the
help text can quote the exact hash the build verified against nodejs.org, and
the launcher can spot a truncated file by size without hashing 94 MB on every
launch.
## 10. Preflight checks
`Test-Platform` runs before the runtime is resolved, and `-Status` prints the
same report. It checks only what the bundle actually needs — taken from the
shipped binaries' PE imports, not from a generic checklist:
| Check | Source | Result |
| --- | --- | --- |
| Windows 10+ | `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\CurrentBuild` ≥ 10240 | blocking dialog, exit 4 |
| 64-bit | `PROCESSOR_ARCHITECTURE` is `AMD64` or `ARM64` | blocking dialog, exit 4 |
| Universal C Runtime | `%SystemRoot%\System32\ucrtbase.dll` | blocking dialog with the KB2999226 link |
| free space on the data drive | `DriveInfo.AvailableFreeSpace` | note below 2 GB, blocking below 200 MB |
| ARM64 | `PROCESSOR_ARCHITECTURE` | note: x64 emulation, slower RAW decode |
Why the list is this short:
- `node.exe` imports only system DLLs (KERNEL32, ADVAPI32, WS2_32, CRYPT32,
USER32, …) and links the C runtime statically, so the Visual C++
Redistributable is **not** required. Checked with `objdump -p` on the bundled
binary.
- `libvips-42.dll` imports the UCRT (`api-ms-win-crt-*`), which ships with
Windows 10/11. It does not import `vcruntime140.dll` or `msvcp140.dll`.
- The only native modules in the bundle are sharp's three files plus
`libraw.wasm`; SQLite comes from `node:sqlite`, not a native addon.
- PowerShell 5.1 is part of Windows 10/11, and the `.vbs` entry point checks for
it explicitly before launching anything.
The launcher cannot install a Windows update, so a missing UCRT is explained
with its KB number and URL rather than "fixed". The one artefact it can fetch
itself is `node.exe`: `-Repair` does it, and a launch with no usable runtime
offers the same download in a Yes/No dialog.
## 11. Desktop mode and the app window
Both launchers set `LUMINARY_LOCAL=1`; nothing else does.
| Behaviour | Effect |
| --- | --- |
| boot | `prepareLocalOwner()` creates `local@luminary` (random password, admin) when missing |
| request with no session | `currentUser()` returns the local owner |
| `GET /api/auth/me` | 200, so the UI never shows the signup or sign-in view |
| `POST /api/auth/register` | 403 |
| `POST /api/auth/login` | returns the local session, so a stale login form cannot trap the user |
| edit/delete the local owner | 403, it is launcher-managed |
| `HOST` not loopback | a warning at boot; the random password means there is nothing to guess |
The app window uses the browser already on the machine:
```
msedge.exe --app=http://127.0.0.1:<port>
--user-data-dir=%LOCALAPPDATA%\Luminary\data\window-profile
--window-size=1500,950 --no-first-run --no-default-browser-check
```
`--app` removes tabs, the address bar and the browser chrome; the separate
profile keeps the app out of the user's normal history and bookmarks.
Window preference, first match wins:
1. `LuminaryWindow.exe` in the bundle root — a WinForms + WebView2 host with its
own icon, taskbar entry and window state (`--url <url>`). Built from
`launcher/webview2` with the .NET 8 SDK, published self-contained, so the
target machine needs no .NET; it does need the WebView2 runtime, which ships
with Windows 10/11 alongside Edge. Missing runtime → a dialog with the
Evergreen link, not a silent exit.
2. Edge `--app`, then Chrome `--app`.
3. The default browser (`-Browser` / `LUMINARY_WINDOW=browser` forces this).
The wrapper is only a window: node stays a child of the launcher, Stop still
uses `runtime.json`, and the browser window remains the fallback when the exe
is absent or fails to start. A direct launch without `--url` forwards to the
bundle launcher and exits immediately; that closes the old hole where
double-clicking the window opened port 8787 directly and showed a login page
(or a dead URL) because no desktop-mode server was running. The handoff prefers
the Go `Luminary.exe`, then runs `Luminary.ps1` in a hidden PowerShell process;
it does not use `Luminary.vbs`, because Windows Script Host can be disabled on
managed machines even when the bundle is healthy.
## 12. Runtime resolution and repair
Three states, checked in order:
| Bundled `node.exe` | Runtime used | What the user sees |
| --- | --- | --- |
| present, size matches the pin | `node.exe` | nothing |
| missing, empty, or wrong size | system Node 24+ from PATH, `%ProgramFiles%\nodejs`, `%ProgramFiles(x86)%\nodejs`, `%LOCALAPPDATA%\Programs\nodejs`, `%NVM_SYMLINK%` | a warning line and one information dialog naming the path, with the repair command |
| neither | none | error dialog listing the three causes, exit 3 |
The fallback is deliberately not silent: an app quietly running a different
runtime is a support mystery, and the user should be told to run `-Repair`.
Node below 24 is rejected because `server/denoise-worker.mjs` imports a `.ts`
module, which needs the type-stripping runtime.
`-Repair` (PowerShell and `Luminary.exe -repair`) does the following:
1. refuses while the server is running — the file is locked, and replacing a
runtime under a live process is wrong anyway;
2. reads the version and hash from `version.txt`, falling back to
`nodejs.org/dist/v<version>/SHASUMS256.txt` when the bundle predates the hash
line;
3. downloads to a temp file (`LUMINARY_NODE_URL` overrides the URL for a mirror
or an air-gapped copy);
4. hashes the download and refuses to install anything that does not match the
pin — a corporate proxy's HTML error page never becomes `node.exe`;
5. replaces `node.exe` atomically (`node.exe.new` + rename) and re-runs the
bundle check.
## 13. Security notes
- Binds loopback by default; no firewall rule is needed.
- Everything runs as the logged-in user; the installer is per-user, no UAC.
- The launcher is unsigned, so SmartScreen may warn on first run. Signing the
launcher (and ideally `node.exe` provenance) is a distribution task, not a
code one.
- The data folder is protected by normal user-profile ACLs.
## 14. Known limitations and phase 2
- **No tray icon.** Closing the browser does not stop the server; Stop is a
shortcut. A tray build needs `Shell_NotifyIcon` (Go with Win32 calls, or C#),
roughly a day of work, and can be swapped in without touching the app.
- **No auto-update.** Replacing `app\` is manual. An updater would read a
version manifest next to the release and download a zip.
- **No service mode.** Running before login needs WinSW/NSSM and a fixed
account/data directory; that is a different install profile, not a launcher
change.
- **Localhost only.** Multi-device proofing galleries need `HOST=0.0.0.0` and a
firewall rule; that is deliberate for a default desktop install.
## 15. Test checklist (Windows VM, no Node installed)
1. Fresh double-click → data folder created, browser opens, login page loads.
2. Second double-click → the running instance is reused and the browser opens;
no second process, whether the first server is answering or still booting.
3. `Stop Luminary.cmd` → process gone, `runtime.json` removed, Stop again says
"not running".
4. Kill node.exe in Task Manager, start again → new port if the old one is held,
otherwise the same port, and the catalog is intact.
5. Port 8787 occupied by another app → launcher uses 8788 and opens that URL.
6. Read-only install folder (Program Files) with data in `%LOCALAPPDATA%` →
starts fine (data path is outside the bundle).
7. RAW import, denoise (proves the `.ts` worker), export — i.e. the server is
fully functional from the bundle.
8. Path with spaces and non-ASCII characters (e.g. `C:\Users\Zoë\Luminary`) →
the quoted entry point and `-WorkingDirectory` still work.
9. Power loss / hard reboot → stale `runtime.json` is ignored and replaced.
10. Delete `node.exe`, then `Luminary.cmd -Verify` → exit code 3 and the three
causes; `Luminary.vbs` → message box instead of a silent no-op.
11. Run `Luminary.cmd` from inside the zip preview → the "not a complete
bundle" message, not a missing-file crash.
12. On a machine with Node 24 installed: delete `node.exe` → the launcher warns,
starts on the system Node and `-Status` names that path; `-Stop` still works.
13. Double-click `LuminaryWindow.exe` with no arguments on a machine where
VBScript is disabled → it exits, the hidden PowerShell launcher starts
desktop mode, and the reopened window is signed in; no login screen and no
Windows Script Host error appear.
14. On a machine with no Node: delete `node.exe` → the launch offers the 90 MB
download; Yes installs and starts, No exits 3; `-Repair` works as well.
15. Truncate `node.exe` (keep the first 100 kB) → `-Verify` reports `damaged`,
and `-Repair` replaces it. A partial file is the usual antivirus outcome.
16. `-Repair` while the server is running → refused with the stop instruction.
17. Write-protect the bundle folder (or use `%ProgramFiles%` without admin) →
`runtime.json` and `logs` move to the data folder and the app starts.
18. Clean Windows 10/11 VM with no Node, no .NET and no VC++ redistributable →
the app starts (proves the import analysis above); `-Status` reports the
build, architecture and Node source.
19. Windows 8.1 (if available) → the UCRT dialog with the KB2999226 link;
Windows 7 → the "needs Windows 10 or 11" dialog, exit 4.
20. Fresh data folder → no signup and no sign-in screen; the app is signed in
as Local, with no account pill in the top bar and no team/admin entry.
21. Restart → the same local account and catalog; delete the data folder →
a fresh one with no prompt.
22. Default launch → chromeless window, no address bar, own window size;
`-Browser` → a normal tab.
23. Start the server by hand with `HOST=0.0.0.0` and `LUMINARY_LOCAL=1` → the
boot log warns that every client is the local admin.
24. Bundle with `LuminaryWindow.exe` → native window with the Luminary icon in
the title bar and taskbar; `Stop Luminary.cmd` still ends the server.
25. Remove the WebView2 runtime (or use an image without it) → the native
window shows the download link instead of disappearing.
+12
View File
@@ -0,0 +1,12 @@
@echo off
rem Start Luminary and open it in the default browser.
rem The server keeps running in the background; use "Stop Luminary.cmd" to stop it.
rem
rem Luminary.cmd start
rem Luminary.cmd -Verify list the files the bundle must contain
rem Luminary.cmd -Status report pid, url, runtime and data folder
rem Luminary.cmd -Repair download node.exe again and verify its sha256
rem Luminary.cmd -Stop stop the server started from this folder
rem Luminary.cmd -Browser open a normal browser tab instead of the app window
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Luminary.ps1" %*
if errorlevel 1 pause
Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

+648
View File
@@ -0,0 +1,648 @@
<#
Luminary launcher (PowerShell).
This is the no-toolchain launcher: it ships in every bundle and is what
Luminary.exe replaces when a Go build is available. It owns the three things
the server deliberately does not do for itself:
1. Pick a free loopback port and pass it as PORT.
2. Start node.exe hidden with LUMINARY_DATA outside the bundle.
3. Wait for /api/health before opening the browser.
Usage:
Luminary.ps1 start (or reuse) the server and open the browser
Luminary.ps1 -Stop stop the server started from this folder
Luminary.ps1 -Status report what is running and where the data lives
Luminary.ps1 -Verify list the files the bundle must contain
Luminary.ps1 -Repair re-download node.exe and check it against version.txt
Luminary.ps1 -Browser open a normal browser tab instead of the app window
Runtime resolution: the bundled node.exe is always preferred. If an antivirus
removed it, a system Node 24+ is used instead so the app still starts, and the
launcher says so; -Repair restores the pinned runtime.
State is kept in runtime.json next to this script; logs go to logs\ (or to
%LOCALAPPDATA%\Luminary\data\logs when the bundle is on read-only media).
#>
[CmdletBinding()]
param(
[switch]$Stop,
[switch]$Status,
[switch]$Verify,
[switch]$Repair,
[switch]$Browser
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
$appDir = Join-Path $root 'app'
$nodeExe = Join-Path $root 'node.exe'
$entry = Join-Path $appDir 'server\index.mjs'
$uiFile = Join-Path $appDir 'dist\index.html'
$versionFile = Join-Path $root 'version.txt'
$logDir = Join-Path $root 'logs'
$runtimeFile = $null # resolved below: it moves to the data folder on read-only media
$firstPort = 8787
$lastPort = 8887
$minNodeMajor = 24
function Show-Dialog([string]$text, [string]$icon) {
try {
Add-Type -AssemblyName System.Windows.Forms
$kind = [System.Windows.Forms.MessageBoxIcon]::Information
if ($icon -eq 'Error') { $kind = [System.Windows.Forms.MessageBoxIcon]::Error }
[void][System.Windows.Forms.MessageBox]::Show($text, 'Luminary', [System.Windows.Forms.MessageBoxButtons]::OK, $kind)
} catch {
Write-Host $text
}
}
function Show-ErrorDialog([string]$text) {
# The .vbs entry point runs PowerShell hidden, so a console-only failure would
# look like nothing happened.
Show-Dialog $text 'Error'
}
function Show-Question([string]$text) {
try {
Add-Type -AssemblyName System.Windows.Forms
$answer = [System.Windows.Forms.MessageBox]::Show($text, 'Luminary', [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Question)
return ($answer -eq [System.Windows.Forms.DialogResult]::Yes)
} catch {
Write-Host $text
return $false
}
}
function Get-DataDir {
if ($env:LUMINARY_DATA) { return $env:LUMINARY_DATA }
$base = $env:LOCALAPPDATA
if (-not $base) {
if ($env:USERPROFILE) {
$base = Join-Path $env:USERPROFILE 'AppData\Local'
} else {
# Neither variable is set: a stripped environment (service account, CI)
# rather than a normal desktop login. Never Join-Path a null.
$base = [System.IO.Path]::GetTempPath()
}
}
return (Join-Path $base 'Luminary\data')
}
function Read-Runtime {
if (-not (Test-Path -LiteralPath $runtimeFile)) { return $null }
try { return Get-Content -Raw -LiteralPath $runtimeFile | ConvertFrom-Json } catch { return $null }
}
function Test-Health([int]$port) {
try {
$response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 2 -Uri ("http://127.0.0.1:{0}/api/health" -f $port)
return ($response.StatusCode -eq 200)
} catch { return $false }
}
function Test-Process([int]$processId) {
try { return $null -ne (Get-Process -Id $processId -ErrorAction Stop) } catch { return $false }
}
function Test-PortFree([int]$port) {
$listener = $null
try {
$listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Loopback, $port)
$listener.Start()
return $true
} catch {
return $false
} finally {
if ($listener) { $listener.Stop() }
}
}
function Find-Port {
for ($port = $firstPort; $port -le $lastPort; $port++) {
if (Test-PortFree $port) { return $port }
}
throw ("No free TCP port between {0} and {1}." -f $firstPort, $lastPort)
}
function Open-Browser([string]$url) {
try { Start-Process $url | Out-Null } catch { Write-Host ("Open {0} in a browser." -f $url) }
}
# Edge is part of Windows 10/11, so a chromeless app window costs no extra
# runtime. Chrome is the second choice; anything else falls back to a tab.
function Find-AppWindowBrowser {
$candidates = @()
if (${env:ProgramFiles(x86)}) {
$candidates += (Join-Path ${env:ProgramFiles(x86)} 'Microsoft\Edge\Application\msedge.exe')
}
if ($env:ProgramFiles) {
$candidates += (Join-Path $env:ProgramFiles 'Microsoft\Edge\Application\msedge.exe')
}
if ($env:LOCALAPPDATA) {
$candidates += (Join-Path $env:LOCALAPPDATA 'Microsoft\Edge\Application\msedge.exe')
$candidates += (Join-Path $env:LOCALAPPDATA 'Google\Chrome\Application\chrome.exe')
}
if ($env:ProgramFiles) {
$candidates += (Join-Path $env:ProgramFiles 'Google\Chrome\Application\chrome.exe')
}
if (${env:ProgramFiles(x86)}) {
$candidates += (Join-Path ${env:ProgramFiles(x86)} 'Google\Chrome\Application\chrome.exe')
}
foreach ($candidate in $candidates) {
if ($candidate -and (Test-Path -LiteralPath $candidate)) { return $candidate }
}
return $null
}
# --app gives a window with no tabs and no address bar, in its own profile, so
# it reads as a desktop app rather than a web page. -Browser opts out.
function Open-App([string]$url) {
if ($Browser -or $env:LUMINARY_WINDOW -eq 'browser') {
Open-Browser $url
return
}
# A native WebView2 host, when the bundle ships one, is the real app window:
# its own icon, no browser branding at all.
$native = Join-Path $root 'LuminaryWindow.exe'
if (Test-Path -LiteralPath $native) {
try {
Start-Process -FilePath $native -ArgumentList @('--url', $url) | Out-Null
return
} catch {
# fall through to the browser window
}
}
$exe = Find-AppWindowBrowser
if (-not $exe) {
Open-Browser $url
return
}
$profile = Join-Path (Get-DataDir) 'window-profile'
try {
New-Item -ItemType Directory -Force -Path $profile | Out-Null
Start-Process -FilePath $exe -ArgumentList @(
"--app=$url",
"--user-data-dir=$profile",
'--window-size=1500,950',
'--no-first-run',
'--no-default-browser-check',
'--disable-features=Translate'
) | Out-Null
} catch {
Open-Browser $url
}
}
function Get-WindowsBuild {
try {
$current = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction Stop
return [int]$current.CurrentBuild
} catch { return 0 }
}
# What a customer machine actually needs. Everything else is in the bundle:
# node.exe ships with it (and -Repair re-downloads it), libvips needs only the
# Universal C Runtime that Windows 10/11 already has, and no admin rights are
# involved. Verified against the PE imports of node.exe and libvips-42.dll.
function Test-Platform {
$problems = @()
$notes = @()
$build = Get-WindowsBuild
if ($build -gt 0 -and $build -lt 10240) {
$problems += ("Luminary needs Windows 10 or 11. This PC reports build {0}." -f $build)
}
$arch = $env:PROCESSOR_ARCHITECTURE
if ($arch -and $arch -ne 'AMD64' -and $arch -ne 'ARM64') {
$problems += ("Luminary ships a 64-bit runtime; this PC reports '{0}'." -f $arch)
} elseif ($arch -eq 'ARM64') {
$notes += 'ARM64 Windows runs the x64 runtime under emulation, so RAW decoding is slower.'
}
if ($env:SystemRoot -and -not (Test-Path -LiteralPath (Join-Path $env:SystemRoot 'System32\ucrtbase.dll'))) {
$problems += 'The Universal C Runtime is missing (Windows 8.1 without KB2999226). Install it from support.microsoft.com/help/2999226, or use Windows 10/11.'
}
# ~130 MB unpacked, plus room for catalogs and previews that grow over time.
$dataDir = Get-DataDir
$qualifier = $null
try { $qualifier = Split-Path -Qualifier $dataDir -ErrorAction Stop } catch { }
if ($qualifier) {
try {
$drive = New-Object System.IO.DriveInfo -ArgumentList $qualifier
$freeGb = [math]::Round($drive.AvailableFreeSpace / 1GB, 1)
if ($drive.AvailableFreeSpace -lt 200MB) {
$problems += ("The data drive has only {0} GB free; Luminary needs about 0.25 GB to start." -f $freeGb)
} elseif ($drive.AvailableFreeSpace -lt 2GB) {
$notes += ("Only {0} GB free on the data drive; catalogs and previews grow from there." -f $freeGb)
}
} catch { }
}
return @{ ok = ($problems.Count -eq 0); problems = $problems; notes = $notes }
}
# --- runtime resolution -------------------------------------------------------
function Read-NodePin {
$pin = @{ version = $null; sha256 = $null; size = [int64]0 }
if (-not (Test-Path -LiteralPath $versionFile)) { return $pin }
$line = Get-Content -LiteralPath $versionFile |
Where-Object { $_ -match '^node\s+v?\d+\.\d+\.\d+\s+win-x64' } |
Select-Object -First 1
if (-not $line) { return $pin }
if ($line -match '^node\s+v?(\d+\.\d+\.\d+)') { $pin.version = $Matches[1] }
if ($line -match 'sha256\s+([0-9a-f]{64})') { $pin.sha256 = $Matches[1] }
if ($line -match 'size\s+(\d+)') { $pin.size = [int64]$Matches[1] }
return $pin
}
function Get-SystemNode([string]$exe) {
if (-not $exe) { return $null }
if (-not (Test-Path -LiteralPath $exe)) { return $null }
try { $raw = & $exe '--version' 2>$null } catch { return $null }
if (-not $raw) { return $null }
$raw = "$raw".Trim()
if ($raw -notmatch '^v?(\d+)\.') { return $null }
if ([int]$Matches[1] -lt $minNodeMajor) { return $null }
return $raw
}
# The bundled runtime wins; a system Node 24+ is a fallback, never a preference.
function Resolve-Node {
if (Test-Path -LiteralPath $nodeExe) {
$info = Get-Item -LiteralPath $nodeExe
$pin = Read-NodePin
$intact = $info.Length -gt 0
# A pinned size catches a truncated file that antivirus left behind; the
# hash itself is only checked by -Verify and -Repair.
if ($intact -and $pin.size -gt 0 -and $info.Length -ne $pin.size) { $intact = $false }
if ($intact) { return @{ path = $nodeExe; version = 'bundled'; system = $false } }
}
$candidates = @()
$onPath = Get-Command node.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if ($onPath) { $candidates += $onPath.Source }
if ($env:ProgramFiles) { $candidates += (Join-Path $env:ProgramFiles 'nodejs\node.exe') }
if (${env:ProgramFiles(x86)}) { $candidates += (Join-Path ${env:ProgramFiles(x86)} 'nodejs\node.exe') }
if ($env:LOCALAPPDATA) { $candidates += (Join-Path $env:LOCALAPPDATA 'Programs\nodejs\node.exe') }
if ($env:NVM_SYMLINK) { $candidates += (Join-Path $env:NVM_SYMLINK 'node.exe') }
$seen = @{}
foreach ($candidate in $candidates) {
if (-not $candidate) { continue }
$key = $candidate.ToLowerInvariant()
if ($seen.ContainsKey($key)) { continue }
$seen[$key] = $true
$version = Get-SystemNode $candidate
if ($version) { return @{ path = $candidate; version = $version; system = $true } }
}
return $null
}
# --- repair -------------------------------------------------------------------
function Get-PublishedHash([string]$version) {
$uri = "https://nodejs.org/dist/v$version/SHASUMS256.txt"
$text = (Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 -Uri $uri).Content
foreach ($line in ($text -split "`n")) {
$parts = $line.Trim() -split '\s+'
if ($parts.Count -ge 2 -and $parts[1] -eq 'win-x64/node.exe') { return $parts[0].ToLowerInvariant() }
}
return $null
}
function Repair-Node {
$pin = Read-NodePin
if (-not $pin.version) {
throw "version.txt does not record a node version, so there is nothing to re-download. Extract the zip again instead."
}
$expected = $pin.sha256
if (-not $expected) {
Write-Host ("Fetching the published checksum for node v{0}..." -f $pin.version)
$expected = Get-PublishedHash $pin.version
}
if (-not $expected) {
throw "No SHA-256 is available for node v$($pin.version), so the download cannot be verified. Refusing to install it."
}
$url = $env:LUMINARY_NODE_URL
if (-not $url) { $url = "https://nodejs.org/dist/v$($pin.version)/win-x64/node.exe" }
Write-Host ("Downloading {0}" -f $url)
$temp = Join-Path ([System.IO.Path]::GetTempPath()) ("luminary-node-{0}.exe" -f [guid]::NewGuid().ToString('N'))
try {
Invoke-WebRequest -UseBasicParsing -TimeoutSec 600 -Uri $url -OutFile $temp
$actual = (Get-FileHash -LiteralPath $temp -Algorithm SHA256).Hash.ToLowerInvariant()
if ($actual -ne $expected.ToLowerInvariant()) {
throw ("The downloaded node.exe does not match the expected checksum (got {0}, want {1}). Nothing was changed." -f $actual, $expected)
}
if (Test-Path -LiteralPath $nodeExe) {
try { (Get-Item -LiteralPath $nodeExe).IsReadOnly = $false } catch { }
}
Move-Item -LiteralPath $temp -Destination $nodeExe -Force
Write-Host ("node.exe restored: v{0}, sha256 {1}" -f $pin.version, $actual)
} finally {
if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp -Force -ErrorAction SilentlyContinue }
}
}
# --- bundle checks ------------------------------------------------------------
# Prints a line for every file the bundle needs and returns $true when all are
# present and non-empty. A zero-byte file is what an antivirus or a half-done
# extraction leaves behind, so it is treated as missing.
function Test-Bundle {
$ok = $true
$required = @(
@{ Name = 'app\server\index.mjs'; Path = $entry },
@{ Name = 'app\dist\index.html'; Path = $uiFile }
)
foreach ($item in $required) {
if (-not (Test-Path -LiteralPath $item.Path)) {
Write-Host (" missing {0}" -f $item.Name)
$ok = $false
} elseif ((Get-Item -LiteralPath $item.Path).Length -eq 0) {
Write-Host (" empty {0} ({1})" -f $item.Name, $item.Path)
$ok = $false
}
}
return $ok
}
function Write-BundleHelp {
$pin = Read-NodePin
Write-Host ''
Write-Host 'This folder is not a complete Luminary bundle. The usual causes:'
Write-Host ''
Write-Host ' 1. The zip was opened, not extracted. Close it, right-click the zip,'
Write-Host ' choose "Extract All...", then run Luminary.cmd (or Luminary.vbs)'
Write-Host ' from the extracted Luminary folder. A file started from inside the'
Write-Host ' zip preview is copied out on its own, without node.exe or app\.'
Write-Host ''
Write-Host ' 2. Antivirus or SmartScreen removed node.exe after extraction.'
Write-Host ' Run "Luminary.cmd -Repair" to download it again and verify it'
Write-Host ' against the checksum in version.txt.'
if ($pin.sha256) { Write-Host (' expected sha256: {0}' -f $pin.sha256) }
Write-Host ''
Write-Host ' 3. This is the source checkout, not a bundle. In the repository run'
Write-Host ' "node windows/build.mjs" and use the zip it prints.'
Write-Host ''
Write-Host 'Run "Luminary.cmd -Verify" to list every file the launcher needs.'
}
function Get-LogDir([string]$dataDir) {
try {
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
return $logDir
} catch {
# Read-only media (USB stick with the write-protect switch, a network share
# the user cannot write): keep the logs with the data instead of failing.
$fallback = Join-Path $dataDir 'logs'
New-Item -ItemType Directory -Force -Path $fallback | Out-Null
Write-Host ("Logs go to {0} (the bundle folder is not writable)." -f $fallback)
return $fallback
}
}
# The state file lives in the bundle folder so a copied bundle is self-contained.
# On read-only media (write-protected USB, Program Files for a non-admin user) it
# moves next to the data, which is always writable.
$runtimeFile = Join-Path $root 'runtime.json'
try {
$probe = Join-Path $root ('.write-test-{0}' -f [guid]::NewGuid().ToString('N'))
[System.IO.File]::WriteAllText($probe, '')
Remove-Item -LiteralPath $probe -Force
} catch {
$runtimeFile = Join-Path (Get-DataDir) 'runtime.json'
}
# --- commands -----------------------------------------------------------------
if ($Verify) {
Write-Host ("Bundle: {0}" -f $root)
$complete = Test-Bundle
$pin = Read-NodePin
if (-not (Test-Path -LiteralPath $nodeExe)) {
Write-Host ' missing node.exe'
$complete = $false
} else {
$nodeInfo = Get-Item -LiteralPath $nodeExe
if ($nodeInfo.Length -eq 0) {
Write-Host ' empty node.exe'
$complete = $false
} elseif ($pin.size -gt 0 -and $nodeInfo.Length -ne $pin.size) {
Write-Host (" damaged node.exe ({0:N0} bytes, expected {1:N0})" -f $nodeInfo.Length, $pin.size)
$complete = $false
}
}
if ($complete) {
foreach ($file in @($nodeExe, $entry, $uiFile)) {
$shown = $file.Replace($root + '\', '')
Write-Host (" ok {0} ({1:N0} bytes)" -f $shown, (Get-Item -LiteralPath $file).Length)
}
if ($pin.version) { Write-Host ("Node: v{0} (pinned)" -f $pin.version) }
Write-Host 'The bundle is complete.'
exit 0
}
Write-BundleHelp
exit 3
}
$runtime = Read-Runtime
$running = $runtime -and (Test-Process ([int]$runtime.pid))
if ($Repair) {
if ($running) {
Write-Host 'Luminary is running. Stop it first: "Luminary.cmd -Stop".'
exit 1
}
try {
Repair-Node
} catch {
Write-Host ''
Write-Host ("Repair failed: {0}" -f $_.Exception.Message)
Show-ErrorDialog ("node.exe could not be restored.`n`n" + $_.Exception.Message)
exit 1
}
Write-Host ''
if (Test-Bundle) {
Write-Host 'The bundle is complete and ready to run.'
exit 0
}
Write-BundleHelp
exit 3
}
if ($Status) {
if ($running) {
$reachable = Test-Health ([int]$runtime.port)
$state = 'not answering yet'
if ($reachable) { $state = 'ok' }
Write-Host ("Luminary is running (pid {0}) at {1}; health {2}." -f $runtime.pid, $runtime.url, $state)
} else {
Write-Host 'Luminary is not running.'
}
$platform = Test-Platform
Write-Host ("System: Windows build {0}, {1}" -f (Get-WindowsBuild), $env:PROCESSOR_ARCHITECTURE)
foreach ($note in $platform.notes) { Write-Host ("Note: {0}" -f $note) }
foreach ($problem in $platform.problems) { Write-Host ("Problem: {0}" -f $problem) }
$node = Resolve-Node
if ($node) {
if ($node.system) {
Write-Host ("Node: {0} ({1}) - bundled node.exe is missing; run -Repair" -f $node.path, $node.version)
} else {
Write-Host 'Node: bundled node.exe'
}
} else {
Write-Host 'Node: missing (run -Repair)'
}
Write-Host ("Data: {0}" -f (Get-DataDir))
exit 0
}
if ($Stop) {
if (-not $running) {
Write-Host 'Luminary is not running.'
Remove-Item -LiteralPath $runtimeFile -Force -ErrorAction SilentlyContinue
exit 0
}
& taskkill.exe /PID ([int]$runtime.pid) /T /F | Out-Null
Remove-Item -LiteralPath $runtimeFile -Force -ErrorAction SilentlyContinue
Write-Host 'Luminary stopped.'
exit 0
}
# A second double-click while the first server is still booting must wait for it,
# not start a second server on the same catalog.
if ($running) {
Write-Host 'Luminary is already starting; waiting for it to answer...'
$deadline = (Get-Date).AddSeconds(120)
while ((Get-Date) -lt $deadline) {
if (Test-Health ([int]$runtime.port)) {
Write-Host ("Luminary is running at {0}" -f $runtime.url)
Open-App ([string]$runtime.url)
exit 0
}
if (-not (Test-Process ([int]$runtime.pid))) { break }
Start-Sleep -Milliseconds 700
}
if (Test-Process ([int]$runtime.pid)) {
$logNote = Join-Path (Get-DataDir) 'logs'
Show-ErrorDialog ("Luminary has been starting for over two minutes and is not answering on port {0}.`n`nSee {1} for the server log." -f $runtime.port, $logNote)
exit 1
}
}
if ($runtime -and (Test-Health ([int]$runtime.port))) {
Write-Host ("Luminary is already running at {0}" -f $runtime.url)
Open-App ([string]$runtime.url)
exit 0
}
if (-not (Test-Bundle)) {
Write-Host ''
Write-Host 'Luminary cannot start: this folder is incomplete.'
Write-BundleHelp
Show-ErrorDialog 'This folder is not a complete Luminary bundle. See the console for the three usual causes.'
exit 3
}
$platform = Test-Platform
foreach ($note in $platform.notes) { Write-Host ("Note: {0}" -f $note) }
if (-not $platform.ok) {
$message = ($platform.problems -join "`n`n") + "`n`nLuminary runs on Windows 10/11 (64-bit) with a current browser (Edge, Chrome or Firefox) for the Develop module. Nothing else needs to be installed."
Write-Host $message
Show-ErrorDialog $message
exit 4
}
$node = Resolve-Node
if (-not $node) {
# The only download Luminary can need is its own runtime. Offer it here so a
# customer who never reads the README still gets a working install.
if (Show-Question "Luminary needs its Node.js 24 runtime, but node.exe is missing from this folder.`n`nDownload it now from nodejs.org (about 90 MB)?") {
try {
Repair-Node
$node = Resolve-Node
} catch {
Write-Host ("Download failed: {0}" -f $_.Exception.Message)
Show-ErrorDialog ("The runtime download failed.`n`n" + $_.Exception.Message)
exit 3
}
}
if (-not $node) {
$message = "Luminary cannot start without node.exe.`n`nRun ""Luminary.cmd -Repair"" to download it, or install Node.js 24 from nodejs.org."
Write-Host $message
Show-ErrorDialog $message
exit 3
}
}
if ($node.system) {
$warning = ("The bundled node.exe is missing; Luminary is using the system Node {0} at {1}.`n`n" +
"Run ""Luminary.cmd -Repair"" to restore the pinned runtime." -f $node.version, $node.path)
Write-Host $warning
Show-Dialog $warning 'Information'
}
$dataDir = Get-DataDir
New-Item -ItemType Directory -Force -Path $dataDir | Out-Null
$logsOut = Get-LogDir $dataDir
$port = Find-Port
$url = "http://127.0.0.1:$port"
# The server reads these from the environment; nothing is written into app\.
$env:PORT = "$port"
$env:HOST = '127.0.0.1'
$env:NODE_ENV = 'production'
$env:LUMINARY_DATA = $dataDir
# Desktop mode: one local admin, no signup, no sign-in. Loopback only, so this
# never exposes a passwordless account to the network.
$env:LUMINARY_LOCAL = '1'
$outLog = Join-Path $logsOut 'server.out.log'
$errLog = Join-Path $logsOut 'server.err.log'
$process = Start-Process -FilePath $node.path `
-ArgumentList ('"' + $entry + '"') `
-WorkingDirectory $appDir `
-WindowStyle Hidden `
-PassThru `
-RedirectStandardOutput $outLog `
-RedirectStandardError $errLog
@{
pid = $process.Id
port = $port
url = $url
data = $dataDir
node = $node.path
started = (Get-Date).ToString('o')
} | ConvertTo-Json | Set-Content -LiteralPath $runtimeFile -Encoding UTF8
$deadline = (Get-Date).AddSeconds(120)
while ((Get-Date) -lt $deadline) {
if ($process.HasExited) { break }
if (Test-Health $port) {
Write-Host ("Luminary is running at {0}" -f $url)
Write-Host ("Data: {0}" -f $dataDir)
Open-App $url
exit 0
}
Start-Sleep -Milliseconds 700
}
$tail = ''
if (Test-Path -LiteralPath $errLog) { $tail = (Get-Content -LiteralPath $errLog -Tail 20) -join "`n" }
Write-Host 'Luminary did not answer on /api/health.'
if ($tail) { Write-Host $tail }
if (-not $process.HasExited) { & taskkill.exe /PID $process.Id /T /F | Out-Null }
Remove-Item -LiteralPath $runtimeFile -Force -ErrorAction SilentlyContinue
Show-ErrorDialog ("Luminary did not start.`n`n" + $tail)
exit 1
+36
View File
@@ -0,0 +1,36 @@
' Start Luminary without a console window.
' Double-click this file, or use the shortcut an installer creates.
Option Explicit
Dim fso, shell, here, script, nodeExe, powershell
Set fso = CreateObject("Scripting.FileSystemObject")
Set shell = CreateObject("WScript.Shell")
here = fso.GetParentFolderName(WScript.ScriptFullName)
script = fso.BuildPath(here, "Luminary.ps1")
nodeExe = fso.BuildPath(here, "node.exe")
powershell = fso.BuildPath(shell.ExpandEnvironmentStrings("%SystemRoot%"), "System32\WindowsPowerShell\v1.0\powershell.exe")
' Windows 10/11 always has PowerShell; a stripped image may not. Say so instead
' of letting WScript report a script error.
If Not fso.FileExists(powershell) Then
MsgBox "Windows PowerShell is missing, so Luminary cannot start." & vbCrLf & vbCrLf & _
"PowerShell 5.1 is included with Windows 10 and 11. On a stripped image, " & _
"install it from Microsoft, or run Luminary.cmd on a normal desktop.", _
16, "Luminary"
WScript.Quit 4
End If
' A file started from inside a zip preview is copied out on its own, so the
' launcher is the only thing present. Say so instead of failing silently.
If Not fso.FileExists(script) Or Not fso.FileExists(nodeExe) Then
MsgBox "This folder is not a complete Luminary bundle." & vbCrLf & vbCrLf & _
"Right-click the zip you downloaded, choose ""Extract All..."", then run " & _
"Luminary.vbs or Luminary.cmd from the extracted Luminary folder." & vbCrLf & vbCrLf & _
"If node.exe is missing after extracting, antivirus or SmartScreen " & _
"removed it: run Luminary.ps1 -Repair (or re-extract the zip) to restore it.", _
16, "Luminary"
WScript.Quit 3
End If
shell.Run """" & powershell & """ -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & script & """", 0, False
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Stop the Luminary server started from this folder.
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Luminary.ps1" -Stop
pause
+3
View File
@@ -0,0 +1,3 @@
module luminary/launcher
go 1.21
+688
View File
@@ -0,0 +1,688 @@
//go:build windows
// Luminary launcher (Go).
//
// Optional: when a Go toolchain is available, windows/build.mjs compiles this
// into Luminary.exe and ships it instead of the PowerShell entry points. It
// does the same jobs as Luminary.ps1, with one difference: being a real
// process it can stay in the background and clean up after the server exits.
//
// Usage:
//
// Luminary.exe start (or reuse) the server and open the browser
// Luminary.exe -stop stop the server started from this folder
// Luminary.exe -repair re-download node.exe and verify it against version.txt
//
// The design and the edge cases are described in ../DESIGN.md.
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"unsafe"
)
const (
firstPort = 8787
lastPort = 8887
healthPath = "/api/health"
startupWait = 120 * time.Second
pollEvery = 700 * time.Millisecond
minNodeMajor = 24
// CREATE_NO_WINDOW keeps the console-based node.exe from flashing a window
// even though the launcher itself is linked with -H windowsgui.
createNoWindow = 0x08000000
// PROCESS_QUERY_LIMITED_INFORMATION is enough to tell whether a pid is alive
// and needs no debug privilege.
processQueryLimitedInformation = 0x1000
)
var (
root = bundleRoot()
logsDir = filepath.Join(root, "logs")
// A -H windowsgui binary has no console, so a missing file would otherwise
// fail silently. MessageBoxW is the only feedback a user can see.
user32 = syscall.NewLazyDLL("user32.dll")
messageBoxW = user32.NewProc("MessageBoxW")
client = &http.Client{Timeout: 2 * time.Second}
downloadClient = &http.Client{Timeout: 10 * time.Minute}
nodePinRE = regexp.MustCompile(`^node\s+v?(\d+\.\d+\.\d+)\s+win-x64(?:\s+sha256\s+([0-9a-f]{64}))?(?:\s+size\s+(\d+))?`)
)
type runtimeInfo struct {
PID int `json:"pid"`
Port int `json:"port"`
URL string `json:"url"`
Data string `json:"data"`
Node string `json:"node"`
Started string `json:"started"`
}
type nodeRuntime struct {
path string
label string
system bool
}
var browserOnly = false
func main() {
args := os.Args[1:]
browserOnly = hasFlag(args, "-browser", "--browser")
switch {
case hasFlag(args, "-repair", "--repair", "/repair"):
if err := repair(); err != nil {
writeLog("launcher.log", "repair: "+err.Error())
showError("node.exe could not be restored.\n\n" + err.Error())
os.Exit(1)
}
showInfo("node.exe is restored and matches the checksum in version.txt.\n\n" +
filepath.Join(root, "node.exe"))
return
case hasFlag(args, "-stop", "--stop", "/stop"):
if err := stop(); err != nil {
showError(err.Error())
os.Exit(1)
}
showInfo("Luminary stopped.")
return
}
if err := run(); err != nil {
writeLog("launcher.log", "error: "+err.Error())
showError(err.Error())
os.Exit(1)
}
}
func hasFlag(args []string, names ...string) bool {
for _, arg := range args {
for _, name := range names {
if strings.EqualFold(arg, name) {
return true
}
}
}
return false
}
func showError(text string) { showMessage(text, 0x10) }
func ask(text string) bool {
title, titleErr := syscall.UTF16PtrFromString("Luminary")
body, bodyErr := syscall.UTF16PtrFromString(text)
if titleErr != nil || bodyErr != nil {
return false
}
// MB_YESNO | MB_ICONQUESTION | MB_SETFOREGROUND; IDYES is 6.
result, _, _ := messageBoxW.Call(0, uintptr(unsafe.Pointer(body)), uintptr(unsafe.Pointer(title)), 0x04|0x20|0x10000)
return result == 6
}
func showInfo(text string) { showMessage(text, 0x40) }
func showMessage(text string, kind uintptr) {
title, titleErr := syscall.UTF16PtrFromString("Luminary")
body, bodyErr := syscall.UTF16PtrFromString(text)
if titleErr != nil || bodyErr != nil {
return
}
// MB_SETFOREGROUND so the dialog is not hidden behind the browser.
messageBoxW.Call(0, uintptr(unsafe.Pointer(body)), uintptr(unsafe.Pointer(title)), kind|0x10000)
}
func run() error {
nodeExe := filepath.Join(root, "node.exe")
appDir := filepath.Join(root, "app")
entry := filepath.Join(appDir, "server", "index.mjs")
required := []struct {
name string
path string
}{
{"app\\server\\index.mjs", entry},
{"app\\dist\\index.html", filepath.Join(appDir, "dist", "index.html")},
}
var missing []string
for _, file := range required {
info, err := os.Stat(file.path)
if err != nil {
missing = append(missing, file.name)
continue
}
if info.Size() == 0 {
// What a half-done extraction or an antivirus leaves behind.
missing = append(missing, file.name+" (empty)")
}
}
if len(missing) > 0 {
return fmt.Errorf("this folder is not a complete Luminary bundle (missing: %s).\n\n"+
"Right-click the zip you downloaded, choose \"Extract All...\", then run "+
"Luminary.exe from the extracted Luminary folder. If files disappeared "+
"after extracting, antivirus or SmartScreen removed them: restore them "+
"from quarantine and extract again.", strings.Join(missing, ", "))
}
node, err := resolveNode(nodeExe)
if err != nil {
// The only download Luminary can need is its own runtime. Offer it here
// so a customer who never reads the README still gets a working install.
if ask("Luminary needs its Node.js 24 runtime, but node.exe is missing from this bundle.\n\n" +
"Download it now from nodejs.org (about 90 MB)?") {
if repairErr := repair(); repairErr != nil {
return fmt.Errorf("the runtime download failed: %w", repairErr)
}
node, err = resolveNode(nodeExe)
}
if err != nil {
return fmt.Errorf("%w\n\nRun \"Luminary.exe -repair\" to download the pinned runtime "+
"again, or install Node.js 24 from nodejs.org.", err)
}
}
if node.system {
message := fmt.Sprintf("The bundled node.exe is missing or damaged, so Luminary is using %s.\n\n"+
"Run \"Luminary.exe -repair\" to restore the pinned runtime.", node.label)
writeLog("launcher.log", "warning: "+message)
showInfo(message)
}
// Already running, or still booting: health is the liveness test, so a stale
// runtime.json from a crash falls through to a fresh start instead of
// blocking it, and a second double-click waits instead of starting a second
// server on the same catalog.
if info, ok := readRuntime(); ok {
if healthy(info.Port) {
openApp(info.URL)
return nil
}
if processAlive(info.PID) {
deadline := time.Now().Add(startupWait)
for time.Now().Before(deadline) {
if healthy(info.Port) {
openApp(info.URL)
return nil
}
if !processAlive(info.PID) {
break
}
time.Sleep(pollEvery)
}
if processAlive(info.PID) {
return fmt.Errorf("Luminary is already starting (pid %d) but is not answering on port %d. "+
"See %s.", info.PID, info.Port, filepath.Join(dataDirectory(), "logs", "server.err.log"))
}
}
}
dataDir := dataDirectory()
if err := os.MkdirAll(dataDir, 0o755); err != nil {
return fmt.Errorf("cannot create the data directory %s: %w", dataDir, err)
}
logDir, err := ensureLogDir(dataDir)
if err != nil {
return err
}
port, err := freePort()
if err != nil {
return err
}
url := fmt.Sprintf("http://127.0.0.1:%d", port)
stdout, err := openLog(logDir, "server.out.log")
if err != nil {
return err
}
defer stdout.Close()
stderr, err := openLog(logDir, "server.err.log")
if err != nil {
return err
}
defer stderr.Close()
cmd := exec.Command(node.path, entry)
cmd.Dir = appDir
cmd.Stdout = stdout
cmd.Stderr = stderr
cmd.Env = append(os.Environ(),
"PORT="+strconv.Itoa(port),
"HOST=127.0.0.1",
"NODE_ENV=production",
"LUMINARY_DATA="+dataDir,
// Desktop mode: one local admin, no signup or sign-in. Loopback only,
// so this never exposes a passwordless account to the network.
"LUMINARY_LOCAL=1",
)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: createNoWindow}
if err := cmd.Start(); err != nil {
return fmt.Errorf("cannot start %s: %w", node.path, err)
}
info := runtimeInfo{
PID: cmd.Process.Pid,
Port: port,
URL: url,
Data: dataDir,
Node: node.path,
Started: time.Now().Format(time.RFC3339),
}
writeRuntime(info)
deadline := time.Now().Add(startupWait)
for time.Now().Before(deadline) {
if healthy(port) {
openApp(url)
// Stay alive for the server's lifetime so runtime.json is removed
// on quit and a crash is written to the launcher log. The exit
// code is deliberately ignored: "Stop" force-kills the child.
_ = cmd.Wait()
removeRuntime()
writeLog("launcher.log", "server exited")
return nil
}
time.Sleep(pollEvery)
}
_ = cmd.Process.Kill()
removeRuntime()
return fmt.Errorf("Luminary did not answer on %s within %s; see %s",
healthPath, startupWait, filepath.Join(logDir, "server.err.log"))
}
// --- runtime resolution -------------------------------------------------------
func nodePin() (version, hash string, size int64) {
data, err := os.ReadFile(filepath.Join(root, "version.txt"))
if err != nil {
return "", "", 0
}
for _, line := range strings.Split(string(data), "\n") {
match := nodePinRE.FindStringSubmatch(strings.TrimSpace(line))
if match == nil {
continue
}
version = match[1]
hash = match[2]
if match[3] != "" {
size, _ = strconv.ParseInt(match[3], 10, 64)
}
return version, hash, size
}
return "", "", 0
}
// The bundled runtime wins; a system Node 24+ is a fallback, never a preference.
func resolveNode(bundled string) (nodeRuntime, error) {
if info, err := os.Stat(bundled); err == nil && info.Size() > 0 {
_, _, pinnedSize := nodePin()
if pinnedSize == 0 || info.Size() == pinnedSize {
return nodeRuntime{path: bundled, label: "the bundled node.exe"}, nil
}
}
seen := map[string]bool{}
for _, candidate := range systemNodeCandidates() {
key := strings.ToLower(candidate)
if seen[key] {
continue
}
seen[key] = true
info, err := os.Stat(candidate)
if err != nil || info.Size() == 0 {
continue
}
if major, ok := nodeMajor(candidate); ok && major >= minNodeMajor {
return nodeRuntime{
path: candidate,
label: fmt.Sprintf("the system Node %d at %s", major, candidate),
system: true,
}, nil
}
}
return nodeRuntime{}, fmt.Errorf("node.exe is missing from the bundle and no Node.js %d+ was found on this machine", minNodeMajor)
}
func systemNodeCandidates() []string {
var candidates []string
if found, err := exec.LookPath("node.exe"); err == nil {
candidates = append(candidates, found)
}
if found, err := exec.LookPath("node"); err == nil {
candidates = append(candidates, found)
}
if dir := os.Getenv("ProgramFiles"); dir != "" {
candidates = append(candidates, filepath.Join(dir, "nodejs", "node.exe"))
}
if dir := os.Getenv("ProgramFiles(x86)"); dir != "" {
candidates = append(candidates, filepath.Join(dir, "nodejs", "node.exe"))
}
if dir := os.Getenv("LOCALAPPDATA"); dir != "" {
candidates = append(candidates, filepath.Join(dir, "Programs", "nodejs", "node.exe"))
}
if dir := os.Getenv("NVM_SYMLINK"); dir != "" {
candidates = append(candidates, filepath.Join(dir, "node.exe"))
}
return candidates
}
func nodeMajor(exe string) (int, bool) {
cmd := exec.Command(exe, "--version")
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: createNoWindow}
out, err := cmd.Output()
if err != nil {
return 0, false
}
raw := strings.TrimPrefix(strings.TrimSpace(string(out)), "v")
parts := strings.SplitN(raw, ".", 2)
major, err := strconv.Atoi(parts[0])
if err != nil || major <= 0 {
return 0, false
}
return major, true
}
// --- repair -------------------------------------------------------------------
func repair() error {
nodeExe := filepath.Join(root, "node.exe")
if info, ok := readRuntime(); ok && (healthy(info.Port) || processAlive(info.PID)) {
return fmt.Errorf("Luminary is running (pid %d). Stop it first: Luminary.exe -stop", info.PID)
}
version, expected, _ := nodePin()
if version == "" {
return fmt.Errorf("version.txt does not record a node version, so there is nothing to re-download. Extract the zip again instead.")
}
if expected == "" {
hash, err := publishedHash(version)
if err != nil {
return err
}
expected = hash
}
url := os.Getenv("LUMINARY_NODE_URL")
if url == "" {
url = fmt.Sprintf("https://nodejs.org/dist/v%s/win-x64/node.exe", version)
}
writeLog("launcher.log", "repair: downloading "+url)
response, err := downloadClient.Get(url)
if err != nil {
return fmt.Errorf("cannot download node.exe: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return fmt.Errorf("cannot download node.exe: %s answered %s", url, response.Status)
}
temp := filepath.Join(root, "node.exe.new")
file, err := os.Create(temp)
if err != nil {
return fmt.Errorf("cannot write next to the launcher: %w", err)
}
hasher := sha256.New()
_, copyErr := io.Copy(io.MultiWriter(file, hasher), response.Body)
closeErr := file.Close()
if copyErr != nil {
_ = os.Remove(temp)
return fmt.Errorf("the download stopped early: %w", copyErr)
}
if closeErr != nil {
_ = os.Remove(temp)
return fmt.Errorf("cannot finish writing node.exe: %w", closeErr)
}
actual := hex.EncodeToString(hasher.Sum(nil))
if !strings.EqualFold(actual, expected) {
_ = os.Remove(temp)
return fmt.Errorf("the downloaded node.exe does not match the expected checksum (got %s, want %s). Nothing was changed.", actual, expected)
}
// Windows will not rename over an existing file; a running server is already
// refused above, so the old copy is not in use here.
_ = os.Remove(nodeExe)
if err := os.Rename(temp, nodeExe); err != nil {
_ = os.Remove(temp)
return fmt.Errorf("cannot replace node.exe: %w", err)
}
writeLog("launcher.log", fmt.Sprintf("repair: restored node v%s sha256 %s", version, actual))
return nil
}
func publishedHash(version string) (string, error) {
url := fmt.Sprintf("https://nodejs.org/dist/v%s/SHASUMS256.txt", version)
response, err := downloadClient.Get(url)
if err != nil {
return "", fmt.Errorf("cannot fetch the published checksum: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return "", fmt.Errorf("cannot fetch the published checksum: %s answered %s", url, response.Status)
}
body, err := io.ReadAll(response.Body)
if err != nil {
return "", fmt.Errorf("cannot read the published checksum: %w", err)
}
for _, line := range strings.Split(string(body), "\n") {
fields := strings.Fields(line)
if len(fields) >= 2 && fields[1] == "win-x64/node.exe" {
return strings.ToLower(fields[0]), nil
}
}
return "", fmt.Errorf("no win-x64/node.exe checksum for v%s", version)
}
// --- commands -----------------------------------------------------------------
func stop() error {
info, ok := readRuntime()
if !ok {
showInfo("Luminary is not running.")
return nil
}
// /T also takes down sharp's helper processes and the denoise workers.
if err := exec.Command("taskkill.exe", "/PID", strconv.Itoa(info.PID), "/T", "/F").Run(); err != nil && processAlive(info.PID) {
return fmt.Errorf("cannot stop pid %d: %w", info.PID, err)
}
removeRuntime()
return nil
}
// --- helpers ------------------------------------------------------------------
func bundleRoot() string {
exe, err := os.Executable()
if err != nil {
return "."
}
return filepath.Dir(exe)
}
func dataDirectory() string {
if dir := strings.TrimSpace(os.Getenv("LUMINARY_DATA")); dir != "" {
return dir
}
base := os.Getenv("LOCALAPPDATA")
if base == "" {
base = filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")
}
return filepath.Join(base, "Luminary", "data")
}
// A bundle on read-only media still has to boot; the logs move next to the data.
func ensureLogDir(dataDir string) (string, error) {
if err := os.MkdirAll(logsDir, 0o755); err == nil {
return logsDir, nil
}
fallback := filepath.Join(dataDir, "logs")
if err := os.MkdirAll(fallback, 0o755); err != nil {
return "", fmt.Errorf("cannot create a log directory: %w", err)
}
return fallback, nil
}
func freePort() (int, error) {
for port := firstPort; port <= lastPort; port++ {
listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err == nil {
listener.Close()
return port, nil
}
}
return 0, fmt.Errorf("no free TCP port between %d and %d", firstPort, lastPort)
}
func healthy(port int) bool {
response, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d%s", port, healthPath))
if err != nil {
return false
}
defer response.Body.Close()
return response.StatusCode == http.StatusOK
}
func processAlive(pid int) bool {
handle, err := syscall.OpenProcess(processQueryLimitedInformation, false, uint32(pid))
if err != nil {
return false
}
syscall.CloseHandle(handle)
return true
}
func openBrowser(url string) {
// FileProtocolHandler goes through the user's default browser without
// needing a protocol registration of our own.
_ = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
}
// Edge ships with Windows 10/11, so a chromeless app window costs no extra
// runtime. Chrome is the second choice; anything else falls back to a tab.
func findAppBrowser() string {
candidates := []string{}
add := func(dir string, rest ...string) {
if dir != "" {
candidates = append(candidates, filepath.Join(append([]string{dir}, rest...)...))
}
}
for _, key := range []string{"ProgramFiles(x86)", "ProgramFiles", "LOCALAPPDATA"} {
add(os.Getenv(key), "Microsoft", "Edge", "Application", "msedge.exe")
}
for _, key := range []string{"LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"} {
add(os.Getenv(key), "Google", "Chrome", "Application", "chrome.exe")
}
for _, candidate := range candidates {
if info, err := os.Stat(candidate); err == nil && info.Size() > 0 {
return candidate
}
}
return ""
}
// --app gives a window with no tabs and no address bar, in its own profile, so
// it reads as a desktop app rather than a web page. -browser opts out.
func openApp(url string) {
if browserOnly || strings.EqualFold(os.Getenv("LUMINARY_WINDOW"), "browser") {
openBrowser(url)
return
}
// A native WebView2 host, when the bundle ships one, is the real app window:
// its own icon, no browser branding at all.
native := filepath.Join(root, "LuminaryWindow.exe")
if info, err := os.Stat(native); err == nil && info.Size() > 0 {
if err := exec.Command(native, "--url", url).Start(); err == nil {
return
}
}
exe := findAppBrowser()
if exe == "" {
openBrowser(url)
return
}
profile := filepath.Join(dataDirectory(), "window-profile")
if err := os.MkdirAll(profile, 0o755); err != nil {
openBrowser(url)
return
}
cmd := exec.Command(exe,
"--app="+url,
"--user-data-dir="+profile,
"--window-size=1500,950",
"--no-first-run",
"--no-default-browser-check",
"--disable-features=Translate",
)
if err := cmd.Start(); err != nil {
openBrowser(url)
}
}
// The state file lives in the bundle folder so a copied bundle is self-contained.
// On read-only media (write-protected USB, Program Files for a non-admin user)
// it moves next to the data, which is always writable.
func runtimePath() string {
probe := filepath.Join(root, ".write-test")
if err := os.WriteFile(probe, nil, 0o644); err == nil {
_ = os.Remove(probe)
return filepath.Join(root, "runtime.json")
}
return filepath.Join(dataDirectory(), "runtime.json")
}
func readRuntime() (runtimeInfo, bool) {
var info runtimeInfo
data, err := os.ReadFile(runtimePath())
if err != nil {
return info, false
}
if json.Unmarshal(data, &info) != nil || info.PID == 0 || info.Port == 0 {
return info, false
}
return info, true
}
func writeRuntime(info runtimeInfo) {
data, err := json.MarshalIndent(info, "", " ")
if err != nil {
return
}
_ = os.WriteFile(runtimePath(), append(data, '\n'), 0o644)
}
func removeRuntime() {
_ = os.Remove(runtimePath())
}
func openLog(dir, name string) (*os.File, error) {
return os.OpenFile(filepath.Join(dir, name), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
}
func writeLog(name, message string) {
dir, err := ensureLogDir(dataDirectory())
if err != nil {
return
}
file, err := openLog(dir, name)
if err != nil {
return
}
defer file.Close()
fmt.Fprintf(file, "%s %s\n", time.Now().Format(time.RFC3339), message)
}
@@ -0,0 +1,47 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Optional native window for the Windows bundle. The launcher starts it with
a url switch pointing at the local server.
It is a window host only: node.exe stays a child of the launcher, so Stop
works the same whether the UI runs here or in an Edge app window. Starting
it without a url argument (for example, double-clicking it) forwards to the
bundle launcher instead of showing a signed-out page.
Published self-contained: the customer needs no .NET install. The only
runtime requirement is Microsoft Edge WebView2, which ships with Windows
10/11 alongside Edge. EnableWindowsTargeting lets this be compiled on a
Linux build host; it still only runs on Windows.
-->
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyName>LuminaryWindow</AssemblyName>
<RootNamespace>Luminary</RootNamespace>
<ApplicationIcon>../Luminary.ico</ApplicationIcon>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>true</PublishSingleFile>
<!-- ~140 MB raw becomes roughly half that in the single file. -->
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
<AllowedReferenceRelatedFileExtensions>none</AllowedReferenceRelatedFileExtensions>
<!-- WebView2Loader.dll is native; single-file must extract it at startup. -->
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<EnableWindowsTargeting>true</EnableWindowsTargeting>
<Version>0.5.1</Version>
<AssemblyTitle>Luminary</AssemblyTitle>
<Product>Luminary</Product>
<Company>Maple Street</Company>
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4370.26" />
</ItemGroup>
</Project>
+100
View File
@@ -0,0 +1,100 @@
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
namespace Luminary;
/// <summary>
/// The whole app window: WebView2 filling the client area, the Luminary icon in
/// the title bar and taskbar, and an explicit message when the WebView2 runtime
/// is missing instead of a silent exit.
/// </summary>
internal sealed class MainForm : Form
{
private const string RuntimeDownload = "https://go.microsoft.com/fwlink/p/?LinkId=2124703";
private readonly string _url;
private readonly WebView2 _web = new() { Dock = DockStyle.Fill };
public MainForm(string url)
{
_url = url;
Text = "Luminary";
Width = 1500;
Height = 950;
MinimumSize = new Size(900, 600);
StartPosition = FormStartPosition.CenterScreen;
Icon = LoadIcon();
Controls.Add(_web);
Load += async (_, _) => await InitializeAsync();
}
/// <summary>The exe carries the icon; extracting it avoids shipping a second file.</summary>
private static Icon? LoadIcon()
{
try
{
var exe = Environment.ProcessPath;
if (!string.IsNullOrEmpty(exe))
{
var icon = Icon.ExtractAssociatedIcon(exe);
if (icon != null) return icon;
}
}
catch
{
// A missing icon must never stop the window from opening.
}
return null;
}
private async Task InitializeAsync()
{
try
{
// Its own profile, next to the catalog, so the app never shares
// cookies or storage with the user's normal browsing. LUMINARY_DATA
// wins, the same precedence the server and launcher use.
var dataRoot = Environment.GetEnvironmentVariable("LUMINARY_DATA");
if (string.IsNullOrWhiteSpace(dataRoot))
{
dataRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Luminary", "data");
}
var dataDir = Path.Combine(dataRoot, "webview2");
Directory.CreateDirectory(dataDir);
var environment = await CoreWebView2Environment.CreateAsync(null, dataDir);
await _web.EnsureCoreWebView2Async(environment);
var settings = _web.CoreWebView2.Settings;
settings.AreDevToolsEnabled = false;
settings.IsStatusBarEnabled = false;
settings.AreDefaultContextMenusEnabled = true;
_web.CoreWebView2.Navigate(_url);
}
catch (WebView2RuntimeNotFoundException)
{
Fail(
"The Microsoft Edge WebView2 runtime is missing.\n\n" +
"Install it from " + RuntimeDownload + " and start Luminary again.",
close: true);
}
catch (Exception error)
{
Fail("Luminary could not open its window.\n\n" + error.Message, close: true);
}
}
private void Fail(string message, bool close)
{
MessageBox.Show(this, message, "Luminary", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (close) Close();
}
}
+131
View File
@@ -0,0 +1,131 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
namespace Luminary;
internal static class Program
{
[STAThread]
private static void Main(string[] args)
{
var url = "http://127.0.0.1:8787";
var urlProvided = false;
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg is "--url" or "-url")
{
if (i + 1 < args.Length) url = args[i + 1];
urlProvided = true;
break;
}
if (arg.StartsWith("--url=", StringComparison.OrdinalIgnoreCase))
{
url = arg[6..];
urlProvided = true;
break;
}
}
// This exe is the window the launcher opens. If someone double-clicks it
// directly there is no server in desktop mode, or port 8787 may belong
// to a full sign-in server. Start the real launcher and let it choose the
// port, set LUMINARY_LOCAL=1 and open this window with --url.
if (!urlProvided)
{
if (StartBundleLauncher()) return;
MessageBox.Show(
"LuminaryWindow.exe is only the app window.\n\n" +
"Start Luminary.cmd (or Luminary.vbs) from the Luminary folder instead.",
"Luminary",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(url));
}
/// <summary>
/// A direct window launch forwards to the bundle launcher. That launcher
/// starts the local server with the correct desktop-mode environment and
/// then reopens this window with --url. Returns false when this file is not
/// inside a complete bundle.
/// </summary>
private static bool StartBundleLauncher()
{
// Environment.ProcessPath is the exe itself even in a single-file publish;
// AppContext.BaseDirectory is only a fallback.
var root = Path.GetDirectoryName(Environment.ProcessPath) ?? AppContext.BaseDirectory;
// A Go build has one native launcher; use it when present.
var native = Path.Combine(root, "Luminary.exe");
if (File.Exists(native) && TryStart(native, root)) return true;
// Do not go through Luminary.vbs here. Windows Script Host can be
// disabled by policy, which makes the window fail even though the
// bundle is healthy. Run the PowerShell launcher hidden instead; it is
// the same code Luminary.cmd uses and needs no console or .vbs handler.
var script = Path.Combine(root, "Luminary.ps1");
if (File.Exists(script))
{
var powershell = Path.Combine(
Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe");
if (!File.Exists(powershell)) powershell = "powershell.exe";
try
{
var start = new ProcessStartInfo(powershell)
{
WorkingDirectory = root,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
};
start.ArgumentList.Add("-NoProfile");
start.ArgumentList.Add("-ExecutionPolicy");
start.ArgumentList.Add("Bypass");
start.ArgumentList.Add("-WindowStyle");
start.ArgumentList.Add("Hidden");
start.ArgumentList.Add("-File");
start.ArgumentList.Add(script);
Process.Start(start);
return true;
}
catch
{
// Fall through to the command entry point.
}
}
foreach (var name in new[] { "Luminary.cmd", "Luminary.vbs" })
{
var launcher = Path.Combine(root, name);
if (File.Exists(launcher) && TryStart(launcher, root)) return true;
}
return false;
}
private static bool TryStart(string launcher, string workingDirectory)
{
try
{
Process.Start(new ProcessStartInfo(launcher)
{
WorkingDirectory = workingDirectory,
UseShellExecute = true,
});
return true;
}
catch
{
return false;
}
}
}
+42
View File
@@ -0,0 +1,42 @@
# Windows releases (transfer folder)
The built bundle, kept here so it can be copied to a Windows machine on a USB
stick, a network share, or a release upload. Nothing reads it at run time; the
app never looks in this folder.
| File | What to do with it |
| --- | --- |
| `Luminary-<version>-win-x64-setup.exe` | Copy to the Windows PC and run it. Per-user install, no admin prompt: Start-menu shortcuts, optional desktop shortcut and start-at-login, and an uninstaller that keeps `%LOCALAPPDATA%\Luminary\data`. |
| `Luminary-<version>-win-x64.zip` | The portable alternative: extract, then run `Luminary.cmd` (or `Luminary.vbs`) from the extracted `Luminary` folder. `README-windows.txt` inside the zip is the end-user guide. |
| `LuminaryWindow.exe` inside the zip | optional native window (WebView2); the launcher uses it automatically when present, and starting it directly forwards to the launcher |
| `SHA256SUMS.txt` | Check a copy did not corrupt: `certutil -hashfile Luminary-<version>-win-x64-setup.exe SHA256` |
## Rebuilding this folder
```bash
node windows/build.mjs --publish # npm run build, then bundle + copy here
node windows/build.mjs --skip-build --publish # reuse the existing dist/
```
`--publish` copies the finished zip, the setup exe and `SHA256SUMS.txt`. The build still
stages and zips **outside** the checkout (`~/.cache/luminary-windows`, or
`%LOCALAPPDATA%\Luminary\build` on Windows); this folder only receives the final
artifact. Old versions are not deleted, so remove the ones you no longer ship.
Add `--webview2 <path to LuminaryWindow.exe>` for the native window; without it
the zip is about half the size (49 MB) and uses the Edge/Chrome app window.
## Before a deploy
`scripts/deploy.mjs` rsyncs the worktree, so a zip left here is also sent to the
production server. On a Linux host it is harmless (nothing loads it), but if you
do not want a ~110 MB file on the server, delete it after transferring, or
publish only when you are actually shipping a build.
## What a Windows user needs
Windows 10/11 x64 and a current browser (Edge, Chrome or Firefox) with WebGL2.
Node.js, .NET and the Visual C++ Redistributable are **not** required — they are
bundled or part of Windows. The native window needs the Microsoft Edge WebView2
runtime, which Windows 10/11 already has alongside Edge. See `../README.md` for
the import-level audit.
+2
View File
@@ -0,0 +1,2 @@
22b8943d1ca3bed3ef115530831947e4e03f6a45317ec6b35c10e871fad22a9a Luminary-0.5.1-win-x64.zip
b33e3d8b595aa3ff20b0898f3adea639e02afe9eb54c4fba5dd09ec07e041a0c Luminary-0.5.1-win-x64-setup.exe