Compare commits

..
Author SHA1 Message Date
spark eb81f69fb8 Merge pull request 'Write folder merges through LightCraft Photo Merge' (#122) from task/folder-merge-dng into main
ci / rust (push) Successful in 5m8s
ci / typescript (push) Successful in 14m14s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 28m59s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 31m5s
A camera raw with no matrix of its own was saved as a linear DNG that other raw tools refused.
2026-10-24 01:02:32 +01:00
spark cb67b0c329 Write folder merges through LightCraft Photo Merge so the DNG keeps colour tags.
ci / rust (pull_request) Successful in 5m3s
ci / typescript (pull_request) Successful in 10m50s
A camera raw with no matrix of its own was saved as a linear DNG that other raw tools refused.
2026-10-24 00:50:39 +01:00
spark e096c6153e Merge pull request 'chore(runtime): upgrade PhotoReport monorepo to Node.js 24.22.1 (BIT-31725)' (#121) from task/BIT-31725-node24-upgrade into main
ci / rust (push) Successful in 9m7s
ci / typescript (push) Successful in 12m45s
Merge PR #121 (BIT-31725)
2026-10-23 18:20:44 +01:00
spark fa2e494d99 Merge pull request 'Open a dropped folder from the window drop event' (#120) from task/folder-drop-window into main
ci / rust (push) Successful in 4m18s
ci / typescript (push) Failing after 11m48s
2026-10-23 17:59:17 +01:00
jos-alves ee617b12de chore(runtime): upgrade PhotoReport monorepo to Node.js 24.22.1 (BIT-31725)
ci / rust (pull_request) Successful in 11m45s
ci / typescript (pull_request) Successful in 15m18s
Paperclip-Issue: BIT-31725
2026-10-23 17:45:50 +01:00
31 changed files with 2682 additions and 96 deletions

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@ jobs:
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 22
node-version: 24.22.1
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm -r build
+1 -1
View File
@@ -45,7 +45,7 @@ jobs:
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 22
node-version: 24.22.1
- uses: dtolnay/rust-toolchain@stable
- name: Both Mac processors (universal app)
if: runner.os == 'macOS'
+1 -1
View File
@@ -1 +1 @@
22
24.22.1
Generated
+1702 -5
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -20,6 +20,10 @@ lightcraft-merge = { git = "https://github.com/storytold/lightcraft", rev = "5fe
lightcraft-raw = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
lightcraft-color = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
lightcraft-meta = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
# Photo Merge only. The develop crates do not export the colour-tag step a raw without matrices
# needs before write_linear_dng. Desktop turns this on; the browser engine does not.
lightcraft-engine = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
lightcraft-catalog = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
+5
View File
@@ -56,6 +56,8 @@ export const t = {
opening: "A abrir a pasta…",
close: "Fechar",
hint: "Folha de contacto desta pasta, neste computador. Não cria um evento nem envia fotografias. Estrelas e marcas ficam só nesta sessão.",
mergeTitle: "Funde as exposições desta pasta num DNG ao lado delas. As originais ficam. Não envia fotografias.",
merged: (n: number) => (n === 1 ? "1 DNG ficou nesta pasta." : `${n} DNG ficaram nesta pasta.`),
empty: "Esta pasta não tem fotografias.",
failed: "Não foi possível abrir esta pasta.",
count: (n: number) => (n === 1 ? "1 foto" : `${n} fotos`),
@@ -297,6 +299,9 @@ export const t = {
missing: "Falta o ficheiro original de alguma exposição.",
engine: "O motor ainda não grava o DNG. Quando a cópia do cartão acabar, atualiza a página.",
failed: "Não fundi. Tenta outra vez.",
raw: "Não consegui ler estes RAW para os fundir.",
write: "Não consegui gravar o DNG nesta pasta.",
failedDetail: (reason: string) => `Não fundi. ${reason}`,
},
},
card: {
+58 -1
View File
@@ -4,6 +4,8 @@ import { t } from "../i18n.js";
import { LABEL_COLOR } from "./Grid.js";
import { FOLDER_CELL_H, FOLDER_CELL_W, FOLDER_GAP, folderCols, folderWindow } from "./folder-layout.js";
import type { FolderListing } from "./folderDrop.js";
import { mergeFailureText } from "./folderMerge.js";
import { MergeError } from "./mergeExposures.js";
import { isMac, patchForKey, pmPatchForKey } from "./store.js";
interface Mark {
@@ -66,8 +68,17 @@ export function FolderSheet(props: {
folder: FolderListing;
onClose: () => void;
thumb: (path: string, edge: number) => Promise<ArrayBuffer | null>;
/**
* Merges the photos on this sheet and returns how many DNG files were written beside them.
* Absent in a view that cannot edit. The library's own merge stays on the event underneath.
*/
merge?: (input: {
files: FolderListing["files"];
selectedIds: readonly string[];
onStatus: (stack: number, total: number) => void;
}) => Promise<number>;
}) {
const { folder, onClose, thumb } = props;
const { folder, onClose, thumb, merge } = props;
const files = folder.files;
const scroller = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(800);
@@ -78,6 +89,34 @@ export function FolderSheet(props: {
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(files[0] ? [files[0].path] : []));
const [marks, setMarks] = useState<ReadonlyMap<string, Mark>>(() => new Map());
const [loupe, setLoupe] = useState(false);
const [mergeStatus, setMergeStatus] = useState<string | null>(null);
const [mergeFailed, setMergeFailed] = useState(false);
const [merging, setMerging] = useState(false);
const mergePending = useRef(false);
const runMerge = () => {
if (!merge || mergePending.current) return;
mergePending.current = true;
setMerging(true);
setMergeFailed(false);
setMergeStatus(t.merge.reading);
void merge({
files,
selectedIds: [...selected],
onStatus: (stack, total) => setMergeStatus(t.merge.working(stack, total)),
}).then(
(made) => setMergeStatus(t.folderSheet.merged(made)),
(err: unknown) => {
const code = err instanceof MergeError ? err.code : "failed";
const detail = err instanceof MergeError ? err.detail : undefined;
setMergeStatus(mergeFailureText(code, detail));
setMergeFailed(true);
},
).finally(() => {
mergePending.current = false;
setMerging(false);
});
};
useEffect(() => {
const el = scroller.current;
@@ -221,6 +260,24 @@ export function FolderSheet(props: {
</span>
<span className="font-mono text-[11px] text-faint">{t.folderSheet.count(files.length)}</span>
<span className="hidden text-[11px] text-faint sm:inline">{t.folderSheet.hint}</span>
{merge && files.length > 0 && (
<span className="inline-flex items-center gap-2">
<button
type="button"
title={t.folderSheet.mergeTitle}
disabled={merging}
onClick={runMerge}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
>
{t.merge.button}
</button>
{mergeStatus && (
<span role="status" title={mergeStatus} className={`max-w-xl text-[12px] ${mergeFailed ? "text-danger" : "text-muted"}`}>
{mergeStatus}
</span>
)}
</span>
)}
<button type="button" onClick={onClose} className="ml-auto h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.folderSheet.close}
</button>
+13
View File
@@ -116,6 +116,19 @@ export async function openFolder(path: string, invoke: Invoke = desktopInvoke):
}
}
/** Capture metadata of one photo on the open sheet, read in the desktop process. */
export function folderMeta(path: string, invoke: Invoke = desktopInvoke): Promise<string> {
return invoke<string>("folder_meta", { path });
}
/**
* Merges these photos in the desktop process and writes the DNG beside the middle one.
* The raws never cross into the page: a folder of CR3 does not fit in the browser engine.
*/
export function mergeFolderDng(paths: readonly string[], maxEdge: number, invoke: Invoke = desktopInvoke): Promise<string> {
return invoke<string>("folder_merge_dng", { paths, maxEdge });
}
export async function folderThumb(path: string, edge: number, invoke?: Invoke): Promise<ArrayBuffer | null> {
if (!invoke && !isDesktop()) return null;
try {
+104
View File
@@ -0,0 +1,104 @@
import { describe, expect, it } from "vitest";
import { mergeFailureText, mergeFolderExposures, mergeFolderNative } from "./folderMerge.js";
import { MergeError } from "./mergeExposures.js";
const at = (ms: number) => new Date(Date.parse("2026-10-21T10:00:00.000Z") + ms).toISOString();
function tags(bias: number, ms: number, exposureTime = 1 / 125): string {
return JSON.stringify({
capturedAt: at(ms),
cameraModel: "EOS R5",
focalLength: 16,
aperture: 8,
iso: 100,
width: 4000,
height: 3000,
exposureBias: bias,
exposureTime,
});
}
function files() {
return [
{ path: "/job/sala/dark.cr3", name: "dark.cr3" },
{ path: "/job/sala/mid.cr3", name: "mid.cr3" },
{ path: "/job/sala/bright.cr3", name: "bright.cr3" },
{ path: "/job/sala/mid-fundido.dng", name: "mid-fundido.dng" },
];
}
const meta = new Map([
["/job/sala/dark.cr3", tags(-2, 0)],
["/job/sala/mid.cr3", tags(0, 200)],
["/job/sala/bright.cr3", tags(2, 400)],
]);
describe("merge a contact sheet", () => {
it("writes one DNG beside the bracket when only the focused photo is selected", async () => {
const saved: { dir: string; name: string; bytes: Uint8Array }[] = [];
const made = await mergeFolderExposures({
files: files(),
selectedIds: ["/job/sala/dark.cr3"],
readFile: async (path) => new TextEncoder().encode(path),
readMeta: (bytes) => meta.get(new TextDecoder().decode(bytes)) ?? "{}",
mergeDng: () => new Uint8Array([1, 2, 3]),
saveDng: async (dir, name, bytes) => {
saved.push({ dir, name, bytes });
},
});
expect(made).toBe(1);
expect(saved).toEqual([{ dir: "/job/sala", name: "mid-fundido.dng", bytes: new Uint8Array([1, 2, 3]) }]);
});
it("merges the photos the user selected even when they are not a detected bracket", async () => {
const saved: string[] = [];
const made = await mergeFolderExposures({
files: files(),
selectedIds: ["/job/sala/dark.cr3", "/job/sala/mid.cr3"],
readFile: async (path) => new TextEncoder().encode(path),
readMeta: () => tags(0, 0, 1 / 125),
mergeDng: (frames) => new Uint8Array([frames.length]),
saveDng: async (_dir, name) => {
saved.push(name);
},
});
expect(made).toBe(1);
expect(saved).toEqual(["dark-fundido.dng"]);
});
it("says there is no set when a single photo is not part of a bracket", async () => {
const run = mergeFolderExposures({
files: [{ path: "/job/a.cr3", name: "a.cr3" }, { path: "/job/b.cr3", name: "b.cr3" }],
selectedIds: ["/job/a.cr3"],
readFile: async (path) => new TextEncoder().encode(path),
readMeta: () => tags(0, 0),
mergeDng: () => new Uint8Array([1]),
saveDng: async () => {},
});
await expect(run).rejects.toBeInstanceOf(MergeError);
await expect(run).rejects.toMatchObject({ code: "none" });
});
});
describe("merge a contact sheet on this computer", () => {
const pair = [
{ path: "/job/dark.cr3", name: "dark.cr3" },
{ path: "/job/mid.cr3", name: "mid.cr3" },
];
it("asks the desktop to merge the stack and keeps its reason when that fails", async () => {
const stacks: string[][] = [];
const run = mergeFolderNative({
files: pair,
selectedIds: pair.map((file) => file.path),
metaOf: async () => tags(0, 0),
mergePaths: async (paths) => {
stacks.push([...paths]);
throw new Error("cannot read the photo: cr3");
},
});
await expect(run).rejects.toMatchObject({ code: "failed", detail: "cannot read the photo: cr3" });
expect(stacks).toEqual([["/job/dark.cr3", "/job/mid.cr3"]]);
expect(mergeFailureText("failed", "cannot read the photo: cr3")).toBe("Não consegui ler estes RAW para os fundir.");
});
});
+206
View File
@@ -0,0 +1,206 @@
import { loadEngine, type EngineModule } from "../develop/engine.js";
import { t } from "../i18n.js";
import { frameFromCapture } from "../realestate/readFrame.js";
import { MergeError } from "./mergeExposures.js";
import { MERGE_EDGE, isMergedName, stacksOfFrames } from "./mergeStacks.js";
export interface FolderExposure {
path: string;
name: string;
}
function parentDir(path: string): string {
const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
if (slash <= 0) throw new MergeError("failed");
return path.slice(0, slash);
}
function stemOf(name: string): string {
const dot = name.lastIndexOf(".");
return dot > 0 ? name.slice(0, dot) : name;
}
/**
* Merges the contact sheet on this computer. A selection of two or more is that set; otherwise every
* bracket in the folder. The DNG is written beside the middle frame. Nothing is uploaded.
* Metadata is read first and the bytes dropped, then each stack is read again to merge: a folder of
* raws must not all sit in memory at once.
*/
export async function mergeFolderExposures(opts: {
files: readonly FolderExposure[];
selectedIds: readonly string[];
readFile: (path: string) => Promise<Uint8Array>;
readMeta: (bytes: Uint8Array) => string | Promise<string>;
mergeDng: (files: Uint8Array[]) => Uint8Array;
saveDng: (dir: string, name: string, bytes: Uint8Array) => Promise<void>;
onStatus?: (stack: number, total: number) => void;
}): Promise<number> {
const candidates = opts.files.filter((file) => !isMergedName(file.name));
const selected = new Set(opts.selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? candidates.filter((file) => selected.has(file.path)) : candidates;
if (pool.length < 2) throw new MergeError("none");
const frames = [];
for (const file of pool) {
const bytes = await readOrMissing(opts.readFile, file.path);
frames.push(await frameOfFile(file, bytes, opts.readMeta));
}
const stacks = stacksOfFrames(frames, opts.selectedIds);
if (stacks.length === 0) throw new MergeError("none");
const byPath = new Map(pool.map((file) => [file.path, file]));
let made = 0;
for (let index = 0; index < stacks.length; index++) {
opts.onStatus?.(index + 1, stacks.length);
const members = (stacks[index] ?? []).map((id) => byPath.get(id)).filter((file): file is FolderExposure => !!file);
if (members.length < 2) throw new MergeError("none");
const files: Uint8Array[] = [];
for (const member of members) files.push(await readOrMissing(opts.readFile, member.path));
const dng = mergedOrFailed(opts.mergeDng, files);
const mid = members[Math.floor((members.length - 1) / 2)]!;
try {
await opts.saveDng(parentDir(mid.path), `${stemOf(mid.name)}-fundido.dng`, dng);
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("failed");
}
made += 1;
}
return made;
}
async function readOrMissing(readFile: (path: string) => Promise<Uint8Array>, path: string): Promise<Uint8Array> {
try {
const bytes = await readFile(path);
if (bytes.byteLength === 0) throw new MergeError("missing");
return bytes;
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("missing");
}
}
async function frameOfFile(
file: FolderExposure,
bytes: Uint8Array,
readMeta: (bytes: Uint8Array) => string | Promise<string>,
) {
try {
const tags = JSON.parse(await readMeta(bytes)) as Record<string, unknown>;
return frameFromCapture(file.path, file.name, tags);
} catch {
return { id: file.path, fileName: file.name };
}
}
function mergedOrFailed(mergeDng: (files: Uint8Array[]) => Uint8Array, files: Uint8Array[]): Uint8Array {
try {
const dng = mergeDng(files);
if (dng.byteLength === 0) throw new MergeError("failed");
return dng;
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("failed");
}
}
/**
* Merges the contact sheet in the desktop process. Metadata and the DNG stay there: sending every
* raw into the browser engine is what made a folder of CR3 fail with no reason.
*/
export async function mergeFolderNative(opts: {
files: readonly FolderExposure[];
selectedIds: readonly string[];
metaOf: (path: string) => Promise<string>;
mergePaths: (paths: readonly string[]) => Promise<void>;
onStatus?: (stack: number, total: number) => void;
}): Promise<number> {
const candidates = opts.files.filter((file) => !isMergedName(file.name));
const selected = new Set(opts.selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? candidates.filter((file) => selected.has(file.path)) : candidates;
if (pool.length < 2) throw new MergeError("none");
const frames = [];
for (const file of pool) {
try {
const tags = JSON.parse(await opts.metaOf(file.path)) as Record<string, unknown>;
frames.push(frameFromCapture(file.path, file.name, tags));
} catch (err) {
if (err instanceof MergeError) throw err;
frames.push({ id: file.path, fileName: file.name });
}
}
const stacks = stacksOfFrames(frames, opts.selectedIds);
if (stacks.length === 0) throw new MergeError("none");
let made = 0;
for (let index = 0; index < stacks.length; index++) {
opts.onStatus?.(index + 1, stacks.length);
const ids = stacks[index] ?? [];
if (ids.length < 2) throw new MergeError("none");
try {
await opts.mergePaths(ids);
} catch (err) {
if (err instanceof MergeError) throw err;
const detail = err instanceof Error ? err.message : String(err);
throw new MergeError("failed", detail);
}
made += 1;
}
return made;
}
/** The sentence under the button. An unknown failure keeps the desktop's reason, so the next try is not a guess. */
export function mergeFailureText(code: MergeError["code"], detail?: string): string {
if (code !== "failed" || !detail) return t.merge.errors[code];
const lower = detail.toLowerCase();
if (lower.includes("permission") || lower.includes("read-only") || lower.includes("operation not permitted")) {
return t.merge.errors.write;
}
if (lower.includes("cannot read the photo") || lower.includes("cannot be reduced")) {
return t.merge.errors.raw;
}
return t.merge.errors.failedDetail(detail);
}
/** The desktop merge: capture metadata and the linear DNG come from the develop engine. */
export async function mergeFolderOnDisk(opts: {
files: readonly FolderExposure[];
selectedIds: readonly string[];
readFile: (path: string) => Promise<Uint8Array>;
saveDng: (dir: string, name: string, bytes: Uint8Array) => Promise<void>;
onStatus?: (stack: number, total: number) => void;
}): Promise<number> {
let engine: EngineModule;
try {
engine = await loadEngine();
} catch {
throw new MergeError("engine");
}
return mergeFolderExposures({
...opts,
readMeta: (bytes) => engine.readCaptureMeta(bytes),
mergeDng: (files) => dngOf(engine, files),
});
}
function dngOf(engine: EngineModule, files: Uint8Array[]): Uint8Array {
const job = new engine.BracketJob();
try {
for (const file of files) job.push(file);
if (!job.mergeDng) throw new MergeError("engine");
const dng = job.mergeDng(MERGE_EDGE);
const copy = new Uint8Array(dng.byteLength);
copy.set(dng);
return copy;
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("failed");
} finally {
job.free();
}
}
+33
View File
@@ -37,6 +37,39 @@ describe("contact sheet", () => {
expect(onClose).toHaveBeenCalledOnce();
});
it("merges the photos on the sheet", async () => {
const user = userEvent.setup();
const merge = vi.fn(
async (_input: {
files: { path: string; name: string }[];
selectedIds: readonly string[];
onStatus: (stack: number, total: number) => void;
}) => 1,
);
render(
<FolderSheet
folder={{
path: "/job",
name: "Sala",
files: [
{ path: "/job/a.jpg", name: "a.jpg" },
{ path: "/job/b.jpg", name: "b.jpg" },
{ path: "/job/c.jpg", name: "c.jpg" },
],
}}
onClose={() => {}}
thumb={thumb}
merge={merge}
/>,
);
await user.click(screen.getByRole("button", { name: "Fundir exposições" }));
expect(merge).toHaveBeenCalledOnce();
const input = merge.mock.calls[0]![0];
expect(input.files.map((file) => file.name)).toEqual(["a.jpg", "b.jpg", "c.jpg"]);
expect(input.selectedIds).toEqual(["/job/a.jpg"]);
expect((await screen.findByRole("status")).textContent).toBe("1 DNG ficou nesta pasta.");
});
it("does not mount a thumbnail button for every file", () => {
const files = Array.from({ length: 200 }, (_, i) => ({ path: `/job/${i}.jpg`, name: `${i}.jpg` }));
render(<FolderSheet folder={{ path: "/job", name: "job", files }} onClose={() => {}} thumb={thumb} />);
+5 -2
View File
@@ -5,8 +5,11 @@ import { localOriginal } from "../platform.js";
import { MERGE_EDGE, stacksToMerge } from "./mergeStacks.js";
export class MergeError extends Error {
constructor(readonly code: "none" | "missing" | "engine" | "failed") {
super(code);
constructor(
readonly code: "none" | "missing" | "engine" | "failed",
readonly detail?: string,
) {
super(detail ? `${code}: ${detail}` : code);
}
}
+25 -17
View File
@@ -4,12 +4,14 @@ import { groupBrackets, type BracketFrame } from "@photoreport/metadata";
/** The engine's long-side cap for a merge. The DNG is this photo, not the full sensor. */
export const MERGE_EDGE = 4096;
/** A DNG this merge already wrote is not another exposure. */
export function isMergedName(name: string): boolean {
const lower = name.toLowerCase();
return lower.endsWith(".dng") || lower.includes("-fundido");
}
function isMergedFile(photo: PhotoSummary): boolean {
const names = [photo.originalName, photo.name];
return names.some((name) => {
const lower = name.toLowerCase();
return lower.endsWith(".dng") || lower.includes("-fundido");
});
return isMergedName(photo.originalName) || isMergedName(photo.name);
}
export function frameOf(photo: PhotoSummary): BracketFrame {
@@ -27,25 +29,31 @@ export function frameOf(photo: PhotoSummary): BracketFrame {
};
}
function byCapture(a: PhotoSummary, b: PhotoSummary): number {
function byFrame(a: BracketFrame, b: BracketFrame): number {
const time = (a.capturedAt ?? "").localeCompare(b.capturedAt ?? "");
if (time !== 0) return time;
return (a.originalName || a.name).localeCompare(b.originalName || b.name, undefined, { numeric: true, sensitivity: "base" });
return (a.fileName ?? a.id).localeCompare(b.fileName ?? b.id, undefined, { numeric: true, sensitivity: "base" });
}
/**
* Stacks to merge. A selection of two or more is that set (detected into angles when they are brackets,
* otherwise one stack in capture order). With nothing selected, every bracket in the folder is a stack.
* A DNG already produced here is not an exposure.
* otherwise one stack in capture order). With fewer than two selected, every bracket in the folder is a stack.
*/
export function stacksOfFrames(frames: readonly BracketFrame[], selectedIds: readonly string[]): string[][] {
const selected = new Set(selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? frames.filter((frame) => selected.has(frame.id)) : [...frames];
if (pool.length < 2) return [];
const grouped = groupBrackets(pool);
if (grouped.stacks.length > 0) return grouped.stacks.map((stack) => stack.frameIds);
if (!chosen) return [];
return [[...pool].sort(byFrame).map((frame) => frame.id)];
}
/**
* Stacks in a library collection. A DNG already produced here is not an exposure.
*/
export function stacksToMerge(photos: readonly PhotoSummary[], selectedIds: readonly string[]): string[][] {
const ready = photos.filter((photo) => photo.status === "READY" && !isMergedFile(photo));
const selected = new Set(selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? ready.filter((photo) => selected.has(photo.id)) : ready;
if (pool.length < 2) return [];
const grouped = groupBrackets(pool.map(frameOf));
if (grouped.stacks.length > 0) return grouped.stacks.map((stack) => stack.frameIds);
if (!chosen) return [];
return [[...pool].sort(byCapture).map((photo) => photo.id)];
return stacksOfFrames(ready.map(frameOf), selectedIds);
}
+34 -3
View File
@@ -13,7 +13,9 @@ import { useFolderScan } from "../library/folderScan.js";
import { FacesView } from "../library/FacesView.js";
import { LookupBanner } from "../library/PhotoLookup.js";
import { FolderSheet } from "../library/FolderSheet.js";
import { beginDropWait, folderDropPath, htmlDropIsFolder, nativePaths, openFolder, folderThumb, type FolderListing } from "../library/folderDrop.js";
import { beginDropWait, folderDropPath, folderMeta, htmlDropIsFolder, mergeFolderDng, nativePaths, openFolder, folderThumb, type FolderListing } from "../library/folderDrop.js";
import { mergeFolderNative } from "../library/folderMerge.js";
import { MERGE_EDGE } from "../library/mergeStacks.js";
import { Grid, Loupe, type LoupeFace } from "../library/Grid.js";
import { InfoPanel } from "../library/InfoPanel.js";
import { IptcInfo } from "../library/IptcInfo.js";
@@ -577,7 +579,7 @@ export function LibraryPage() {
))}
</select>
)}
{canCull && state.scope && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
{canCull && !sheet && state.scope && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
<MergeButton api={api} orgId={orgId} eventId={state.scope === "inbox" ? null : state.scope} photos={state.photos} selectedIds={[...state.selected]} />
)}
{canCull && (
@@ -707,7 +709,36 @@ export function LibraryPage() {
/>
)}
{sheet ? (
<FolderSheet folder={sheet} onClose={() => setSheet(null)} thumb={folderThumb} />
<FolderSheet
folder={sheet}
onClose={() => setSheet(null)}
thumb={folderThumb}
{...(canCull
? {
merge: async (input: {
files: FolderListing["files"];
selectedIds: readonly string[];
onStatus: (stack: number, total: number) => void;
}) => {
const made = await mergeFolderNative({
files: input.files,
selectedIds: input.selectedIds,
onStatus: input.onStatus,
metaOf: folderMeta,
mergePaths: (paths) => mergeFolderDng(paths, MERGE_EDGE).then(() => undefined),
});
const folderPath = sheet.path;
try {
const listing = await openFolder(folderPath);
setSheet((current) => (current?.path === folderPath ? listing : current));
} catch {
// The DNG is already beside the frames. Reopening the folder shows it.
}
return made;
},
}
: {})}
/>
) : openingFolder ? (
<p className="p-8 text-center text-[13px] text-faint">{t.folderSheet.opening}</p>
) : view === "faces" && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? (
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.23",
"version": "0.3.24",
"private": true,
"type": "module",
"scripts": {
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.23"
version = "0.3.24"
edition = "2024"
publish = false
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
@@ -31,7 +31,7 @@ sha2 = "0.10"
libc = "0.2"
image = { version = "0.25", default-features = false, features = ["jpeg"] }
# Capture time and filmstrip thumbnails. The embedded-preview feature reads the camera JPEG; the browser build leaves it off.
photoreport-engine = { path = "../../../engine/core", features = ["embedded-preview"] }
photoreport-engine = { path = "../../../engine/core", features = ["embedded-preview", "photo-merge"] }
photoreport-faces = { path = "../../../workers/faces" }
tauri-plugin-dialog = "2"
tauri-plugin-updater = "2"
+4
View File
@@ -22,6 +22,10 @@ fn main() {
"folder_drop",
"folder_open",
"folder_thumb",
"folder_read",
"folder_meta",
"folder_merge_dng",
"folder_save_dng",
"ftp_preview",
"ftp_info",
"catalog_folders",
@@ -37,6 +37,10 @@
"allow-folder-drop",
"allow-folder-open",
"allow-folder-thumb",
"allow-folder-read",
"allow-folder-meta",
"allow-folder-merge-dng",
"allow-folder-save-dng",
"allow-ftp-preview",
"allow-ftp-info",
"allow-catalog-folders",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-merge-dng"
description = "Enables the folder_merge_dng command without any pre-configured scope."
commands.allow = ["folder_merge_dng"]
[[permission]]
identifier = "deny-folder-merge-dng"
description = "Denies the folder_merge_dng command without any pre-configured scope."
commands.deny = ["folder_merge_dng"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-meta"
description = "Enables the folder_meta command without any pre-configured scope."
commands.allow = ["folder_meta"]
[[permission]]
identifier = "deny-folder-meta"
description = "Denies the folder_meta command without any pre-configured scope."
commands.deny = ["folder_meta"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-read"
description = "Enables the folder_read command without any pre-configured scope."
commands.allow = ["folder_read"]
[[permission]]
identifier = "deny-folder-read"
description = "Denies the folder_read command without any pre-configured scope."
commands.deny = ["folder_read"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-save-dng"
description = "Enables the folder_save_dng command without any pre-configured scope."
commands.allow = ["folder_save_dng"]
[[permission]]
identifier = "deny-folder-save-dng"
description = "Denies the folder_save_dng command without any pre-configured scope."
commands.deny = ["folder_save_dng"]
+250 -2
View File
@@ -1,8 +1,8 @@
//! A folder dropped on the window, shown as a contact sheet.
//!
//! The page only learns the path because the operating system delivered it to this window. `folder_open` refuses
//! any other path, and a thumbnail is only read for a file inside a folder that was opened that way. Nothing is
//! uploaded, moved or deleted: the sheet is a view of the folder on this computer.
//! any other path, and a file is only read inside a folder that was opened that way. Nothing is uploaded.
//! The one write is a merged `-fundido.dng` beside the frames of an open sheet.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
@@ -80,6 +80,63 @@ impl OpenFolders {
}
Ok(canon)
}
/// Where a merged DNG may be written: a single `-fundido.dng` name, inside an opened folder, never through a
/// symlink that leaves it. Replacing an earlier merge of the same name is allowed.
pub fn allow_save_dng(&self, dir: &Path, name: &str, len: usize) -> Result<PathBuf, String> {
if len == 0 || len > MAX_DNG_BYTES {
return Err("bad_file".to_string());
}
if !is_fundido_dng(name) {
return Err("not_a_merge".to_string());
}
let dir = dir.canonicalize().map_err(|e| e.to_string())?;
if !dir.is_dir() {
return Err("not_a_folder".to_string());
}
let open = self.open.lock().unwrap();
if !open.iter().any(|root| dir.starts_with(root)) {
return Err("not_allowed".to_string());
}
let dest = dir.join(name);
match std::fs::symlink_metadata(&dest) {
Ok(meta) if meta.file_type().is_symlink() || !meta.is_file() => {
return Err("not_allowed".to_string());
}
_ => {}
}
Ok(dest)
}
}
/// A merged DNG is tens of megabytes. Anything larger is not this merge.
const MAX_DNG_BYTES: usize = 512 * 1024 * 1024;
fn is_fundido_dng(name: &str) -> bool {
if name.contains('/') || name.contains('\\') || name.contains('\0') || name.starts_with('.') {
return false;
}
let lower = name.to_ascii_lowercase();
lower.ends_with(".dng") && lower.contains("-fundido")
}
fn percent_decode(value: &str) -> String {
let bytes = value.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& i + 2 < bytes.len()
&& let Ok(v) = u8::from_str_radix(&value[i + 1..i + 3], 16)
{
out.push(v);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
fn sort_names(paths: &mut [PathBuf]) {
@@ -181,6 +238,113 @@ pub async fn folder_thumb(
Ok(tauri::ipc::Response::new(jpeg))
}
/// The original of one photo on the open sheet, so a merge can read the exposures.
#[tauri::command]
pub async fn folder_read(
folders: tauri::State<'_, OpenFolders>,
path: String,
) -> Result<tauri::ipc::Response, String> {
let file = folders.allow_file(Path::new(&path))?;
let bytes = tokio::fs::read(&file).await.map_err(|e| e.to_string())?;
Ok(tauri::ipc::Response::new(bytes))
}
/// Capture metadata of one photo on the open sheet. The bytes stay in this process.
#[tauri::command]
pub async fn folder_meta(
folders: tauri::State<'_, OpenFolders>,
path: String,
) -> Result<String, String> {
let file = folders.allow_file(Path::new(&path))?;
tokio::task::spawn_blocking(move || {
let bytes = std::fs::read(&file).map_err(|e| e.to_string())?;
Ok(photoreport_engine::capture::read_capture(&bytes).to_string())
})
.await
.map_err(|e| e.to_string())?
}
/// The files of one stack, in merge order, and where the DNG is written (beside the middle frame).
pub fn merge_plan(
folders: &OpenFolders,
paths: &[String],
) -> Result<(Vec<PathBuf>, PathBuf), String> {
if paths.len() < 2 {
return Err("none".to_string());
}
let mut files = Vec::with_capacity(paths.len());
for path in paths {
files.push(folders.allow_file(Path::new(path))?);
}
let mid = &files[(files.len() - 1) / 2];
let dir = mid.parent().ok_or_else(|| "failed".to_string())?;
let stem = mid
.file_stem()
.and_then(|s| s.to_str())
.ok_or_else(|| "failed".to_string())?;
let dest = folders.allow_save_dng(dir, &format!("{stem}-fundido.dng"), 1)?;
Ok((files, dest))
}
fn merge_files_to(files: &[PathBuf], dest: &Path, max_edge: u32) -> Result<(), String> {
let mut bufs = Vec::with_capacity(files.len());
for file in files {
bufs.push(std::fs::read(file).map_err(|e| e.to_string())?);
}
let refs: Vec<&[u8]> = bufs.iter().map(Vec::as_slice).collect();
let dng =
photoreport_engine::merge::merge_linear_dng(&refs, max_edge).map_err(|e| e.to_string())?;
if dng.is_empty() || dng.len() > MAX_DNG_BYTES {
return Err("bad_file".to_string());
}
std::fs::write(dest, dng).map_err(|e| e.to_string())
}
/// Merges one stack and writes the DNG beside the middle frame. The raws are not sent to the page.
#[tauri::command]
pub async fn folder_merge_dng(
folders: tauri::State<'_, OpenFolders>,
paths: Vec<String>,
max_edge: u32,
) -> Result<String, String> {
let (files, dest) = merge_plan(&folders, &paths)?;
tokio::task::spawn_blocking(move || {
merge_files_to(&files, &dest, max_edge)?;
Ok(dest.to_string_lossy().into_owned())
})
.await
.map_err(|e| e.to_string())?
}
/// Writes one merged DNG into an opened folder. The bytes are the request body; `dir` and `name` are
/// percent-encoded headers, so the DNG is not sent as a JSON array.
#[tauri::command]
pub async fn folder_save_dng(
request: tauri::ipc::Request<'_>,
folders: tauri::State<'_, OpenFolders>,
) -> Result<String, String> {
let header = |name: &str| {
request
.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.map(percent_decode)
.ok_or_else(|| format!("missing {name}"))
};
let dir = header("dir")?;
let name = header("name")?;
let tauri::ipc::InvokeBody::Raw(data) = request.body() else {
return Err("expected the file as the body".to_string());
};
// Copy before the write: the request does not live across the await.
let bytes = data.to_vec();
let path = folders.allow_save_dng(Path::new(&dir), &name, bytes.len())?;
tokio::fs::write(&path, &bytes)
.await
.map_err(|e| e.to_string())?;
Ok(path.to_string_lossy().into_owned())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -278,4 +442,88 @@ mod tests {
assert!(thumb.len() < bytes.len());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn a_merge_is_only_a_fundido_dng_inside_the_open_folder() {
let root = temp_dir("save");
let nested = root.join("sala");
std::fs::create_dir_all(&nested).unwrap();
let other = temp_dir("save-other");
let folders = OpenFolders::default();
folders.note(&[root.clone()]);
folders.open(&root).unwrap();
let saved = folders
.allow_save_dng(&nested, "IMG_0002-fundido.dng", 4)
.unwrap();
assert_eq!(
saved,
nested.canonicalize().unwrap().join("IMG_0002-fundido.dng")
);
assert_eq!(
folders
.allow_save_dng(&other, "IMG_0002-fundido.dng", 4)
.unwrap_err(),
"not_allowed"
);
assert_eq!(
folders
.allow_save_dng(&nested, "../IMG_0002-fundido.dng", 4)
.unwrap_err(),
"not_a_merge"
);
assert_eq!(
folders
.allow_save_dng(&nested, "IMG_0002.dng", 4)
.unwrap_err(),
"not_a_merge"
);
assert_eq!(
folders
.allow_save_dng(&nested, "IMG_0002-fundido.dng", 0)
.unwrap_err(),
"bad_file"
);
#[cfg(unix)]
{
let link = nested.join("IMG_0002-fundido.dng");
let outside = other.join("secret.dng");
std::fs::write(&outside, b"x").unwrap();
std::os::unix::fs::symlink(&outside, &link).unwrap();
assert_eq!(
folders
.allow_save_dng(&nested, "IMG_0002-fundido.dng", 4)
.unwrap_err(),
"not_allowed"
);
}
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(&other);
}
#[test]
fn a_stack_is_named_after_its_middle_frame() {
let root = temp_dir("plan");
let names = ["dark.jpg", "mid.jpg", "bright.jpg"];
for name in names {
std::fs::write(root.join(name), b"jpeg").unwrap();
}
let folders = OpenFolders::default();
folders.note(&[root.clone()]);
folders.open(&root).unwrap();
let paths: Vec<String> = names
.iter()
.map(|name| root.join(name).to_string_lossy().into_owned())
.collect();
let (files, dest) = merge_plan(&folders, &paths).unwrap();
assert_eq!(files.len(), 3);
assert_eq!(
dest.file_name().unwrap().to_string_lossy(),
"mid-fundido.dng"
);
assert_eq!(merge_plan(&folders, &paths[..1]).unwrap_err(), "none");
let _ = std::fs::remove_dir_all(&root);
}
}
+4
View File
@@ -145,6 +145,10 @@ pub fn run() {
browse::folder_drop,
browse::folder_open,
browse::folder_thumb,
browse::folder_read,
browse::folder_meta,
browse::folder_merge_dng,
browse::folder_save_dng,
ftp::ftp_preview,
ftp::ftp_info,
catalog::catalog_folders,
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.23",
"version": "0.3.24",
"identifier": "pt.photoreport.desktop",
"build": {
"devUrl": "http://localhost:5173",
+5 -3
View File
@@ -10,8 +10,10 @@ This file is the in-repo summary agents work from. Decisions dated 2026-10-11.
Final domain: `app.photoreport.pt`. Data (accounts, galleries, sales, squads) is imported, not restarted.
- Desktop = Tauri around the same React SPA (replaces the Flutter Studio).
- Develop engine = LightCraft crates (`lightcraft-develop`, `lightcraft-pipeline`, `lightcraft-raw`,
`lightcraft-codecs`, `lightcraft-faces`), pinned, behind `engine/core`. Not `lightcraft-engine`/`catalog`:
our catalog is the API.
`lightcraft-codecs`, `lightcraft-faces`), pinned, behind `engine/core`. Not `lightcraft-engine`/`catalog`
for the library: our catalog is the API. The desktop folder merge is the exception (`photo-merge`):
it runs LightCraft Photo Merge so a raw without its own matrices still gets colour tags in the DNG.
The browser engine leaves that feature off.
- Faces: `lightcraft-faces` (YuNet detection + AuraFace v1 recognition, SFace optional; pure Rust) in
`workers/faces`, a long-running process the background worker talks to over stdin/stdout. See "Faces" below.
Enabled for FPA (own photos, internal federation use for news and galleries); off by default elsewhere.
@@ -21,7 +23,7 @@ This file is the in-repo summary agents work from. Decisions dated 2026-10-11.
## Stack
Node 22 + TypeScript + Fastify · PostgreSQL 17 + pgvector · Prisma · queues as PostgreSQL tables
Node 24 + TypeScript + Fastify · PostgreSQL 17 + pgvector · Prisma · queues as PostgreSQL tables
(`FOR UPDATE SKIP LOCKED`) · Socket.io fanned out with `LISTEN/NOTIFY` · sharp + ExifTool · local storage now,
Garage (S3-compatible) later · SFTPGo (tusd later) · React + Vite + Tailwind (`apps/app`) · Next.js
(`apps/site`) · Tauri 2 (`apps/desktop`) · Rust (`engine`, `workers/render`) · Python (`workers/ml`).
+21 -1
View File
@@ -44,10 +44,30 @@ Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`r
| `infra/nginx/deploy-receiver.conf` | Exposes `/_deploy/gitea` to Gitea; `/_deploy/status` only locally. |
| `infra/pm2/api.config.cjs` | API processes (2 instances, cluster mode) and `photoreport-worker` (one, fork mode). |
## Runtime upgrades on an already-provisioned container
Bumping the Node version pinned in this repo (`.nvmrc`, `package.json#engines`, CI) does not touch the Node
binary already installed on a running container — that binary is provisioned once in "First-time setup" below
and only a human with host access can change it (agents never SSH into containers). `pr-api` (CT 264,
`10.10.50.61`) currently has Node 22 installed; before (or right after) the first deploy that lands with this
repo pinned to Node 24.22.1, a human needs to run, on that container:
```sh
curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash -
sudo apt-get install -y nodejs=24.22.1-1nodesource1
node -v # expect v24.22.1
pm2 reload all
```
(Adjust the exact `nodejs=` package version string to whatever NodeSource publishes for 24.22.1 at run time;
`apt list -a nodejs` after adding the repo shows the available build string.) Until that runs, `pr-api` keeps
serving on Node 22 even though the deployed code and lockfile target Node 24 — PM2 processes don't re-exec
against a different Node binary on their own.
## First-time setup of a container
1. Clone the repo to `/srv/photoreport` (read-only deploy key from Gitea).
2. Install Node 22, pnpm, PM2 (and Rust for `workers`); create the service `.env` from its `.env.example`.
2. Install Node 24.22.1, pnpm, PM2 (and Rust for `workers`); create the service `.env` from its `.env.example`.
3. `/etc/photoreport/deploy-receiver.env` from `infra/deploy-receiver/.env.example` (0600), with a new secret.
4. `pnpm install && pnpm --filter @photoreport/deploy-receiver build`, then enable
`photoreport-deploy-receiver.service` and include `infra/nginx/deploy-receiver.conf` in the site.
+5
View File
@@ -11,6 +11,9 @@ default = ["parallel"]
parallel = ["lightcraft-codecs/parallel"]
# Camera JPEG inside a raw, for the desktop filmstrip. Off in the browser build.
embedded-preview = []
# Write a merged DNG the way LightCraft Photo Merge does, including colour tags for CR2/CR3/NEF.
# Off in the browser build: that crate is the native app engine, not the develop core.
photo-merge = ["dep:lightcraft-engine", "dep:lightcraft-catalog"]
[dependencies]
lightcraft-develop = { workspace = true }
@@ -22,6 +25,8 @@ lightcraft-merge = { workspace = true }
lightcraft-raw = { workspace = true }
lightcraft-color = { workspace = true }
lightcraft-meta = { workspace = true }
lightcraft-engine = { workspace = true, optional = true }
lightcraft-catalog = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+97 -5
View File
@@ -10,10 +10,9 @@ use std::sync::Arc;
use lightcraft_color::Xy;
use lightcraft_develop::DevelopSettings;
use lightcraft_merge::frame::Frame;
use lightcraft_merge::{
Deghost, DngSamples, FrameColor, HdrOptions, HdrResult, merge_hdr, no_progress,
write_linear_dng,
};
use lightcraft_merge::{Deghost, FrameColor, HdrOptions, HdrResult, merge_hdr, no_progress};
#[cfg(not(feature = "photo-merge"))]
use lightcraft_merge::{DngSamples, write_linear_dng};
use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, auto};
use lightcraft_raster::Rgb32f;
use lightcraft_raster::resample::{Filter, fit};
@@ -233,7 +232,63 @@ pub fn merge_linear_dng(files: &[&[u8]], max_edge: u32) -> Result<Vec<u8>, Engin
"a bracket needs at least two exposures".into(),
));
}
let edge = clamped_edge(max_edge);
write_merged_dng(files, clamped_edge(max_edge))
}
/// LightCraft Photo Merge (`MergeJob`) reads each raw with `starting_colour_tags` before
/// `write_linear_dng`. A CR3 has no colour matrix of its own; without that step the file is a
/// linear DNG other raw tools refuse. The develop crates do not export the step.
#[cfg(feature = "photo-merge")]
fn write_merged_dng(files: &[&[u8]], edge: usize) -> Result<Vec<u8>, EngineError> {
use std::sync::Arc;
use lightcraft_catalog::PhotoId;
use lightcraft_engine::merge::{MergeFinish, MergeJob, MergeKind};
let owned: Vec<Vec<u8>> = files.iter().map(|file| (*file).to_vec()).collect();
let count = owned.len();
let read = Arc::new(move |path: &str| -> Result<Vec<u8>, String> {
let index: usize = path
.parse()
.map_err(|_| format!("bad frame index {path}"))?;
owned
.get(index)
.cloned()
.ok_or_else(|| format!("missing frame {index}"))
});
let sources = (0..count)
.map(|index| (PhotoId(index as u64), index.to_string()))
.collect();
let job = MergeJob {
kind: MergeKind::Hdr {
hdr: HdrOptions {
align: true,
deghost: Deghost::None,
},
},
finish: MergeFinish {
auto_settings: false,
stack: false,
show_overlay: false,
},
sources,
preview: Some(edge),
read,
};
let out = job
.run(&|_done, _stage| true)
.map_err(EngineError::Decode)?;
let raw = lightcraft_raw::decode(&out.dng).map_err(|e| EngineError::Decode(e.to_string()))?;
if !lightcraft_raw::color::has_matrix(&raw.color) {
return Err(EngineError::Decode(
"the merged file has no colour matrix, so other raw tools cannot open it".into(),
));
}
Ok(out.dng)
}
#[cfg(not(feature = "photo-merge"))]
fn write_merged_dng(files: &[&[u8]], edge: usize) -> Result<Vec<u8>, EngineError> {
let mut frames = Vec::with_capacity(files.len());
for file in files {
frames.push(load_bracket_frame(file, edge)?);
@@ -360,6 +415,11 @@ mod tests {
let files = [dark.as_slice(), mid.as_slice(), bright.as_slice()];
let dng = merge_linear_dng(&files, 256).expect("dng");
assert!(dng.len() > 64);
let raw = lightcraft_raw::decode(&dng).expect("colour tags");
assert!(
lightcraft_raw::color::has_matrix(&raw.color),
"a merged DNG without ColorMatrix is refused by other raw tools"
);
let source = crate::render::Source::decode(&dng, 256).expect("decode");
let (w, h) = source.size();
assert!(w >= 64 && h >= 64, "{w}x{h}");
@@ -370,6 +430,38 @@ mod tests {
);
}
/// Three camera raws in `PHOTOREPORT_MERGE_SAMPLES` (comma-separated paths). Confirms the
/// Photo Merge colour tags, which a synthetic linear DNG already has on its own.
#[cfg(feature = "photo-merge")]
#[test]
#[ignore = "local camera raws via PHOTOREPORT_MERGE_SAMPLES"]
fn a_camera_raw_merge_carries_lightcraft_colour_tags() {
let spec = std::env::var("PHOTOREPORT_MERGE_SAMPLES")
.expect("PHOTOREPORT_MERGE_SAMPLES is three raw paths separated by commas");
let paths: Vec<&str> = spec
.split(',')
.map(str::trim)
.filter(|path| !path.is_empty())
.collect();
assert!(paths.len() >= 2, "need at least two raws");
let mut owned = Vec::new();
for path in &paths {
let bytes = std::fs::read(path).unwrap_or_else(|err| panic!("{path}: {err}"));
owned.push(bytes);
}
let refs: Vec<&[u8]> = owned.iter().map(Vec::as_slice).collect();
let dng = merge_linear_dng(&refs, 4096).expect("dng");
let raw = lightcraft_raw::decode(&dng).expect("decode");
assert!(
lightcraft_raw::color::has_matrix(&raw.color),
"ColorMatrix missing"
);
assert!(
!raw.color.profile.is_empty(),
"matrix without the fitted camera look"
);
}
#[test]
fn one_photo_is_not_a_bracket() {
let mid = exposure_dng(0.0);
+5 -3
View File
@@ -1,8 +1,10 @@
{
"name": "photoreport",
"private": true,
"packageManager": "[email protected]",
"engines": { "node": ">=22" },
"packageManager": "[email protected]+sha512.f0dda8580f0ee9481c5c79a1d927b9164f2c478e90992ad268bbb2465a736984391d6333d2c327913578b2804af33474ca554ba29c04a8b13060a717675ae3ac",
"engines": {
"node": ">=24.22.1"
},
"scripts": {
"build": "pnpm -r build",
"typecheck": "pnpm -r typecheck",
@@ -13,6 +15,6 @@
"typescript": "^5.9.2",
"vitest": "4.1.11",
"tsx": "^4.20.3",
"@types/node": "^22.15.0"
"@types/node": "^24.9.1"
}
}
+47 -47
View File
@@ -15,8 +15,8 @@ importers:
.:
devDependencies:
'@types/node':
specifier: ^22.15.0
version: 22.20.5
specifier: ^24.9.1
version: 24.19.2
tsx:
specifier: ^4.20.3
version: 4.23.15
@@ -25,7 +25,7 @@ importers:
version: 5.9.3
vitest:
specifier: 4.1.11
version: 4.1.11(@types/node@22.20.5)([email protected])([email protected](@types/node@22.20.5)([email protected])([email protected])([email protected]))
version: 4.1.11(@types/node@24.19.2)([email protected])([email protected](@types/node@24.19.2)([email protected])([email protected])([email protected]))
apps/api:
dependencies:
@@ -55,7 +55,7 @@ importers:
version: 7.10.0
'@prisma/client':
specifier: ^7.10.0
version: 7.10.0([email protected](@types/node@22.20.5)(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])
version: 7.10.0([email protected](@types/node@24.19.2)(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])
basic-ftp:
specifier: 6.2.1
version: 6.2.1
@@ -79,7 +79,7 @@ importers:
version: 6.2.12
mysql2:
specifier: 3.24.4
version: 3.24.4(@types/node@22.20.5)
version: 3.24.4(@types/node@24.19.2)
nodemailer:
specifier: 10.0.13
version: 10.0.13
@@ -94,7 +94,7 @@ importers:
version: 10.4.0
sharp:
specifier: ^0.35.5
version: 0.35.5(@types/node@22.20.5)
version: 0.35.5(@types/node@24.19.2)
socket.io:
specifier: ^4.8.4
version: 4.8.4
@@ -122,7 +122,7 @@ importers:
version: 4.6.3
prisma:
specifier: ^7.10.0
version: 7.10.0(@types/node@22.20.5)(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])
version: 7.10.0(@types/node@24.19.2)(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])
socket.io-client:
specifier: ^4.8.4
version: 4.8.4
@@ -177,7 +177,7 @@ importers:
devDependencies:
'@tailwindcss/vite':
specifier: ^4.3.3
version: 4.3.3([email protected](@types/node@22.20.5)([email protected])([email protected])([email protected]))
version: 4.3.3([email protected](@types/node@24.19.2)([email protected])([email protected])([email protected]))
'@testing-library/react':
specifier: ^16.3.3
version: 16.3.3(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
@@ -195,7 +195,7 @@ importers:
version: 19.3.0(@types/[email protected])
'@vitejs/plugin-react':
specifier: ^5.2.0
version: 5.2.0([email protected](@types/node@22.20.5)([email protected])([email protected])([email protected]))
version: 5.2.0([email protected](@types/node@24.19.2)([email protected])([email protected])([email protected]))
jsdom:
specifier: ^30.1.2
version: 30.1.2
@@ -204,7 +204,7 @@ importers:
version: 4.3.3
vite:
specifier: ^7.3.7
version: 7.3.7(@types/node@22.20.5)([email protected])([email protected])([email protected])
version: 7.3.7(@types/node@24.19.2)([email protected])([email protected])([email protected])
apps/desktop:
devDependencies:
@@ -243,7 +243,7 @@ importers:
version: link:../../packages/contracts
next:
specifier: 15.5.27
version: 15.5.27(@types/node@22.20.5)([email protected]([email protected]))([email protected])
version: 15.5.27(@types/node@24.19.2)([email protected]([email protected]))([email protected])
react:
specifier: ^19.3.0
version: 19.3.0
@@ -1527,8 +1527,8 @@ packages:
'@types/[email protected]':
resolution: {integrity: sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==}
'@types/node@22.20.5':
resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==}
'@types/node@24.19.2':
resolution: {integrity: sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==}
'@types/[email protected]':
resolution: {integrity: sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==}
@@ -2974,8 +2974,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==}
undici-types@6.21.0:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
undici-types@7.24.6:
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
[email protected]:
resolution: {integrity: sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==}
@@ -3727,11 +3727,11 @@ snapshots:
'@prisma/[email protected]': {}
'@prisma/[email protected]([email protected](@types/node@22.20.5)(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])':
'@prisma/[email protected]([email protected](@types/node@24.19.2)(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])':
dependencies:
'@prisma/client-runtime-utils': 7.10.0
optionalDependencies:
prisma: 7.10.0(@types/node@22.20.5)(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])
prisma: 7.10.0(@types/node@24.19.2)(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])
typescript: 5.9.3
'@prisma/[email protected]':
@@ -4044,12 +4044,12 @@ snapshots:
'@tailwindcss/oxide-win32-arm64-msvc': 4.3.3
'@tailwindcss/oxide-win32-x64-msvc': 4.3.3
'@tailwindcss/[email protected]([email protected](@types/node@22.20.5)([email protected])([email protected])([email protected]))':
'@tailwindcss/[email protected]([email protected](@types/node@24.19.2)([email protected])([email protected])([email protected]))':
dependencies:
'@tailwindcss/node': 4.3.3
'@tailwindcss/oxide': 4.3.3
tailwindcss: 4.3.3
vite: 7.3.7(@types/node@22.20.5)([email protected])([email protected])([email protected])
vite: 7.3.7(@types/node@24.19.2)([email protected])([email protected])([email protected])
'@tauri-apps/[email protected]': {}
@@ -4159,7 +4159,7 @@ snapshots:
'@types/[email protected]':
dependencies:
'@types/node': 22.20.5
'@types/node': 24.19.2
'@types/[email protected]': {}
@@ -4205,23 +4205,23 @@ snapshots:
dependencies:
undici-types: 5.26.5
'@types/node@22.20.5':
'@types/node@24.19.2':
dependencies:
undici-types: 6.21.0
undici-types: 7.24.6
'@types/[email protected]':
dependencies:
'@types/node': 22.20.5
'@types/node': 24.19.2
'@types/[email protected]':
dependencies:
'@types/node': 22.20.5
'@types/node': 24.19.2
pg-protocol: 1.16.1
pg-types: 2.2.0
'@types/[email protected]':
dependencies:
'@types/node': 22.20.5
'@types/node': 24.19.2
'@types/[email protected](@types/[email protected])':
dependencies:
@@ -4241,7 +4241,7 @@ snapshots:
'@types/[email protected]':
dependencies:
'@types/node': 22.20.5
'@types/node': 24.19.2
'@visx/[email protected]':
dependencies:
@@ -4320,7 +4320,7 @@ snapshots:
d3-time-format: 4.1.0
internmap: 2.0.3
'@vitejs/[email protected]([email protected](@types/node@22.20.5)([email protected])([email protected])([email protected]))':
'@vitejs/[email protected]([email protected](@types/node@24.19.2)([email protected])([email protected])([email protected]))':
dependencies:
'@babel/core': 7.29.7
'@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/[email protected])
@@ -4328,7 +4328,7 @@ snapshots:
'@rolldown/pluginutils': 1.0.0-rc.3
'@types/babel__core': 7.20.5
react-refresh: 0.18.0
vite: 7.3.7(@types/node@22.20.5)([email protected])([email protected])([email protected])
vite: 7.3.7(@types/node@24.19.2)([email protected])([email protected])([email protected])
transitivePeerDependencies:
- supports-color
@@ -4341,13 +4341,13 @@ snapshots:
chai: 6.3.0
tinyrainbow: 3.2.0
'@vitest/[email protected]([email protected](@types/node@22.20.5)([email protected])([email protected])([email protected]))':
'@vitest/[email protected]([email protected](@types/node@24.19.2)([email protected])([email protected])([email protected]))':
dependencies:
'@vitest/spy': 4.1.11
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
vite: 7.3.7(@types/node@22.20.5)([email protected])([email protected])([email protected])
vite: 7.3.7(@types/node@24.19.2)([email protected])([email protected])([email protected])
'@vitest/[email protected]':
dependencies:
@@ -4742,7 +4742,7 @@ snapshots:
[email protected]:
dependencies:
'@types/cors': 2.8.19
'@types/node': 22.20.5
'@types/node': 24.19.2
'@types/ws': 8.18.2
accepts: 1.3.8
cookie: 0.7.2
@@ -5177,9 +5177,9 @@ snapshots:
rimraf: 2.4.5
optional: true
[email protected](@types/node@22.20.5):
[email protected](@types/node@24.19.2):
dependencies:
'@types/node': 22.20.5
'@types/node': 24.19.2
aws-ssl-profiles: 1.1.2
generate-function: 2.3.1
iconv-lite: 0.7.3
@@ -5202,7 +5202,7 @@ snapshots:
[email protected]: {}
[email protected](@types/node@22.20.5)([email protected]([email protected]))([email protected]):
[email protected](@types/node@24.19.2)([email protected]([email protected]))([email protected]):
dependencies:
'@next/env': 15.5.27
'@swc/helpers': 0.5.15
@@ -5220,7 +5220,7 @@ snapshots:
'@next/swc-linux-x64-musl': 15.5.27
'@next/swc-win32-arm64-msvc': 15.5.27
'@next/swc-win32-x64-msvc': 15.5.27
sharp: 0.35.5(@types/node@22.20.5)
sharp: 0.35.5(@types/node@24.19.2)
transitivePeerDependencies:
- '@babel/core'
- '@types/node'
@@ -5399,13 +5399,13 @@ snapshots:
ansi-styles: 5.2.0
react-is: 17.0.2
[email protected](@types/node@22.20.5)(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]):
[email protected](@types/node@24.19.2)(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]):
dependencies:
'@prisma/config': 7.10.0
'@prisma/dev': 0.24.17([email protected])
'@prisma/engines': 7.10.0
'@prisma/studio-core': 0.33.0(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
mysql2: 3.24.4(@types/node@22.20.5)
mysql2: 3.24.4(@types/node@24.19.2)
postgres: 3.4.7
optionalDependencies:
typescript: 5.9.3
@@ -5436,7 +5436,7 @@ snapshots:
'@protobufjs/path': 1.1.2
'@protobufjs/pool': 1.1.0
'@protobufjs/utf8': 1.1.2
'@types/node': 22.20.5
'@types/node': 24.19.2
long: 5.3.2
[email protected]: {}
@@ -5575,7 +5575,7 @@ snapshots:
[email protected]: {}
[email protected](@types/node@22.20.5):
[email protected](@types/node@24.19.2):
dependencies:
'@img/colour': 1.1.0
detect-libc: 2.1.2
@@ -5606,7 +5606,7 @@ snapshots:
'@img/sharp-win32-arm64': 0.35.5
'@img/sharp-win32-ia32': 0.35.5
'@img/sharp-win32-x64': 0.35.5
'@types/node': 22.20.5
'@types/node': 24.19.2
[email protected]:
dependencies:
@@ -5761,7 +5761,7 @@ snapshots:
[email protected]: {}
undici-types@6.21.0: {}
undici-types@7.24.6: {}
[email protected]: {}
@@ -5783,7 +5783,7 @@ snapshots:
[email protected]: {}
[email protected](@types/node@22.20.5)([email protected])([email protected])([email protected]):
[email protected](@types/node@24.19.2)([email protected])([email protected])([email protected]):
dependencies:
esbuild: 0.28.2
fdir: 6.5.0([email protected])
@@ -5792,16 +5792,16 @@ snapshots:
rollup: 4.64.5
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 22.20.5
'@types/node': 24.19.2
fsevents: 2.3.3
jiti: 2.7.0
lightningcss: 1.32.0
tsx: 4.23.15
[email protected](@types/node@22.20.5)([email protected])([email protected](@types/node@22.20.5)([email protected])([email protected])([email protected])):
[email protected](@types/node@24.19.2)([email protected])([email protected](@types/node@24.19.2)([email protected])([email protected])([email protected])):
dependencies:
'@vitest/expect': 4.1.11
'@vitest/mocker': 4.1.11([email protected](@types/node@22.20.5)([email protected])([email protected])([email protected]))
'@vitest/mocker': 4.1.11([email protected](@types/node@24.19.2)([email protected])([email protected])([email protected]))
'@vitest/pretty-format': 4.1.11
'@vitest/runner': 4.1.11
'@vitest/snapshot': 4.1.11
@@ -5818,10 +5818,10 @@ snapshots:
tinyexec: 1.3.1
tinyglobby: 0.2.17
tinyrainbow: 3.2.0
vite: 7.3.7(@types/node@22.20.5)([email protected])([email protected])([email protected])
vite: 7.3.7(@types/node@24.19.2)([email protected])([email protected])([email protected])
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 22.20.5
'@types/node': 24.19.2
jsdom: 30.1.2
transitivePeerDependencies:
- msw