Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
66ac11621c | ||
|
|
eb81f69fb8 | ||
|
|
cb67b0c329 | ||
|
|
e096c6153e | ||
|
|
fa2e494d99 | ||
|
|
ee617b12de | ||
|
|
a8a887e82f | ||
|
|
3a2828e4ca |
No files matched your search
@@ -27,7 +27,7 @@ jobs:
|
|||||||
- uses: pnpm/action-setup@v4
|
- uses: pnpm/action-setup@v4
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 24.22.1
|
||||||
cache: pnpm
|
cache: pnpm
|
||||||
- run: pnpm install --frozen-lockfile
|
- run: pnpm install --frozen-lockfile
|
||||||
- run: pnpm -r build
|
- run: pnpm -r build
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ jobs:
|
|||||||
- uses: pnpm/action-setup@v4
|
- uses: pnpm/action-setup@v4
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 24.22.1
|
||||||
- uses: dtolnay/rust-toolchain@stable
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
- name: Both Mac processors (universal app)
|
- name: Both Mac processors (universal app)
|
||||||
if: runner.os == 'macOS'
|
if: runner.os == 'macOS'
|
||||||
|
|||||||
Generated
+1702
-5
File diff suppressed because it is too large.
Load diff
@@ -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-raw = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||||
lightcraft-color = { 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" }
|
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 = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
|
|||||||
@@ -17,6 +17,48 @@ function renderWorker(): Worker | undefined {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let autoIds = 0;
|
let autoIds = 0;
|
||||||
|
let exportIds = 0;
|
||||||
|
|
||||||
|
/** Decodes one file into the render worker. A new key replaces whatever was open. */
|
||||||
|
export function openFrame(key: string, bytes: ArrayBuffer, maxEdge: number): Promise<void> {
|
||||||
|
const w = renderWorker();
|
||||||
|
if (!w) return Promise.reject(new Error("no worker"));
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const onMessage = (e: MessageEvent<WorkerReply>) => {
|
||||||
|
const msg = e.data;
|
||||||
|
if (msg.type === "opened" && msg.key === key) {
|
||||||
|
w.removeEventListener("message", onMessage);
|
||||||
|
resolve();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (msg.type === "error" && msg.key === key && msg.ticket === undefined) {
|
||||||
|
w.removeEventListener("message", onMessage);
|
||||||
|
reject(new Error(msg.message));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
w.addEventListener("message", onMessage);
|
||||||
|
w.postMessage({ type: "open", key, url: "", bytes, maxEdge } satisfies WorkerRequest, [bytes]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One full-size render of the photo already open in the loupe. The loupe keeps its own frame. */
|
||||||
|
export function exportFrame(key: string, settings: string, maxW: number, maxH: number): Promise<{ width: number; height: number; pixels: Uint8ClampedArray }> {
|
||||||
|
const w = renderWorker();
|
||||||
|
if (!w) return Promise.reject(new Error("no worker"));
|
||||||
|
const id = ++exportIds;
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const onMessage = (e: MessageEvent<WorkerReply>) => {
|
||||||
|
const msg = e.data;
|
||||||
|
if (msg.type !== "exported" && msg.type !== "exportError") return;
|
||||||
|
if (msg.id !== id) return;
|
||||||
|
w.removeEventListener("message", onMessage);
|
||||||
|
if (msg.type === "exported") resolve({ width: msg.width, height: msg.height, pixels: msg.pixels });
|
||||||
|
else reject(new Error(msg.message));
|
||||||
|
};
|
||||||
|
w.addEventListener("message", onMessage);
|
||||||
|
w.postMessage({ type: "export", id, key, settings, maxW, maxH } satisfies WorkerRequest);
|
||||||
|
});
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Asks the render worker for automatic values computed from the open photo (tone, white balance, or the
|
* Asks the render worker for automatic values computed from the open photo (tone, white balance, or the
|
||||||
* eyedropper at a point of the uncropped frame). Resolves with control id -> value, ready for `develop.set`.
|
* eyedropper at a point of the uncropped frame). Resolves with control id -> value, ready for `develop.set`.
|
||||||
@@ -59,6 +101,8 @@ interface ViewerProps {
|
|||||||
onError?: (message: string) => void;
|
onError?: (message: string) => void;
|
||||||
/** The original from this computer, when the desktop app has it (no download); null to use `sourceUrl`. */
|
/** The original from this computer, when the desktop app has it (no download); null to use `sourceUrl`. */
|
||||||
localSource?: () => Promise<ArrayBuffer | null>;
|
localSource?: () => Promise<ArrayBuffer | null>;
|
||||||
|
/** Longest side to decode, when this is not the 1:1 view. The loupe still draws only what fits the screen. */
|
||||||
|
decodeEdge?: number;
|
||||||
/** 1:1 (Lightroom's Z): the photo at its own pixels, scrolled to look around, from the full-resolution original. */
|
/** 1:1 (Lightroom's Z): the photo at its own pixels, scrolled to look around, from the full-resolution original. */
|
||||||
actualPixels?: boolean;
|
actualPixels?: boolean;
|
||||||
/** Eyedropper on: a click reports where (0..1 in the shown frame). */
|
/** Eyedropper on: a click reports where (0..1 in the shown frame). */
|
||||||
@@ -111,7 +155,7 @@ export function Viewer(props: ViewerProps) {
|
|||||||
if (!w) return;
|
if (!w) return;
|
||||||
const onMessage = (e: MessageEvent<WorkerReply>) => {
|
const onMessage = (e: MessageEvent<WorkerReply>) => {
|
||||||
const msg = e.data;
|
const msg = e.data;
|
||||||
if (msg.type === "auto") return;
|
if (msg.type === "auto" || msg.type === "exported" || msg.type === "exportError") return;
|
||||||
if (msg.type === "opened") {
|
if (msg.type === "opened") {
|
||||||
if (msg.key === photoKey) {
|
if (msg.key === photoKey) {
|
||||||
setOpened(msg.key);
|
setOpened(msg.key);
|
||||||
@@ -144,14 +188,15 @@ export function Viewer(props: ViewerProps) {
|
|||||||
void (async () => {
|
void (async () => {
|
||||||
const bytes = await (callbacks.current.localSource?.() ?? Promise.resolve(null)).catch(() => null);
|
const bytes = await (callbacks.current.localSource?.() ?? Promise.resolve(null)).catch(() => null);
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
const msg: WorkerRequest = { type: "open", key: photoKey, url: sourceUrl, ...(bytes && { bytes }), ...(callbacks.current.actualPixels && { maxEdge: FULL_EDGE }) };
|
const edge = callbacks.current.actualPixels ? FULL_EDGE : callbacks.current.decodeEdge;
|
||||||
|
const msg: WorkerRequest = { type: "open", key: photoKey, url: sourceUrl, ...(bytes && { bytes }), ...(edge ? { maxEdge: edge } : {}) };
|
||||||
w.postMessage(msg, bytes ? [bytes] : []);
|
w.postMessage(msg, bytes ? [bytes] : []);
|
||||||
})();
|
})();
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
w.removeEventListener("message", onMessage);
|
w.removeEventListener("message", onMessage);
|
||||||
};
|
};
|
||||||
}, [photoKey, sourceUrl, send]);
|
}, [photoKey, sourceUrl, send, props.decodeEdge]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (opened !== photoKey || !size.w || !size.h) return;
|
if (opened !== photoKey || !size.w || !size.h) return;
|
||||||
|
|||||||
@@ -89,10 +89,14 @@ export type WorkerRequest =
|
|||||||
| { type: "open"; key: string; url: string; bytes?: ArrayBuffer; maxEdge?: number }
|
| { type: "open"; key: string; url: string; bytes?: ArrayBuffer; maxEdge?: number }
|
||||||
| { type: "render"; ticket: number; key: string; settings: string; maxW: number; maxH: number; draft: boolean; applyCrop: boolean }
|
| { type: "render"; ticket: number; key: string; settings: string; maxW: number; maxH: number; draft: boolean; applyCrop: boolean }
|
||||||
/** Auto values from the photo itself: tone (under `settings`), white balance, or the eyedropper at x, y. */
|
/** Auto values from the photo itself: tone (under `settings`), white balance, or the eyedropper at x, y. */
|
||||||
| { type: "auto"; id: number; key: string; kind: "tone" | "wb" | "pick" | "level"; settings?: string; x?: number; y?: number };
|
| { type: "auto"; id: number; key: string; kind: "tone" | "wb" | "pick" | "level"; settings?: string; x?: number; y?: number }
|
||||||
|
/** One full render of the open photo, for a JPEG saved from Revelar. Does not replace the loupe frame. */
|
||||||
|
| { type: "export"; id: number; key: string; settings: string; maxW: number; maxH: number };
|
||||||
|
|
||||||
export type WorkerReply =
|
export type WorkerReply =
|
||||||
| { type: "opened"; key: string; sourceWidth: number; sourceHeight: number }
|
| { type: "opened"; key: string; sourceWidth: number; sourceHeight: number }
|
||||||
| { type: "frame"; ticket: number; key: string; width: number; height: number; pixels: Uint8ClampedArray }
|
| { type: "frame"; ticket: number; key: string; width: number; height: number; pixels: Uint8ClampedArray }
|
||||||
| { type: "error"; key: string; ticket?: number; message: string }
|
| { type: "error"; key: string; ticket?: number; message: string }
|
||||||
| { type: "auto"; id: number; values?: Record<string, number>; message?: string };
|
| { type: "auto"; id: number; values?: Record<string, number>; message?: string }
|
||||||
|
| { type: "exported"; id: number; width: number; height: number; pixels: Uint8ClampedArray }
|
||||||
|
| { type: "exportError"; id: number; message: string };
|
||||||
@@ -36,6 +36,18 @@ async function open(key: string, url: string, bytes?: ArrayBuffer, maxEdge = 204
|
|||||||
|
|
||||||
self.onmessage = async (e: MessageEvent<WorkerRequest>) => {
|
self.onmessage = async (e: MessageEvent<WorkerRequest>) => {
|
||||||
const msg = e.data;
|
const msg = e.data;
|
||||||
|
if (msg.type === "export") {
|
||||||
|
try {
|
||||||
|
const photo = current?.key === msg.key ? current.photo : await opening.get(msg.key);
|
||||||
|
if (!photo) throw new Error("photo not open");
|
||||||
|
photo.render(msg.settings, msg.maxW, msg.maxH, false, true);
|
||||||
|
const pixels = new Uint8ClampedArray(photo.pixels().buffer);
|
||||||
|
post({ type: "exported", id: msg.id, width: photo.width, height: photo.height, pixels }, [pixels.buffer]);
|
||||||
|
} catch (err) {
|
||||||
|
post({ type: "exportError", id: msg.id, message: err instanceof Error ? err.message : String(err) });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
if (msg.type === "open") {
|
if (msg.type === "open") {
|
||||||
const photo = await open(msg.key, msg.url, msg.bytes, msg.maxEdge);
|
const photo = await open(msg.key, msg.url, msg.bytes, msg.maxEdge);
|
||||||
|
|||||||
+26
-1
@@ -55,11 +55,33 @@ export const t = {
|
|||||||
folderSheet: {
|
folderSheet: {
|
||||||
opening: "A abrir a pasta…",
|
opening: "A abrir a pasta…",
|
||||||
close: "Fechar",
|
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.",
|
hint: "Folha de contacto desta pasta, neste computador. Não cria um evento nem envia fotografias. D abre o Revelar. Estrelas e marcas ficam só nesta sessão.",
|
||||||
|
develop: "Revelar",
|
||||||
|
developTitle: "Abre esta fotografia no Revelar, neste computador. Não envia o ficheiro.",
|
||||||
|
mergeTitle: "Funde as exposições desta pasta num DNG ao lado delas. As originais ficam. Não envia fotografias.",
|
||||||
|
alsoJpeg: "e o JPEG editado",
|
||||||
|
alsoJpegTitle: "No mesmo clique funde, grava o DNG, o JPEG revelado e o XMP com esses ajustes. Desmarca para gravar só o DNG.",
|
||||||
|
workingJpeg: (n: number, total: number) => `A revelar e a gravar o JPEG ${n} de ${total}…`,
|
||||||
|
merged: (n: number) => (n === 1 ? "1 DNG ficou nesta pasta." : `${n} DNG ficaram nesta pasta.`),
|
||||||
|
mergedBoth: (n: number) => (n === 1 ? "1 DNG e o JPEG editado ficaram nesta pasta." : `${n} DNG e os JPEG editados ficaram nesta pasta.`),
|
||||||
|
mergedDownload: (n: number) => (n === 1 ? "O DNG ficou nesta pasta. O JPEG foi descarregado." : "Os DNG ficaram nesta pasta. Os JPEG foram descarregados."),
|
||||||
empty: "Esta pasta não tem fotografias.",
|
empty: "Esta pasta não tem fotografias.",
|
||||||
failed: "Não foi possível abrir esta pasta.",
|
failed: "Não foi possível abrir esta pasta.",
|
||||||
count: (n: number) => (n === 1 ? "1 foto" : `${n} fotos`),
|
count: (n: number) => (n === 1 ? "1 foto" : `${n} fotos`),
|
||||||
},
|
},
|
||||||
|
folderDevelop: {
|
||||||
|
back: "Pasta",
|
||||||
|
preset: "Interior",
|
||||||
|
presetHelp: "Luz de dia, sombras abertas e janelas contidas. O XMP ao lado do DNG guarda estes ajustes para os mudares aqui.",
|
||||||
|
dressing: "A acertar brancos, luz e cor…",
|
||||||
|
save: "Guardar JPEG",
|
||||||
|
saving: "A gravar o JPEG…",
|
||||||
|
savedBeside: (name: string) => `${name} ficou nesta pasta.`,
|
||||||
|
savedDownload: (name: string) => `${name} foi descarregado.`,
|
||||||
|
saveFailed: "Não gravei o JPEG.",
|
||||||
|
openFailed: "Não abri esta fotografia no Revelar.",
|
||||||
|
adjustFailed: "Não apliquei este acerto.",
|
||||||
|
},
|
||||||
newEvent: "Novo evento",
|
newEvent: "Novo evento",
|
||||||
noEvents: "Sem eventos. Cria o primeiro.",
|
noEvents: "Sem eventos. Cria o primeiro.",
|
||||||
noPhotos: "Sem fotografias neste filtro.",
|
noPhotos: "Sem fotografias neste filtro.",
|
||||||
@@ -297,6 +319,9 @@ export const t = {
|
|||||||
missing: "Falta o ficheiro original de alguma exposição.",
|
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.",
|
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.",
|
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: {
|
card: {
|
||||||
|
|||||||
@@ -0,0 +1,330 @@
|
|||||||
|
import type { Module } from "@photoreport/contracts";
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { engineAuto, exportFrame, Viewer } from "../develop/Viewer.js";
|
||||||
|
import { loadEngine, type EngineModule } from "../develop/engine.js";
|
||||||
|
import { DevelopPanels } from "../develop/Panels.js";
|
||||||
|
import type { Crop } from "../develop/session.js";
|
||||||
|
import { t } from "../i18n.js";
|
||||||
|
import { jpegFromRgba } from "./finishMergedJpeg.js";
|
||||||
|
import { folderRead, saveDevelopedJpeg, saveDevelopedXmp } from "./folderDrop.js";
|
||||||
|
import type { FolderFile } from "./folderDrop.js";
|
||||||
|
import { developedJpegName, developedXmpName, developXmp, dirOf, FOLDER_DEVELOP_EDGE, interiorCommand, interiorPartial, partialFromSettings, partialFromXmp } from "./interiorPreset.js";
|
||||||
|
|
||||||
|
const MODULES: readonly Module[] = ["basic", "detail"];
|
||||||
|
const FULL: Crop = { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0, aspect: null };
|
||||||
|
|
||||||
|
const isTyping = (target: EventTarget | null) =>
|
||||||
|
target instanceof HTMLElement && (target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName));
|
||||||
|
|
||||||
|
function setCommand(values: Record<string, number>): string {
|
||||||
|
return JSON.stringify({ command: "develop.set", params: { values } });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Temperature and tint only take effect once the white balance is no longer As Shot. */
|
||||||
|
function applyValues(mod: EngineModule, settings: string, values: Record<string, number>): string {
|
||||||
|
let next = mod.apply(settings, setCommand(values));
|
||||||
|
if ("wb.temp" in values || "wb.tint" in values) {
|
||||||
|
next = mod.apply(next, JSON.stringify({ command: "develop.merge", params: { partial: { wb: { mode: "custom", scale: "kelvin" } } } }));
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Revelar for one file from a folder dropped on this computer. Settings stay in this window.
|
||||||
|
* Opening the photo applies the interior look (neutral whites, recovered windows, colour). Nothing is uploaded.
|
||||||
|
*/
|
||||||
|
export function FolderDevelop(props: {
|
||||||
|
files: readonly FolderFile[];
|
||||||
|
path: string;
|
||||||
|
onPath: (path: string) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const { files, path, onPath, onClose } = props;
|
||||||
|
const file = files.find((item) => item.path === path) ?? null;
|
||||||
|
const engineRef = useRef<EngineModule | null>(null);
|
||||||
|
const pathRef = useRef(path);
|
||||||
|
pathRef.current = path;
|
||||||
|
const remembered = useRef(new Map<string, string>());
|
||||||
|
const dressing = useRef<string | null>(null);
|
||||||
|
const [engine, setEngine] = useState<EngineModule | null>(null);
|
||||||
|
const [missing, setMissing] = useState(false);
|
||||||
|
const [settings, setSettings] = useState<string | null>(null);
|
||||||
|
const [opened, setOpened] = useState(false);
|
||||||
|
const [before, setBefore] = useState(false);
|
||||||
|
const [picking, setPicking] = useState(false);
|
||||||
|
const [dragging, setDragging] = useState(false);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [note, setNote] = useState<string | null>(null);
|
||||||
|
const strip = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let dead = false;
|
||||||
|
loadEngine().then(
|
||||||
|
(mod) => {
|
||||||
|
if (dead) return;
|
||||||
|
engineRef.current = mod;
|
||||||
|
setEngine(mod);
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
if (!dead) setMissing(true);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
dead = true;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!engine) return;
|
||||||
|
setSettings(remembered.current.get(path) ?? engine.defaultSettings());
|
||||||
|
setOpened(false);
|
||||||
|
setBefore(false);
|
||||||
|
setPicking(false);
|
||||||
|
}, [engine, path]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
strip.current?.querySelector("[data-current='true']")?.scrollIntoView({ inline: "center", block: "nearest" });
|
||||||
|
}, [path]);
|
||||||
|
|
||||||
|
const applyInterior = async (forPath: string, fromSidecar: boolean) => {
|
||||||
|
const mod = engineRef.current;
|
||||||
|
if (!mod || dressing.current === forPath) return;
|
||||||
|
dressing.current = forPath;
|
||||||
|
setNote(t.folderDevelop.dressing);
|
||||||
|
try {
|
||||||
|
let next = mod.defaultSettings();
|
||||||
|
let loaded = false;
|
||||||
|
if (fromSidecar) {
|
||||||
|
const slash = Math.max(forPath.lastIndexOf("/"), forPath.lastIndexOf("\\"));
|
||||||
|
const fileName = slash >= 0 ? forPath.slice(slash + 1) : forPath;
|
||||||
|
const xmpPath = `${dirOf(forPath)}/${developedXmpName(fileName)}`;
|
||||||
|
try {
|
||||||
|
const bytes = await folderRead(xmpPath);
|
||||||
|
const partial = partialFromXmp(new TextDecoder().decode(bytes));
|
||||||
|
if (partial) {
|
||||||
|
next = mod.apply(next, interiorCommand(partial));
|
||||||
|
loaded = true;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// No sidecar yet: the interior finish below is the first edit.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!loaded) {
|
||||||
|
let exposure: number | undefined;
|
||||||
|
try {
|
||||||
|
const tone = await engineAuto(forPath, "tone");
|
||||||
|
exposure = tone["light.exposure"];
|
||||||
|
} catch {
|
||||||
|
// The finish still opens the room when the photo has nothing to measure.
|
||||||
|
}
|
||||||
|
next = mod.apply(mod.defaultSettings(), interiorCommand(interiorPartial(exposure)));
|
||||||
|
}
|
||||||
|
if (pathRef.current !== forPath) return;
|
||||||
|
remembered.current.set(forPath, next);
|
||||||
|
setSettings(next);
|
||||||
|
setNote(null);
|
||||||
|
} catch {
|
||||||
|
if (pathRef.current !== forPath) return;
|
||||||
|
const next = mod.apply(mod.defaultSettings(), interiorCommand(interiorPartial(undefined)));
|
||||||
|
remembered.current.set(forPath, next);
|
||||||
|
setSettings(next);
|
||||||
|
setNote(null);
|
||||||
|
} finally {
|
||||||
|
if (dressing.current === forPath) dressing.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const index = files.findIndex((item) => item.path === path);
|
||||||
|
const go = (delta: number) => {
|
||||||
|
const next = files[index + delta];
|
||||||
|
if (next) onPath(next.path);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (isTyping(e.target)) return;
|
||||||
|
e.stopPropagation();
|
||||||
|
if (e.key === "Escape") {
|
||||||
|
e.preventDefault();
|
||||||
|
if (picking) setPicking(false);
|
||||||
|
else onClose();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.metaKey || e.ctrlKey || e.altKey) return;
|
||||||
|
if (e.key === "ArrowRight") {
|
||||||
|
e.preventDefault();
|
||||||
|
go(1);
|
||||||
|
} else if (e.key === "ArrowLeft") {
|
||||||
|
e.preventDefault();
|
||||||
|
go(-1);
|
||||||
|
} else if (e.key === "\\") setBefore((value) => !value);
|
||||||
|
else if (e.key.toLowerCase() === "w") setPicking((value) => !value);
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", onKey, true);
|
||||||
|
return () => window.removeEventListener("keydown", onKey, true);
|
||||||
|
}, [go, onClose, picking]);
|
||||||
|
|
||||||
|
const setValue = (id: string, value: number) => {
|
||||||
|
const mod = engineRef.current;
|
||||||
|
if (!mod || !settings) return;
|
||||||
|
setDragging(true);
|
||||||
|
const next = applyValues(mod, settings, { [id]: value });
|
||||||
|
remembered.current.set(path, next);
|
||||||
|
setSettings(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const save = async () => {
|
||||||
|
const mod = engineRef.current;
|
||||||
|
if (!mod || !settings || !file || saving) return;
|
||||||
|
setSaving(true);
|
||||||
|
setNote(t.folderDevelop.saving);
|
||||||
|
try {
|
||||||
|
const frame = await exportFrame(path, settings, FOLDER_DEVELOP_EDGE, FOLDER_DEVELOP_EDGE);
|
||||||
|
const blob = await jpegFromRgba(frame.pixels, frame.width, frame.height);
|
||||||
|
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||||
|
const name = developedJpegName(file.name);
|
||||||
|
const dir = dirOf(file.path);
|
||||||
|
const where = await saveDevelopedJpeg(dir, name, bytes);
|
||||||
|
const partial = partialFromSettings(settings);
|
||||||
|
if (partial) await saveDevelopedXmp(dir, developedXmpName(file.name), new TextEncoder().encode(developXmp(partial)));
|
||||||
|
setNote(where === "beside" ? t.folderDevelop.savedBeside(name) : t.folderDevelop.savedDownload(name));
|
||||||
|
} catch {
|
||||||
|
setNote(t.folderDevelop.saveFailed);
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!file) return null;
|
||||||
|
|
||||||
|
const shown = settings && before && engine ? engine.defaultSettings() : settings;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-0 flex-1 flex-col">
|
||||||
|
<div className="flex flex-wrap items-center gap-2 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
|
||||||
|
<button type="button" onClick={onClose} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
|
||||||
|
{t.folderDevelop.back}
|
||||||
|
</button>
|
||||||
|
<span className="min-w-0 flex-1 truncate text-ink" title={file.path}>
|
||||||
|
{file.name}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={t.folderDevelop.presetHelp}
|
||||||
|
disabled={!opened || !engine || saving}
|
||||||
|
onClick={() => void applyInterior(path, false)}
|
||||||
|
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{t.folderDevelop.preset}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={!opened || !settings || saving}
|
||||||
|
onClick={() => void save()}
|
||||||
|
className="h-6 border border-black bg-accent px-2.5 text-[12px] text-white disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{t.folderDevelop.save}
|
||||||
|
</button>
|
||||||
|
{note && (
|
||||||
|
<span role="status" className="max-w-sm truncate text-[12px] text-muted" title={note}>
|
||||||
|
{note}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{missing ? (
|
||||||
|
<p className="p-8 text-center text-[13px] text-faint">{t.dev.engineMissing}</p>
|
||||||
|
) : (
|
||||||
|
<div className="flex min-h-0 flex-1">
|
||||||
|
<div className="min-w-0 flex-1 bg-black">
|
||||||
|
{engine && shown ? (
|
||||||
|
<Viewer
|
||||||
|
photoKey={path}
|
||||||
|
sourceUrl=""
|
||||||
|
settings={shown}
|
||||||
|
dragging={dragging}
|
||||||
|
cropping={false}
|
||||||
|
crop={FULL}
|
||||||
|
decodeEdge={FOLDER_DEVELOP_EDGE}
|
||||||
|
localSource={() => folderRead(path).catch(() => null)}
|
||||||
|
picking={picking}
|
||||||
|
onSourceSize={() => {
|
||||||
|
setOpened(true);
|
||||||
|
if (!remembered.current.has(path)) void applyInterior(path, true);
|
||||||
|
}}
|
||||||
|
onPick={(u, v) => {
|
||||||
|
setPicking(false);
|
||||||
|
void (async () => {
|
||||||
|
const mod = engineRef.current;
|
||||||
|
if (!mod || !settings) return;
|
||||||
|
try {
|
||||||
|
const values = await engineAuto(path, "pick", { x: u, y: v });
|
||||||
|
const next = applyValues(mod, settings, values);
|
||||||
|
remembered.current.set(path, next);
|
||||||
|
setSettings(next);
|
||||||
|
} catch {
|
||||||
|
setNote(t.folderDevelop.adjustFailed);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}}
|
||||||
|
onError={() => setNote(t.folderDevelop.openFailed)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<p className="p-8 text-center font-mono text-[12px] text-faint">{t.dev.loading}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<aside className="w-80 shrink-0 overflow-y-auto border-l border-line bg-panel">
|
||||||
|
<DevelopPanels
|
||||||
|
modules={MODULES}
|
||||||
|
value={(id) => (engine && settings ? engine.value(settings, id) : Number.NaN)}
|
||||||
|
disabled={!opened || !engine}
|
||||||
|
onChange={setValue}
|
||||||
|
onEnd={() => setDragging(false)}
|
||||||
|
onSet={(values) => {
|
||||||
|
const mod = engineRef.current;
|
||||||
|
if (!mod || !settings) return;
|
||||||
|
const next = applyValues(mod, settings, values);
|
||||||
|
remembered.current.set(path, next);
|
||||||
|
setSettings(next);
|
||||||
|
}}
|
||||||
|
picking={picking}
|
||||||
|
onAuto={(kind) => {
|
||||||
|
if (kind === "pick") {
|
||||||
|
setPicking((value) => !value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void (async () => {
|
||||||
|
const mod = engineRef.current;
|
||||||
|
if (!mod || !settings) return;
|
||||||
|
try {
|
||||||
|
const values = await engineAuto(path, kind, kind === "tone" ? { settings } : {});
|
||||||
|
const next = applyValues(mod, settings, values);
|
||||||
|
remembered.current.set(path, next);
|
||||||
|
setSettings(next);
|
||||||
|
} catch {
|
||||||
|
setNote(t.folderDevelop.adjustFailed);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<div className="px-3 py-2 text-[11px] text-faint">{t.folderDevelop.presetHelp}</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div ref={strip} className="flex h-10 shrink-0 items-center gap-1 overflow-x-auto border-t border-line bg-chrome px-2">
|
||||||
|
{files.map((item) => (
|
||||||
|
<button
|
||||||
|
key={item.path}
|
||||||
|
type="button"
|
||||||
|
data-current={item.path === path ? "true" : "false"}
|
||||||
|
onClick={() => onPath(item.path)}
|
||||||
|
className={`h-6 max-w-40 shrink-0 truncate border px-2 font-mono text-[10px] ${
|
||||||
|
item.path === path ? "border-white/70 bg-cell-on text-ink" : "border-transparent text-muted hover:text-ink"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{item.name}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import type { ColorLabel, PhotoFlag, PhotoPatch } from "@photoreport/contracts";
|
import type { ColorLabel, PhotoFlag, PhotoPatch } from "@photoreport/contracts";
|
||||||
import { useEffect, useRef, useState, type CSSProperties } from "react";
|
import { useEffect, useRef, useState, type CSSProperties } from "react";
|
||||||
import { t } from "../i18n.js";
|
import { t } from "../i18n.js";
|
||||||
|
import { prefs } from "../platform.js";
|
||||||
import { LABEL_COLOR } from "./Grid.js";
|
import { LABEL_COLOR } from "./Grid.js";
|
||||||
import { FOLDER_CELL_H, FOLDER_CELL_W, FOLDER_GAP, folderCols, folderWindow } from "./folder-layout.js";
|
import { FOLDER_CELL_H, FOLDER_CELL_W, FOLDER_GAP, folderCols, folderWindow } from "./folder-layout.js";
|
||||||
import type { FolderListing } from "./folderDrop.js";
|
import type { FolderListing } from "./folderDrop.js";
|
||||||
|
import { mergeFailureText } from "./folderMerge.js";
|
||||||
|
import { MergeError } from "./mergeExposures.js";
|
||||||
import { isMac, patchForKey, pmPatchForKey } from "./store.js";
|
import { isMac, patchForKey, pmPatchForKey } from "./store.js";
|
||||||
|
|
||||||
interface Mark {
|
interface Mark {
|
||||||
@@ -66,8 +69,20 @@ export function FolderSheet(props: {
|
|||||||
folder: FolderListing;
|
folder: FolderListing;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
thumb: (path: string, edge: number) => Promise<ArrayBuffer | null>;
|
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[];
|
||||||
|
jpeg: boolean;
|
||||||
|
onStatus: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
|
||||||
|
}) => Promise<{ made: number; jpeg: "beside" | "download" | "none" }>;
|
||||||
|
/** Opens the focused file in Revelar. Absent where the sheet cannot edit. */
|
||||||
|
onDevelop?: (path: string) => void;
|
||||||
}) {
|
}) {
|
||||||
const { folder, onClose, thumb } = props;
|
const { folder, onClose, thumb, merge, onDevelop } = props;
|
||||||
const files = folder.files;
|
const files = folder.files;
|
||||||
const scroller = useRef<HTMLDivElement>(null);
|
const scroller = useRef<HTMLDivElement>(null);
|
||||||
const [width, setWidth] = useState(800);
|
const [width, setWidth] = useState(800);
|
||||||
@@ -78,6 +93,37 @@ export function FolderSheet(props: {
|
|||||||
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(files[0] ? [files[0].path] : []));
|
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(files[0] ? [files[0].path] : []));
|
||||||
const [marks, setMarks] = useState<ReadonlyMap<string, Mark>>(() => new Map());
|
const [marks, setMarks] = useState<ReadonlyMap<string, Mark>>(() => new Map());
|
||||||
const [loupe, setLoupe] = useState(false);
|
const [loupe, setLoupe] = useState(false);
|
||||||
|
const [mergeStatus, setMergeStatus] = useState<string | null>(null);
|
||||||
|
const [mergeFailed, setMergeFailed] = useState(false);
|
||||||
|
const [merging, setMerging] = useState(false);
|
||||||
|
const [alsoJpeg, setAlsoJpeg] = useState(() => prefs.get("folder.alsoJpeg") !== "0");
|
||||||
|
const mergePending = useRef(false);
|
||||||
|
|
||||||
|
const runMerge = () => {
|
||||||
|
if (!merge || mergePending.current) return;
|
||||||
|
const withJpeg = alsoJpeg;
|
||||||
|
mergePending.current = true;
|
||||||
|
setMerging(true);
|
||||||
|
setMergeFailed(false);
|
||||||
|
setMergeStatus(t.merge.reading);
|
||||||
|
void merge({
|
||||||
|
files,
|
||||||
|
selectedIds: [...selected],
|
||||||
|
jpeg: withJpeg,
|
||||||
|
onStatus: (stack, total, phase) => setMergeStatus(phase === "jpeg" ? t.folderSheet.workingJpeg(stack, total) : t.merge.working(stack, total)),
|
||||||
|
}).then(
|
||||||
|
(result) => setMergeStatus(result.jpeg === "beside" ? t.folderSheet.mergedBoth(result.made) : result.jpeg === "download" ? t.folderSheet.mergedDownload(result.made) : t.folderSheet.merged(result.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(() => {
|
useEffect(() => {
|
||||||
const el = scroller.current;
|
const el = scroller.current;
|
||||||
@@ -178,11 +224,16 @@ export function FolderSheet(props: {
|
|||||||
setLoupe(true);
|
setLoupe(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (e.key.toLowerCase() === "d" && focus && onDevelop) {
|
||||||
|
e.preventDefault();
|
||||||
|
onDevelop(focus);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (e.key.toLowerCase() === "g") setLoupe(false);
|
if (e.key.toLowerCase() === "g") setLoupe(false);
|
||||||
};
|
};
|
||||||
window.addEventListener("keydown", onKey, true);
|
window.addEventListener("keydown", onKey, true);
|
||||||
return () => window.removeEventListener("keydown", onKey, true);
|
return () => window.removeEventListener("keydown", onKey, true);
|
||||||
}, [anchor, cols, files, focus, loupe, marks, onClose, selected]);
|
}, [anchor, cols, files, focus, loupe, marks, onClose, onDevelop, selected]);
|
||||||
|
|
||||||
const pick = (path: string, e: React.MouseEvent) => {
|
const pick = (path: string, e: React.MouseEvent) => {
|
||||||
const paths = files.map((file) => file.path);
|
const paths = files.map((file) => file.path);
|
||||||
@@ -221,6 +272,46 @@ export function FolderSheet(props: {
|
|||||||
</span>
|
</span>
|
||||||
<span className="font-mono text-[11px] text-faint">{t.folderSheet.count(files.length)}</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>
|
<span className="hidden text-[11px] text-faint sm:inline">{t.folderSheet.hint}</span>
|
||||||
|
{onDevelop && focus && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={t.folderSheet.developTitle}
|
||||||
|
onClick={() => onDevelop(focus)}
|
||||||
|
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
|
||||||
|
>
|
||||||
|
{t.folderSheet.develop}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{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>
|
||||||
|
<label title={t.folderSheet.alsoJpegTitle} className="inline-flex items-center gap-1.5 text-[12px] text-ink">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={alsoJpeg}
|
||||||
|
disabled={merging}
|
||||||
|
onChange={(e) => {
|
||||||
|
setAlsoJpeg(e.target.checked);
|
||||||
|
prefs.set("folder.alsoJpeg", e.target.checked ? "1" : "0");
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{t.folderSheet.alsoJpeg}
|
||||||
|
</label>
|
||||||
|
{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">
|
<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}
|
{t.folderSheet.close}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -9,6 +9,13 @@ import { localPhotos } from "../offline/local.js";
|
|||||||
// the target has no organization, so a bare client is enough.
|
// the target has no organization, so a bare client is enough.
|
||||||
vi.mock("../auth.js", () => ({ useAuth: () => ({ api: {} }) }));
|
vi.mock("../auth.js", () => ({ useAuth: () => ({ api: {} }) }));
|
||||||
|
|
||||||
|
const autopilot = vi.hoisted(() => ({
|
||||||
|
run: (_args: unknown): Promise<void> => Promise.resolve(),
|
||||||
|
}));
|
||||||
|
vi.mock("../offline/autopilot.js", () => ({
|
||||||
|
planLocalAutopilot: (args: unknown) => autopilot.run(args),
|
||||||
|
}));
|
||||||
|
|
||||||
const status = (running: boolean): FtpStatus => ({
|
const status = (running: boolean): FtpStatus => ({
|
||||||
running,
|
running,
|
||||||
settings: { port: 2121, users: [{ name: "1dx", password: "1dx" }], ingest: "~/Desktop/ingest", workFolder: "~/Desktop/{year}/{date} - {event}", autoStart: false, uploadOriginals: false },
|
settings: { port: 2121, users: [{ name: "1dx", password: "1dx" }], ingest: "~/Desktop/ingest", workFolder: "~/Desktop/{year}/{date} - {event}", autoStart: false, uploadOriginals: false },
|
||||||
@@ -17,22 +24,26 @@ const status = (running: boolean): FtpStatus => ({
|
|||||||
error: null,
|
error: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
function fakeShell(files: IncomingFile[]) {
|
function fakeShell(files: IncomingFile[], originals = false) {
|
||||||
let running = false;
|
let running = false;
|
||||||
const calls: string[] = [];
|
const calls: string[] = [];
|
||||||
const sent: unknown[] = [];
|
const sent: unknown[] = [];
|
||||||
|
const asStatus = (runningNow: boolean): FtpStatus => ({
|
||||||
|
...status(runningNow),
|
||||||
|
settings: { ...status(runningNow).settings, uploadOriginals: originals },
|
||||||
|
});
|
||||||
const invoke = vi.fn(async (cmd: string, args?: Record<string, unknown>) => {
|
const invoke = vi.fn(async (cmd: string, args?: Record<string, unknown>) => {
|
||||||
calls.push(cmd);
|
calls.push(cmd);
|
||||||
switch (cmd) {
|
switch (cmd) {
|
||||||
case "ftp_status":
|
case "ftp_status":
|
||||||
return status(running);
|
return asStatus(running);
|
||||||
case "ftp_start":
|
case "ftp_start":
|
||||||
running = true;
|
running = true;
|
||||||
return status(true);
|
return asStatus(true);
|
||||||
case "ftp_take":
|
case "ftp_take":
|
||||||
return files.splice(0);
|
return files.splice(0);
|
||||||
case "ftp_read":
|
case "ftp_read":
|
||||||
return new TextEncoder().encode(`bytes of ${String(args?.path)}`).buffer;
|
return [...new TextEncoder().encode(`bytes of ${String(args?.path)}`)];
|
||||||
case "ftp_preview":
|
case "ftp_preview":
|
||||||
// Over the JSON bridge (page loaded from the server) binary answers arrive as arrays of numbers.
|
// Over the JSON bridge (page loaded from the server) binary answers arrive as arrays of numbers.
|
||||||
return [...new TextEncoder().encode(`preview of ${String(args?.path)}`)];
|
return [...new TextEncoder().encode(`preview of ${String(args?.path)}`)];
|
||||||
@@ -80,6 +91,30 @@ describe("local FTP feed", () => {
|
|||||||
for (const photo of localPhotos.list()) localPhotos.remove(photo.id);
|
for (const photo of localPhotos.list()) localPhotos.remove(photo.id);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("sends the original while detection is still running", async () => {
|
||||||
|
let release: (() => void) | undefined;
|
||||||
|
autopilot.run = () =>
|
||||||
|
new Promise((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
});
|
||||||
|
const shell = fakeShell([{ path: "/x/FTP/C.JPG", name: "C.JPG", size: 10, modifiedMs: 3 }], true);
|
||||||
|
const added: { name: string; kind: string }[] = [];
|
||||||
|
const add = (files: Iterable<File>, _eventId?: string, onSettled?: (f: File, s: UploadStatus) => void, original?: { sha256: string } | "original") => {
|
||||||
|
for (const f of files) {
|
||||||
|
added.push({ name: f.name, kind: original === "original" ? "original" : "preview" });
|
||||||
|
onSettled?.(f, "done");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const { result } = renderHook(() => useLocalFtp(add, true, shell.invoke));
|
||||||
|
await waitFor(() => expect(result.current.status).not.toBeNull());
|
||||||
|
act(() => result.current.setTarget({ id: "ev1", title: "ABC x Benfica", home: "ABC", away: "Benfica", startsAt: "2026-10-12T18:00:00Z" } as EventSummary));
|
||||||
|
await act(() => result.current.start());
|
||||||
|
await waitFor(() => expect(added).toEqual([{ name: "C.JPG", kind: "original" }]));
|
||||||
|
release?.();
|
||||||
|
autopilot.run = () => Promise.resolve();
|
||||||
|
for (const photo of localPhotos.list()) localPhotos.remove(photo.id);
|
||||||
|
});
|
||||||
|
|
||||||
it("does nothing outside the desktop app", async () => {
|
it("does nothing outside the desktop app", async () => {
|
||||||
const shell = fakeShell([]);
|
const shell = fakeShell([]);
|
||||||
renderHook(() => useLocalFtp(() => {}, false, shell.invoke));
|
renderHook(() => useLocalFtp(() => {}, false, shell.invoke));
|
||||||
|
|||||||
@@ -60,6 +60,12 @@ const IN_FLIGHT = 6;
|
|||||||
* token expires, and the server answers 401. Two leaves room for the upload to leave.
|
* token expires, and the server answers 401. Two leaves room for the upload to leave.
|
||||||
*/
|
*/
|
||||||
const IN_FLIGHT_ORIGINALS = 2;
|
const IN_FLIGHT_ORIGINALS = 2;
|
||||||
|
/**
|
||||||
|
* Originals on the wire at once. One waits out each detection and each server reply, so a full card sits in
|
||||||
|
* ingest while the link is idle. This matches the upload queue. The slot stays held until that file has left,
|
||||||
|
* so the queue cannot pull the whole folder into memory.
|
||||||
|
*/
|
||||||
|
const ORIGINAL_UPLOADS = 4;
|
||||||
const POLL_MS = 1000;
|
const POLL_MS = 1000;
|
||||||
|
|
||||||
/** The shell put the file back on the queue because the camera has not finished sending it. */
|
/** The shell put the file back on the queue because the camera has not finished sending it. */
|
||||||
@@ -103,9 +109,11 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
|||||||
const [checkState, setCheckState] = useState<null | "busy" | "done" | "unsupported">(null);
|
const [checkState, setCheckState] = useState<null | "busy" | "done" | "unsupported">(null);
|
||||||
const backlog = useRef<IncomingFile[]>([]);
|
const backlog = useRef<IncomingFile[]>([]);
|
||||||
const inFlight = useRef(0);
|
const inFlight = useRef(0);
|
||||||
/** One full original at a time. Several at once freeze the window, and the preview must not wait for that. */
|
/** Originals being read or uploaded. The preview is already on screen and does not wait for these. */
|
||||||
const reading = useRef(0);
|
const reading = useRef(0);
|
||||||
const readQueue = useRef<(() => void)[]>([]);
|
const readQueue = useRef<(() => void)[]>([]);
|
||||||
|
/** Local detection, one photo at a time, off the upload path. */
|
||||||
|
const autopilotChain = useRef(Promise.resolve());
|
||||||
const targetRef = useRef(target);
|
const targetRef = useRef(target);
|
||||||
targetRef.current = target;
|
targetRef.current = target;
|
||||||
const originalsRef = useRef(false);
|
const originalsRef = useRef(false);
|
||||||
@@ -119,7 +127,7 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
|||||||
|
|
||||||
const pump = useCallback(() => {
|
const pump = useCallback(() => {
|
||||||
const takeOriginal = () => {
|
const takeOriginal = () => {
|
||||||
if (reading.current < 1) {
|
if (reading.current < ORIGINAL_UPLOADS) {
|
||||||
reading.current++;
|
reading.current++;
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
@@ -194,13 +202,19 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
const event = events.find((e) => e.id === eventId);
|
const event = events.find((e) => e.id === eventId);
|
||||||
await planLocalAutopilot({ api, orgId, event, sha256: info.sha256, preview, width: info.width, height: info.height }).catch(() => {});
|
// The cloud must not wait for detection. One at a time, or a full card freezes the window.
|
||||||
|
const plan = autopilotChain.current.then(() =>
|
||||||
|
planLocalAutopilot({ api, orgId, event, sha256: info.sha256, preview, width: info.width, height: info.height }).catch(() => {}),
|
||||||
|
);
|
||||||
|
autopilotChain.current = plan.then(
|
||||||
|
() => undefined,
|
||||||
|
() => undefined,
|
||||||
|
);
|
||||||
if (!full) {
|
if (!full) {
|
||||||
const file = new File([preview], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
|
const file = new File([preview], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
|
||||||
add([file], eventId ?? undefined, (_file, result, photo) => settle(_file, result, photo), info);
|
add([file], eventId ?? undefined, (_file, result, photo) => settle(_file, result, photo), info);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// One original at a time, and only when it is this file's turn to go up. Several at once freeze the window.
|
|
||||||
await takeOriginal();
|
await takeOriginal();
|
||||||
let held = true;
|
let held = true;
|
||||||
const drop = () => {
|
const drop = () => {
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { engineAuto, exportFrame, openFrame } from "../develop/Viewer.js";
|
||||||
|
import { loadEngine } from "../develop/engine.js";
|
||||||
|
import { folderRead, saveDevelopedJpeg, saveDevelopedXmp } from "./folderDrop.js";
|
||||||
|
import { developedJpegName, developedXmpName, developXmp, dirOf, FOLDER_DEVELOP_EDGE, interiorCommand, interiorPartial } from "./interiorPreset.js";
|
||||||
|
|
||||||
|
/** JPEG bytes of one rendered frame. The pixels are already the developed image. */
|
||||||
|
export async function jpegFromRgba(pixels: Uint8ClampedArray, width: number, height: number): Promise<Blob> {
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
canvas.width = width;
|
||||||
|
canvas.height = height;
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
if (!ctx) throw new Error("canvas");
|
||||||
|
const rgba = new Uint8ClampedArray(pixels.byteLength);
|
||||||
|
rgba.set(pixels);
|
||||||
|
ctx.putImageData(new ImageData(rgba, width, height), 0, 0);
|
||||||
|
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.92));
|
||||||
|
if (!blob) throw new Error("jpeg");
|
||||||
|
return blob;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The merged DNG, revealed for an interior (neutral whites, held windows, colour) and written beside it.
|
||||||
|
* `download` means this shell cannot write into the folder yet, so the file went to Downloads.
|
||||||
|
*/
|
||||||
|
export async function finishMergedJpeg(dngPath: string): Promise<"beside" | "download"> {
|
||||||
|
const engine = await loadEngine();
|
||||||
|
const bytes = await folderRead(dngPath);
|
||||||
|
const key = `${dngPath}#${Date.now()}`;
|
||||||
|
await openFrame(key, bytes.slice(0), FOLDER_DEVELOP_EDGE);
|
||||||
|
let exposure: number | undefined;
|
||||||
|
try {
|
||||||
|
const tone = await engineAuto(key, "tone");
|
||||||
|
exposure = tone["light.exposure"];
|
||||||
|
} catch {
|
||||||
|
// The finish still opens the room when the photo has nothing to measure.
|
||||||
|
}
|
||||||
|
const partial = interiorPartial(exposure);
|
||||||
|
const settings = engine.apply(engine.defaultSettings(), interiorCommand(partial));
|
||||||
|
const frame = await exportFrame(key, settings, FOLDER_DEVELOP_EDGE, FOLDER_DEVELOP_EDGE);
|
||||||
|
const blob = await jpegFromRgba(frame.pixels, frame.width, frame.height);
|
||||||
|
const jpeg = new Uint8Array(await blob.arrayBuffer());
|
||||||
|
const slash = Math.max(dngPath.lastIndexOf("/"), dngPath.lastIndexOf("\\"));
|
||||||
|
const fileName = slash >= 0 ? dngPath.slice(slash + 1) : dngPath;
|
||||||
|
const dir = dirOf(dngPath);
|
||||||
|
const where = await saveDevelopedJpeg(dir, developedJpegName(fileName), jpeg);
|
||||||
|
await saveDevelopedXmp(dir, developedXmpName(fileName), new TextEncoder().encode(developXmp(partial)));
|
||||||
|
return where;
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import { beginDropWait, htmlDropIsFolder, nativePaths, resetDropGate } from "./folderDrop.js";
|
import { beginDropWait, htmlDropIsFolder, nativePaths, resetDropGate, saveDevelopedJpeg } from "./folderDrop.js";
|
||||||
|
|
||||||
describe("folder drop", () => {
|
describe("folder drop", () => {
|
||||||
beforeEach(() => resetDropGate());
|
beforeEach(() => resetDropGate());
|
||||||
@@ -31,6 +31,18 @@ describe("folder drop", () => {
|
|||||||
await expect(wait).resolves.toBe("files");
|
await expect(wait).resolves.toBe("files");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("writes a developed jpeg beside the photo", async () => {
|
||||||
|
const writes: string[] = [];
|
||||||
|
const where = await saveDevelopedJpeg("/job", "a.jpg", new Uint8Array([1, 2]), async (dir, name) => {
|
||||||
|
writes.push(`${dir}/${name}`);
|
||||||
|
});
|
||||||
|
expect(where).toBe("beside");
|
||||||
|
expect(writes).toEqual(["/job/a.jpg"]);
|
||||||
|
await expect(saveDevelopedJpeg("/job", "a.jpg", new Uint8Array([1]), async () => {
|
||||||
|
throw new Error("permission denied");
|
||||||
|
})).rejects.toThrow(/permission/);
|
||||||
|
});
|
||||||
|
|
||||||
it("sees a directory item as a folder", () => {
|
it("sees a directory item as a folder", () => {
|
||||||
expect(htmlDropIsFolder([{ webkitGetAsEntry: () => ({ isDirectory: true }) }])).toBe(true);
|
expect(htmlDropIsFolder([{ webkitGetAsEntry: () => ({ isDirectory: true }) }])).toBe(true);
|
||||||
expect(htmlDropIsFolder([{ webkitGetAsEntry: () => ({ isDirectory: false }) }])).toBe(false);
|
expect(htmlDropIsFolder([{ webkitGetAsEntry: () => ({ isDirectory: false }) }])).toBe(false);
|
||||||
|
|||||||
@@ -116,6 +116,90 @@ 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 });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The original of one photo on the open sheet, so Revelar can decode it here. */
|
||||||
|
export async function folderRead(path: string, invoke: Invoke = desktopInvoke): Promise<ArrayBuffer> {
|
||||||
|
return asArrayBuffer(await invoke<unknown>("folder_read", { path }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The file is the raw body. `dir` and `name` ride in headers, the same way a merged DNG is written. */
|
||||||
|
async function writeJpegInShell(dir: string, name: string, bytes: Uint8Array): Promise<void> {
|
||||||
|
const { invoke } = await import("@tauri-apps/api/core");
|
||||||
|
await invoke<string>("folder_save_jpeg", bytes, {
|
||||||
|
headers: { dir: encodeURIComponent(dir), name: encodeURIComponent(name) },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function writeXmpInShell(dir: string, name: string, bytes: Uint8Array): Promise<void> {
|
||||||
|
const { invoke } = await import("@tauri-apps/api/core");
|
||||||
|
await invoke<string>("folder_save_xmp", bytes, {
|
||||||
|
headers: { dir: encodeURIComponent(dir), name: encodeURIComponent(name) },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writes the edit sidecar beside the DNG. A shell without the command leaves the JPEG as the only file. */
|
||||||
|
export async function saveDevelopedXmp(dir: string, name: string, bytes: Uint8Array, write?: (dir: string, name: string, bytes: Uint8Array) => Promise<void>): Promise<"beside" | "missing"> {
|
||||||
|
if (!dir) return "missing";
|
||||||
|
if (!write && !isDesktop()) return "missing";
|
||||||
|
try {
|
||||||
|
await (write ?? writeXmpInShell)(dir, name, bytes);
|
||||||
|
return "beside";
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
if (!write && /not found|unknown command/i.test(message)) return "missing";
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function downloadJpeg(name: string, bytes: Uint8Array): void {
|
||||||
|
const copy = new Uint8Array(bytes.byteLength);
|
||||||
|
copy.set(bytes);
|
||||||
|
const blob = new Blob([copy], { type: "image/jpeg" });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = url;
|
||||||
|
link.download = name;
|
||||||
|
link.click();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 1500);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes a developed JPEG into the opened folder. A shell from before this command downloads the file instead.
|
||||||
|
* `write` replaces the shell call in tests.
|
||||||
|
*/
|
||||||
|
export async function saveDevelopedJpeg(
|
||||||
|
dir: string,
|
||||||
|
name: string,
|
||||||
|
bytes: Uint8Array,
|
||||||
|
write?: (dir: string, name: string, bytes: Uint8Array) => Promise<void>,
|
||||||
|
): Promise<"beside" | "download"> {
|
||||||
|
if (!dir) throw new Error("not_a_folder");
|
||||||
|
if (write || isDesktop()) {
|
||||||
|
try {
|
||||||
|
await (write ?? writeJpegInShell)(dir, name, bytes);
|
||||||
|
return "beside";
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
const missing = !write && /not found|unknown command/i.test(message);
|
||||||
|
if (!missing) throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
downloadJpeg(name, bytes);
|
||||||
|
return "download";
|
||||||
|
}
|
||||||
|
|
||||||
export async function folderThumb(path: string, edge: number, invoke?: Invoke): Promise<ArrayBuffer | null> {
|
export async function folderThumb(path: string, edge: number, invoke?: Invoke): Promise<ArrayBuffer | null> {
|
||||||
if (!invoke && !isDesktop()) return null;
|
if (!invoke && !isDesktop()) return null;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
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.");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reveals each merged file when a jpeg was asked for", async () => {
|
||||||
|
const finished: string[] = [];
|
||||||
|
const phases: string[] = [];
|
||||||
|
const result = await mergeFolderNative({
|
||||||
|
files: pair,
|
||||||
|
selectedIds: pair.map((file) => file.path),
|
||||||
|
metaOf: async () => tags(0, 0),
|
||||||
|
onStatus: (stack, total, phase) => phases.push(`${phase ?? "merge"} ${stack}/${total}`),
|
||||||
|
mergePaths: async () => "/job/mid-fundido.dng",
|
||||||
|
finishJpeg: async (path) => {
|
||||||
|
finished.push(path);
|
||||||
|
return "beside";
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(result).toEqual({ made: 1, jpeg: "beside" });
|
||||||
|
expect(finished).toEqual(["/job/mid-fundido.dng"]);
|
||||||
|
expect(phases).toEqual(["merge 1/1", "jpeg 1/1"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
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>;
|
||||||
|
/** Merges one stack and returns the DNG path written beside the middle frame. */
|
||||||
|
mergePaths: (paths: readonly string[]) => Promise<string>;
|
||||||
|
/** When set, each DNG is also revealed and saved as a JPEG before the next stack. */
|
||||||
|
finishJpeg?: (dngPath: string) => Promise<"beside" | "download">;
|
||||||
|
onStatus?: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
|
||||||
|
}): Promise<{ made: number; jpeg: "beside" | "download" | "none" }> {
|
||||||
|
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;
|
||||||
|
let jpeg: "beside" | "download" | "none" = opts.finishJpeg ? "beside" : "none";
|
||||||
|
for (let index = 0; index < stacks.length; index++) {
|
||||||
|
const ids = stacks[index] ?? [];
|
||||||
|
if (ids.length < 2) throw new MergeError("none");
|
||||||
|
opts.onStatus?.(index + 1, stacks.length, "merge");
|
||||||
|
let dngPath = "";
|
||||||
|
try {
|
||||||
|
dngPath = 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);
|
||||||
|
}
|
||||||
|
if (opts.finishJpeg) {
|
||||||
|
opts.onStatus?.(index + 1, stacks.length, "jpeg");
|
||||||
|
try {
|
||||||
|
const where = await opts.finishJpeg(dngPath);
|
||||||
|
if (where === "download") jpeg = "download";
|
||||||
|
} 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, jpeg };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -37,6 +37,59 @@ describe("contact sheet", () => {
|
|||||||
expect(onClose).toHaveBeenCalledOnce();
|
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[];
|
||||||
|
jpeg: boolean;
|
||||||
|
onStatus: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
|
||||||
|
}) => ({ made: 1, jpeg: "none" as const }),
|
||||||
|
);
|
||||||
|
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(input.jpeg).toBe(true);
|
||||||
|
expect((await screen.findByRole("status")).textContent).toBe("1 DNG ficou nesta pasta.");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("opens the focused photo in develop", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const onDevelop = vi.fn();
|
||||||
|
render(
|
||||||
|
<FolderSheet
|
||||||
|
folder={{ path: "/job", name: "Sala", files: [{ path: "/job/a.jpg", name: "a.jpg" }, { path: "/job/b.jpg", name: "b.jpg" }] }}
|
||||||
|
onClose={() => {}}
|
||||||
|
thumb={thumb}
|
||||||
|
onDevelop={onDevelop}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
await user.click(screen.getByRole("button", { name: "Revelar" }));
|
||||||
|
expect(onDevelop).toHaveBeenCalledWith("/job/a.jpg");
|
||||||
|
onDevelop.mockClear();
|
||||||
|
await user.keyboard("d");
|
||||||
|
expect(onDevelop).toHaveBeenCalledWith("/job/a.jpg");
|
||||||
|
});
|
||||||
|
|
||||||
it("does not mount a thumbnail button for every file", () => {
|
it("does not mount a thumbnail button for every file", () => {
|
||||||
const files = Array.from({ length: 200 }, (_, i) => ({ path: `/job/${i}.jpg`, name: `${i}.jpg` }));
|
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} />);
|
render(<FolderSheet folder={{ path: "/job", name: "job", files }} onClose={() => {}} thumb={thumb} />);
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { developedJpegName, developedXmpName, developXmp, dirOf, interiorPartial, partialFromSettings, partialFromXmp } from "./interiorPreset.js";
|
||||||
|
|
||||||
|
describe("interior finish", () => {
|
||||||
|
it("opens the room from the photo's exposure and holds the windows", () => {
|
||||||
|
const next = interiorPartial(0.31);
|
||||||
|
expect(next.wb.mode).toBe("daylight");
|
||||||
|
expect(next.wb.temp).toBe(5500);
|
||||||
|
expect(next.wb.tint).toBe(10);
|
||||||
|
expect(next.light.exposure).toBe(0.71);
|
||||||
|
expect(next.light.contrast).toBe(12);
|
||||||
|
expect(next.light.highlights).toBe(-100);
|
||||||
|
expect(next.light.shadows).toBe(100);
|
||||||
|
expect(next.light.whites).toBe(-15);
|
||||||
|
expect(next.detail.sharpen_amount).toBe(40);
|
||||||
|
expect(next.detail.nr_color).toBe(25);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not let a bright or dark measurement throw the exposure away", () => {
|
||||||
|
expect(interiorPartial(2).light.exposure).toBe(1.15);
|
||||||
|
expect(interiorPartial(-2).light.exposure).toBe(0.35);
|
||||||
|
expect(interiorPartial(undefined).light.exposure).toBe(0.7);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("develop sidecar", () => {
|
||||||
|
it("writes the edit and reads the same sliders back", () => {
|
||||||
|
const partial = interiorPartial(0.31);
|
||||||
|
const back = partialFromXmp(developXmp(partial));
|
||||||
|
expect(back).toEqual(partial);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reads a sidecar another editor saved", () => {
|
||||||
|
const xml = `<rdf:Description crs:WhiteBalance="Custom" crs:Temperature="5200" crs:Tint="+4" crs:Exposure2012="+0.40" crs:Shadows2012="+80" crs:Highlights2012="-60"/>`;
|
||||||
|
const back = partialFromXmp(xml);
|
||||||
|
expect(back?.wb.mode).toBe("custom");
|
||||||
|
expect(back?.wb.temp).toBe(5200);
|
||||||
|
expect(back?.light.exposure).toBe(0.4);
|
||||||
|
expect(back?.light.shadows).toBe(80);
|
||||||
|
expect(back?.light.highlights).toBe(-60);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("takes the edit off the settings document", () => {
|
||||||
|
const partial = partialFromSettings(
|
||||||
|
JSON.stringify({
|
||||||
|
wb: { mode: "daylight", temp: 5500, tint: 10 },
|
||||||
|
light: { exposure: 0.71, contrast: 12, highlights: -100, shadows: 90, whites: -15, blacks: 4 },
|
||||||
|
color: { vibrance: 12, saturation: 0 },
|
||||||
|
effects: { clarity: 8, dehaze: 6 },
|
||||||
|
detail: { sharpen_amount: 40, nr_color: 25 },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(partial?.light.shadows).toBe(90);
|
||||||
|
expect(partial?.wb.mode).toBe("daylight");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("developed jpeg name", () => {
|
||||||
|
it("uses the file's own stem beside it", () => {
|
||||||
|
expect(developedJpegName("PSR10172-fundido.dng")).toBe("PSR10172-fundido.jpg");
|
||||||
|
expect(developedXmpName("PSR10172-fundido.dng")).toBe("PSR10172-fundido.xmp");
|
||||||
|
expect(developedJpegName("PSR10172.CR3")).toBe("PSR10172.jpg");
|
||||||
|
expect(developedJpegName("sala")).toBe("sala.jpg");
|
||||||
|
expect(dirOf("/Users/cyclop/Desktop/RAW/PSR10172-fundido.dng")).toBe("/Users/cyclop/Desktop/RAW");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
/** Longest side decoded for a folder photo in Revelar, and for the JPEG saved from it. */
|
||||||
|
export const FOLDER_DEVELOP_EDGE = 4096;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Daylight interior. Auto contrast (a high fixed value) was crushing the shadows it had just
|
||||||
|
* lifted, and a grey-world white balance on wood stayed warmer than the daylight the camera used.
|
||||||
|
* Exposure still follows the photo, a little brighter, and is kept inside a range that opens the
|
||||||
|
* room without throwing the windows away. The other sliders are the finish, not a nudge.
|
||||||
|
*/
|
||||||
|
export type InteriorPartial = {
|
||||||
|
wb: { mode: string; temp: number; tint: number; scale: "kelvin" };
|
||||||
|
light: { exposure: number; contrast: number; highlights: number; shadows: number; whites: number; blacks: number };
|
||||||
|
color: { vibrance: number; saturation: number };
|
||||||
|
effects: { clarity: number; dehaze: number };
|
||||||
|
detail: { sharpen_amount: number; nr_color: number };
|
||||||
|
};
|
||||||
|
|
||||||
|
const FINISH = {
|
||||||
|
contrast: 12,
|
||||||
|
highlights: -100,
|
||||||
|
shadows: 100,
|
||||||
|
whites: -15,
|
||||||
|
blacks: 4,
|
||||||
|
vibrance: 12,
|
||||||
|
saturation: 0,
|
||||||
|
clarity: 8,
|
||||||
|
dehaze: 6,
|
||||||
|
sharpen: 40,
|
||||||
|
nrColor: 25,
|
||||||
|
temp: 5500,
|
||||||
|
tint: 10,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function interiorPartial(autoExposure: number | undefined): InteriorPartial {
|
||||||
|
const base = Number.isFinite(autoExposure) ? (autoExposure as number) : 0.3;
|
||||||
|
const exposure = Math.round(Math.min(1.15, Math.max(0.35, base + 0.4)) * 100) / 100;
|
||||||
|
return {
|
||||||
|
wb: { mode: "daylight", temp: FINISH.temp, tint: FINISH.tint, scale: "kelvin" },
|
||||||
|
light: {
|
||||||
|
exposure,
|
||||||
|
contrast: FINISH.contrast,
|
||||||
|
highlights: FINISH.highlights,
|
||||||
|
shadows: FINISH.shadows,
|
||||||
|
whites: FINISH.whites,
|
||||||
|
blacks: FINISH.blacks,
|
||||||
|
},
|
||||||
|
color: { vibrance: FINISH.vibrance, saturation: FINISH.saturation },
|
||||||
|
effects: { clarity: FINISH.clarity, dehaze: FINISH.dehaze },
|
||||||
|
detail: { sharpen_amount: FINISH.sharpen, nr_color: FINISH.nrColor },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One develop.merge of the interior finish, including the daylight white balance. */
|
||||||
|
export function interiorCommand(partial: InteriorPartial): string {
|
||||||
|
return JSON.stringify({ command: "develop.merge", params: { partial } });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** JPEG written beside the file being developed: `PSR10172-fundido.dng` becomes `PSR10172-fundido.jpg`. */
|
||||||
|
export function developedJpegName(fileName: string): string {
|
||||||
|
const slash = Math.max(fileName.lastIndexOf("/"), fileName.lastIndexOf("\\"));
|
||||||
|
const base = slash >= 0 ? fileName.slice(slash + 1) : fileName;
|
||||||
|
const dot = base.lastIndexOf(".");
|
||||||
|
const stem = dot > 0 ? base.slice(0, dot) : base;
|
||||||
|
return `${stem || "foto"}.jpg`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sidecar with the same stem, so the edit can be opened and changed again. */
|
||||||
|
export function developedXmpName(fileName: string): string {
|
||||||
|
return developedJpegName(fileName).replace(/\.jpg$/i, ".xmp");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dirOf(path: string): string {
|
||||||
|
const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
|
||||||
|
if (slash <= 0) return "";
|
||||||
|
return path.slice(0, slash);
|
||||||
|
}
|
||||||
|
|
||||||
|
type SettingsDoc = {
|
||||||
|
wb?: { mode?: string; temp?: number; tint?: number };
|
||||||
|
light?: Partial<InteriorPartial["light"]>;
|
||||||
|
color?: Partial<InteriorPartial["color"]>;
|
||||||
|
effects?: Partial<InteriorPartial["effects"]>;
|
||||||
|
detail?: { sharpen_amount?: number; nr_color?: number };
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The edit currently on the photo, in the shape a sidecar stores. */
|
||||||
|
export function partialFromSettings(settings: string): InteriorPartial | null {
|
||||||
|
let doc: SettingsDoc;
|
||||||
|
try {
|
||||||
|
doc = JSON.parse(settings) as SettingsDoc;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!doc || typeof doc !== "object") return null;
|
||||||
|
const fallback = interiorPartial(0.3);
|
||||||
|
const num = (value: number | undefined, instead: number) => (typeof value === "number" && Number.isFinite(value) ? value : instead);
|
||||||
|
const mode = typeof doc.wb?.mode === "string" && doc.wb.mode ? doc.wb.mode : fallback.wb.mode;
|
||||||
|
return {
|
||||||
|
wb: {
|
||||||
|
mode,
|
||||||
|
temp: num(doc.wb?.temp, fallback.wb.temp),
|
||||||
|
tint: num(doc.wb?.tint, fallback.wb.tint),
|
||||||
|
scale: "kelvin",
|
||||||
|
},
|
||||||
|
light: {
|
||||||
|
exposure: num(doc.light?.exposure, fallback.light.exposure),
|
||||||
|
contrast: num(doc.light?.contrast, fallback.light.contrast),
|
||||||
|
highlights: num(doc.light?.highlights, fallback.light.highlights),
|
||||||
|
shadows: num(doc.light?.shadows, fallback.light.shadows),
|
||||||
|
whites: num(doc.light?.whites, fallback.light.whites),
|
||||||
|
blacks: num(doc.light?.blacks, fallback.light.blacks),
|
||||||
|
},
|
||||||
|
color: {
|
||||||
|
vibrance: num(doc.color?.vibrance, fallback.color.vibrance),
|
||||||
|
saturation: num(doc.color?.saturation, fallback.color.saturation),
|
||||||
|
},
|
||||||
|
effects: {
|
||||||
|
clarity: num(doc.effects?.clarity, fallback.effects.clarity),
|
||||||
|
dehaze: num(doc.effects?.dehaze, fallback.effects.dehaze),
|
||||||
|
},
|
||||||
|
detail: {
|
||||||
|
sharpen_amount: num(doc.detail?.sharpen_amount, fallback.detail.sharpen_amount),
|
||||||
|
nr_color: num(doc.detail?.nr_color, fallback.detail.nr_color),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const WB_LABEL: Record<string, string> = {
|
||||||
|
asShot: "As Shot",
|
||||||
|
auto: "Auto",
|
||||||
|
daylight: "Daylight",
|
||||||
|
cloudy: "Cloudy",
|
||||||
|
shade: "Shade",
|
||||||
|
tungsten: "Tungsten",
|
||||||
|
fluorescent: "Fluorescent",
|
||||||
|
flash: "Flash",
|
||||||
|
custom: "Custom",
|
||||||
|
};
|
||||||
|
|
||||||
|
function crsNumber(value: number, digits: number): string {
|
||||||
|
const text = digits === 0 ? String(Math.round(value)) : value.toFixed(digits);
|
||||||
|
return value > 0 ? `+${text}` : text;
|
||||||
|
}
|
||||||
|
|
||||||
|
function xmlAttr(value: string): string {
|
||||||
|
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sidecar in the camera-raw vocabulary: temperature, tint and the same sliders, so the edit can be
|
||||||
|
* read back here and by another raw editor that understands those names.
|
||||||
|
*/
|
||||||
|
export function developXmp(partial: InteriorPartial): string {
|
||||||
|
const wb = WB_LABEL[partial.wb.mode] ?? "Custom";
|
||||||
|
const attrs = [
|
||||||
|
`crs:Version="15.4"`,
|
||||||
|
`crs:ProcessVersion="11.0"`,
|
||||||
|
`crs:WhiteBalance="${xmlAttr(wb)}"`,
|
||||||
|
`crs:Temperature="${crsNumber(partial.wb.temp, 0)}"`,
|
||||||
|
`crs:Tint="${crsNumber(partial.wb.tint, 0)}"`,
|
||||||
|
`crs:Exposure2012="${crsNumber(partial.light.exposure, 2)}"`,
|
||||||
|
`crs:Contrast2012="${crsNumber(partial.light.contrast, 0)}"`,
|
||||||
|
`crs:Highlights2012="${crsNumber(partial.light.highlights, 0)}"`,
|
||||||
|
`crs:Shadows2012="${crsNumber(partial.light.shadows, 0)}"`,
|
||||||
|
`crs:Whites2012="${crsNumber(partial.light.whites, 0)}"`,
|
||||||
|
`crs:Blacks2012="${crsNumber(partial.light.blacks, 0)}"`,
|
||||||
|
`crs:Clarity2012="${crsNumber(partial.effects.clarity, 0)}"`,
|
||||||
|
`crs:Dehaze="${crsNumber(partial.effects.dehaze, 0)}"`,
|
||||||
|
`crs:Vibrance="${crsNumber(partial.color.vibrance, 0)}"`,
|
||||||
|
`crs:Saturation="${crsNumber(partial.color.saturation, 0)}"`,
|
||||||
|
`crs:Sharpness="${crsNumber(partial.detail.sharpen_amount, 0)}"`,
|
||||||
|
`crs:ColorNoiseReduction="${crsNumber(partial.detail.nr_color, 0)}"`,
|
||||||
|
].join(" ");
|
||||||
|
return `<?xml version="1.0" encoding="UTF-8"?>\n<x:xmpmeta xmlns:x="adobe:ns:meta/">\n <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n <rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" ${attrs}/>\n </rdf:RDF>\n</x:xmpmeta>\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function crsAttr(xml: string, name: string): string | undefined {
|
||||||
|
const match = new RegExp(`crs:${name}="([^"]*)"`).exec(xml);
|
||||||
|
return match?.[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
function crsFloat(xml: string, name: string): number | undefined {
|
||||||
|
const text = crsAttr(xml, name);
|
||||||
|
if (text === undefined) return undefined;
|
||||||
|
const value = Number(text);
|
||||||
|
return Number.isFinite(value) ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const WB_MODE: Record<string, string> = {
|
||||||
|
"as shot": "asShot",
|
||||||
|
auto: "auto",
|
||||||
|
daylight: "daylight",
|
||||||
|
cloudy: "cloudy",
|
||||||
|
shade: "shade",
|
||||||
|
tungsten: "tungsten",
|
||||||
|
fluorescent: "fluorescent",
|
||||||
|
flash: "flash",
|
||||||
|
custom: "custom",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The edit stored in a sidecar. Null when the packet has none of the sliders. */
|
||||||
|
export function partialFromXmp(xml: string): InteriorPartial | null {
|
||||||
|
const exposure = crsFloat(xml, "Exposure2012");
|
||||||
|
const shadows = crsFloat(xml, "Shadows2012");
|
||||||
|
const highlights = crsFloat(xml, "Highlights2012");
|
||||||
|
const temp = crsFloat(xml, "Temperature");
|
||||||
|
if (exposure === undefined && shadows === undefined && highlights === undefined && temp === undefined) return null;
|
||||||
|
const fallback = interiorPartial(exposure);
|
||||||
|
const label = (crsAttr(xml, "WhiteBalance") ?? "").toLowerCase().replace(/\s+/g, " ");
|
||||||
|
const mode = WB_MODE[label] ?? (temp === undefined ? fallback.wb.mode : "custom");
|
||||||
|
return {
|
||||||
|
wb: {
|
||||||
|
mode,
|
||||||
|
temp: temp ?? fallback.wb.temp,
|
||||||
|
tint: crsFloat(xml, "Tint") ?? fallback.wb.tint,
|
||||||
|
scale: "kelvin",
|
||||||
|
},
|
||||||
|
light: {
|
||||||
|
exposure: exposure ?? fallback.light.exposure,
|
||||||
|
contrast: crsFloat(xml, "Contrast2012") ?? fallback.light.contrast,
|
||||||
|
highlights: highlights ?? fallback.light.highlights,
|
||||||
|
shadows: shadows ?? fallback.light.shadows,
|
||||||
|
whites: crsFloat(xml, "Whites2012") ?? fallback.light.whites,
|
||||||
|
blacks: crsFloat(xml, "Blacks2012") ?? fallback.light.blacks,
|
||||||
|
},
|
||||||
|
color: {
|
||||||
|
vibrance: crsFloat(xml, "Vibrance") ?? fallback.color.vibrance,
|
||||||
|
saturation: crsFloat(xml, "Saturation") ?? fallback.color.saturation,
|
||||||
|
},
|
||||||
|
effects: {
|
||||||
|
clarity: crsFloat(xml, "Clarity2012") ?? fallback.effects.clarity,
|
||||||
|
dehaze: crsFloat(xml, "Dehaze") ?? fallback.effects.dehaze,
|
||||||
|
},
|
||||||
|
detail: {
|
||||||
|
sharpen_amount: crsFloat(xml, "Sharpness") ?? fallback.detail.sharpen_amount,
|
||||||
|
nr_color: crsFloat(xml, "ColorNoiseReduction") ?? fallback.detail.nr_color,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -5,8 +5,11 @@ import { localOriginal } from "../platform.js";
|
|||||||
import { MERGE_EDGE, stacksToMerge } from "./mergeStacks.js";
|
import { MERGE_EDGE, stacksToMerge } from "./mergeStacks.js";
|
||||||
|
|
||||||
export class MergeError extends Error {
|
export class MergeError extends Error {
|
||||||
constructor(readonly code: "none" | "missing" | "engine" | "failed") {
|
constructor(
|
||||||
super(code);
|
readonly code: "none" | "missing" | "engine" | "failed",
|
||||||
|
readonly detail?: string,
|
||||||
|
) {
|
||||||
|
super(detail ? `${code}: ${detail}` : code);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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. */
|
/** The engine's long-side cap for a merge. The DNG is this photo, not the full sensor. */
|
||||||
export const MERGE_EDGE = 4096;
|
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 {
|
function isMergedFile(photo: PhotoSummary): boolean {
|
||||||
const names = [photo.originalName, photo.name];
|
return isMergedName(photo.originalName) || isMergedName(photo.name);
|
||||||
return names.some((name) => {
|
|
||||||
const lower = name.toLowerCase();
|
|
||||||
return lower.endsWith(".dng") || lower.includes("-fundido");
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function frameOf(photo: PhotoSummary): BracketFrame {
|
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 ?? "");
|
const time = (a.capturedAt ?? "").localeCompare(b.capturedAt ?? "");
|
||||||
if (time !== 0) return time;
|
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,
|
* 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.
|
* otherwise one stack in capture order). With fewer than two selected, every bracket in the folder is a stack.
|
||||||
* A DNG already produced here is not an exposure.
|
*/
|
||||||
|
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[][] {
|
export function stacksToMerge(photos: readonly PhotoSummary[], selectedIds: readonly string[]): string[][] {
|
||||||
const ready = photos.filter((photo) => photo.status === "READY" && !isMergedFile(photo));
|
const ready = photos.filter((photo) => photo.status === "READY" && !isMergedFile(photo));
|
||||||
const selected = new Set(selectedIds);
|
return stacksOfFrames(ready.map(frameOf), 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)];
|
|
||||||
}
|
}
|
||||||
@@ -12,8 +12,12 @@ import { EventSettingsButton } from "../library/EventSettings.js";
|
|||||||
import { useFolderScan } from "../library/folderScan.js";
|
import { useFolderScan } from "../library/folderScan.js";
|
||||||
import { FacesView } from "../library/FacesView.js";
|
import { FacesView } from "../library/FacesView.js";
|
||||||
import { LookupBanner } from "../library/PhotoLookup.js";
|
import { LookupBanner } from "../library/PhotoLookup.js";
|
||||||
|
import { FolderDevelop } from "../library/FolderDevelop.js";
|
||||||
import { FolderSheet } from "../library/FolderSheet.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 { finishMergedJpeg } from "../library/finishMergedJpeg.js";
|
||||||
|
import { mergeFolderNative } from "../library/folderMerge.js";
|
||||||
|
import { MERGE_EDGE } from "../library/mergeStacks.js";
|
||||||
import { Grid, Loupe, type LoupeFace } from "../library/Grid.js";
|
import { Grid, Loupe, type LoupeFace } from "../library/Grid.js";
|
||||||
import { InfoPanel } from "../library/InfoPanel.js";
|
import { InfoPanel } from "../library/InfoPanel.js";
|
||||||
import { IptcInfo } from "../library/IptcInfo.js";
|
import { IptcInfo } from "../library/IptcInfo.js";
|
||||||
@@ -269,6 +273,7 @@ export function LibraryPage() {
|
|||||||
const fileInput = useRef<HTMLInputElement>(null);
|
const fileInput = useRef<HTMLInputElement>(null);
|
||||||
const [dragging, setDragging] = useState(false);
|
const [dragging, setDragging] = useState(false);
|
||||||
const [sheet, setSheet] = useState<FolderListing | null>(null);
|
const [sheet, setSheet] = useState<FolderListing | null>(null);
|
||||||
|
const [developPath, setDevelopPath] = useState<string | null>(null);
|
||||||
const [openingFolder, setOpeningFolder] = useState(false);
|
const [openingFolder, setOpeningFolder] = useState(false);
|
||||||
const [removeOpen, setRemoveOpen] = useState(false);
|
const [removeOpen, setRemoveOpen] = useState(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -288,6 +293,7 @@ export function LibraryPage() {
|
|||||||
(listing) => {
|
(listing) => {
|
||||||
if (dead) return;
|
if (dead) return;
|
||||||
setOpeningFolder(false);
|
setOpeningFolder(false);
|
||||||
|
setDevelopPath(null);
|
||||||
setSheet(listing);
|
setSheet(listing);
|
||||||
},
|
},
|
||||||
() => {
|
() => {
|
||||||
@@ -577,7 +583,7 @@ export function LibraryPage() {
|
|||||||
))}
|
))}
|
||||||
</select>
|
</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]} />
|
<MergeButton api={api} orgId={orgId} eventId={state.scope === "inbox" ? null : state.scope} photos={state.photos} selectedIds={[...state.selected]} />
|
||||||
)}
|
)}
|
||||||
{canCull && (
|
{canCull && (
|
||||||
@@ -706,8 +712,45 @@ export function LibraryPage() {
|
|||||||
onClose={() => void open(lookup.from ?? "inbox")}
|
onClose={() => void open(lookup.from ?? "inbox")}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{sheet ? (
|
{sheet && developPath && sheet.files.some((file) => file.path === developPath) ? (
|
||||||
<FolderSheet folder={sheet} onClose={() => setSheet(null)} thumb={folderThumb} />
|
<FolderDevelop files={sheet.files} path={developPath} onPath={setDevelopPath} onClose={() => setDevelopPath(null)} />
|
||||||
|
) : sheet ? (
|
||||||
|
<FolderSheet
|
||||||
|
folder={sheet}
|
||||||
|
onClose={() => {
|
||||||
|
setDevelopPath(null);
|
||||||
|
setSheet(null);
|
||||||
|
}}
|
||||||
|
onDevelop={setDevelopPath}
|
||||||
|
thumb={folderThumb}
|
||||||
|
{...(canCull
|
||||||
|
? {
|
||||||
|
merge: async (input: {
|
||||||
|
files: FolderListing["files"];
|
||||||
|
selectedIds: readonly string[];
|
||||||
|
jpeg: boolean;
|
||||||
|
onStatus: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
|
||||||
|
}) => {
|
||||||
|
const result = await mergeFolderNative({
|
||||||
|
files: input.files,
|
||||||
|
selectedIds: input.selectedIds,
|
||||||
|
onStatus: input.onStatus,
|
||||||
|
metaOf: folderMeta,
|
||||||
|
mergePaths: (paths) => mergeFolderDng(paths, MERGE_EDGE),
|
||||||
|
...(input.jpeg ? { finishJpeg: finishMergedJpeg } : {}),
|
||||||
|
});
|
||||||
|
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 result;
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {})}
|
||||||
|
/>
|
||||||
) : openingFolder ? (
|
) : openingFolder ? (
|
||||||
<p className="p-8 text-center text-[13px] text-faint">{t.folderSheet.opening}</p>
|
<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:") ? (
|
) : view === "faces" && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? (
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@photoreport/desktop",
|
"name": "@photoreport/desktop",
|
||||||
"version": "0.3.22",
|
"version": "0.3.24",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "photoreport-desktop"
|
name = "photoreport-desktop"
|
||||||
version = "0.3.22"
|
version = "0.3.24"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
publish = false
|
publish = false
|
||||||
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
|
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"
|
libc = "0.2"
|
||||||
image = { version = "0.25", default-features = false, features = ["jpeg"] }
|
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.
|
# 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" }
|
photoreport-faces = { path = "../../../workers/faces" }
|
||||||
tauri-plugin-dialog = "2"
|
tauri-plugin-dialog = "2"
|
||||||
tauri-plugin-updater = "2"
|
tauri-plugin-updater = "2"
|
||||||
|
|||||||
@@ -22,6 +22,12 @@ fn main() {
|
|||||||
"folder_drop",
|
"folder_drop",
|
||||||
"folder_open",
|
"folder_open",
|
||||||
"folder_thumb",
|
"folder_thumb",
|
||||||
|
"folder_read",
|
||||||
|
"folder_meta",
|
||||||
|
"folder_merge_dng",
|
||||||
|
"folder_save_dng",
|
||||||
|
"folder_save_jpeg",
|
||||||
|
"folder_save_xmp",
|
||||||
"ftp_preview",
|
"ftp_preview",
|
||||||
"ftp_info",
|
"ftp_info",
|
||||||
"catalog_folders",
|
"catalog_folders",
|
||||||
|
|||||||
@@ -37,6 +37,12 @@
|
|||||||
"allow-folder-drop",
|
"allow-folder-drop",
|
||||||
"allow-folder-open",
|
"allow-folder-open",
|
||||||
"allow-folder-thumb",
|
"allow-folder-thumb",
|
||||||
|
"allow-folder-read",
|
||||||
|
"allow-folder-meta",
|
||||||
|
"allow-folder-merge-dng",
|
||||||
|
"allow-folder-save-dng",
|
||||||
|
"allow-folder-save-jpeg",
|
||||||
|
"allow-folder-save-xmp",
|
||||||
"allow-ftp-preview",
|
"allow-ftp-preview",
|
||||||
"allow-ftp-info",
|
"allow-ftp-info",
|
||||||
"allow-catalog-folders",
|
"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"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-folder-save-jpeg"
|
||||||
|
description = "Enables the folder_save_jpeg command without any pre-configured scope."
|
||||||
|
commands.allow = ["folder_save_jpeg"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-folder-save-jpeg"
|
||||||
|
description = "Denies the folder_save_jpeg command without any pre-configured scope."
|
||||||
|
commands.deny = ["folder_save_jpeg"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-folder-save-xmp"
|
||||||
|
description = "Enables the folder_save_xmp command without any pre-configured scope."
|
||||||
|
commands.allow = ["folder_save_xmp"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-folder-save-xmp"
|
||||||
|
description = "Denies the folder_save_xmp command without any pre-configured scope."
|
||||||
|
commands.deny = ["folder_save_xmp"]
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
//! A folder dropped on the window, shown as a contact sheet.
|
//! 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
|
//! 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
|
//! any other path, and a file is only read inside a folder that was opened that way. Nothing is uploaded.
|
||||||
//! uploaded, moved or deleted: the sheet is a view of the folder on this computer.
|
//! Writes stay inside an opened folder: a merged `-fundido.dng`, or a JPEG exported from Revelar.
|
||||||
|
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
@@ -80,6 +80,154 @@ impl OpenFolders {
|
|||||||
}
|
}
|
||||||
Ok(canon)
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a developed JPEG may be written: one `.jpg` name, inside an opened folder, never through a symlink
|
||||||
|
/// that leaves it. Replacing an earlier export of the same name is allowed.
|
||||||
|
pub fn allow_save_jpeg(&self, dir: &Path, name: &str, len: usize) -> Result<PathBuf, String> {
|
||||||
|
if len == 0 || len > MAX_JPEG_BYTES {
|
||||||
|
return Err("bad_file".to_string());
|
||||||
|
}
|
||||||
|
if !is_jpeg_export(name) {
|
||||||
|
return Err("not_a_jpeg".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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An edit sidecar next to a photo in an opened folder. Same folder rules as the JPEG.
|
||||||
|
pub fn allow_save_xmp(&self, dir: &Path, name: &str, len: usize) -> Result<PathBuf, String> {
|
||||||
|
if len == 0 || len > MAX_XMP_BYTES {
|
||||||
|
return Err("bad_file".to_string());
|
||||||
|
}
|
||||||
|
if !is_xmp_sidecar(name) {
|
||||||
|
return Err("not_an_xmp".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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An existing sidecar in an opened folder, so Revelar can load the edit.
|
||||||
|
pub fn allow_xmp(&self, path: &Path) -> Result<PathBuf, String> {
|
||||||
|
let canon = path.canonicalize().map_err(|_| "not_found".to_string())?;
|
||||||
|
if !canon.is_file() {
|
||||||
|
return Err("not_found".to_string());
|
||||||
|
}
|
||||||
|
let name = canon.file_name().and_then(|n| n.to_str()).unwrap_or("");
|
||||||
|
if !is_xmp_sidecar(name) {
|
||||||
|
return Err("not_an_xmp".to_string());
|
||||||
|
}
|
||||||
|
let open = self.open.lock().unwrap();
|
||||||
|
if !open.iter().any(|root| canon.starts_with(root)) {
|
||||||
|
return Err("not_allowed".to_string());
|
||||||
|
}
|
||||||
|
Ok(canon)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 is_jpeg_export(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(".jpg") || lower.ends_with(".jpeg")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_xmp_sidecar(name: &str) -> bool {
|
||||||
|
if name.contains('/') || name.contains('\\') || name.contains('\0') || name.starts_with('.') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
name.to_ascii_lowercase().ends_with(".xmp")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A developed JPEG from Revelar. Larger than this is not a still from this editor.
|
||||||
|
const MAX_JPEG_BYTES: usize = 80 * 1024 * 1024;
|
||||||
|
|
||||||
|
/// An edit sidecar is a short XML packet. Anything larger is not one of these.
|
||||||
|
const MAX_XMP_BYTES: usize = 1024 * 1024;
|
||||||
|
|
||||||
|
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]) {
|
fn sort_names(paths: &mut [PathBuf]) {
|
||||||
@@ -181,6 +329,175 @@ pub async fn folder_thumb(
|
|||||||
Ok(tauri::ipc::Response::new(jpeg))
|
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 = if path.to_ascii_lowercase().ends_with(".xmp") {
|
||||||
|
folders.allow_xmp(Path::new(&path))?
|
||||||
|
} else {
|
||||||
|
folders.allow_file(Path::new(&path))?
|
||||||
|
};
|
||||||
|
let bytes = tokio::fs::read(&file).await.map_err(|e| e.to_string())?;
|
||||||
|
if path.to_ascii_lowercase().ends_with(".xmp") && bytes.len() > MAX_XMP_BYTES {
|
||||||
|
return Err("bad_file".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())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes one developed JPEG into an opened folder. The bytes are the request body; `dir` and `name` are
|
||||||
|
/// percent-encoded headers.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn folder_save_jpeg(
|
||||||
|
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());
|
||||||
|
};
|
||||||
|
let bytes = data.to_vec();
|
||||||
|
let path = folders.allow_save_jpeg(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())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the edit sidecar beside the DNG. The bytes are the request body; `dir` and `name` are percent-encoded headers.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn folder_save_xmp(
|
||||||
|
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());
|
||||||
|
};
|
||||||
|
let bytes = data.to_vec();
|
||||||
|
let path = folders.allow_save_xmp(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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -278,4 +595,143 @@ mod tests {
|
|||||||
assert!(thumb.len() < bytes.len());
|
assert!(thumb.len() < bytes.len());
|
||||||
let _ = std::fs::remove_dir_all(&root);
|
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_jpeg_export_stays_inside_the_open_folder() {
|
||||||
|
let root = temp_dir("jpeg");
|
||||||
|
let nested = root.join("sala");
|
||||||
|
std::fs::create_dir_all(&nested).unwrap();
|
||||||
|
let other = temp_dir("jpeg-other");
|
||||||
|
let folders = OpenFolders::default();
|
||||||
|
folders.note(&[root.clone()]);
|
||||||
|
folders.open(&root).unwrap();
|
||||||
|
|
||||||
|
let saved = folders.allow_save_jpeg(&nested, "IMG_0002.jpg", 4).unwrap();
|
||||||
|
assert_eq!(saved, nested.canonicalize().unwrap().join("IMG_0002.jpg"));
|
||||||
|
assert_eq!(
|
||||||
|
folders
|
||||||
|
.allow_save_jpeg(&other, "IMG_0002.jpg", 4)
|
||||||
|
.unwrap_err(),
|
||||||
|
"not_allowed"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
folders
|
||||||
|
.allow_save_jpeg(&nested, "../IMG_0002.jpg", 4)
|
||||||
|
.unwrap_err(),
|
||||||
|
"not_a_jpeg"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
folders
|
||||||
|
.allow_save_jpeg(&nested, "IMG_0002.dng", 4)
|
||||||
|
.unwrap_err(),
|
||||||
|
"not_a_jpeg"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
folders
|
||||||
|
.allow_save_jpeg(&nested, "IMG_0002.jpg", 0)
|
||||||
|
.unwrap_err(),
|
||||||
|
"bad_file"
|
||||||
|
);
|
||||||
|
let xmp = folders.allow_save_xmp(&nested, "IMG_0002.xmp", 20).unwrap();
|
||||||
|
assert_eq!(xmp, nested.canonicalize().unwrap().join("IMG_0002.xmp"));
|
||||||
|
assert_eq!(
|
||||||
|
folders
|
||||||
|
.allow_save_xmp(&nested, "../IMG_0002.xmp", 20)
|
||||||
|
.unwrap_err(),
|
||||||
|
"not_an_xmp"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
folders
|
||||||
|
.allow_save_xmp(&other, "IMG_0002.xmp", 20)
|
||||||
|
.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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -5,11 +5,11 @@
|
|||||||
//! then deletes the original; on any mismatch or error it never deletes, so a card is never emptied of a file
|
//! then deletes the original; on any mismatch or error it never deletes, so a card is never emptied of a file
|
||||||
//! that did not arrive whole. The last settings used are remembered (like Photo Mechanic's dialog).
|
//! that did not arrive whole. The last settings used are remembered (like Photo Mechanic's dialog).
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use chrono::{Datelike, Local, TimeZone};
|
use chrono::{Datelike, Local, TimeZone};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -20,8 +20,8 @@ use crate::local::sha256_file;
|
|||||||
|
|
||||||
/// RAW extensions we offload (lower-case, no dot).
|
/// RAW extensions we offload (lower-case, no dot).
|
||||||
const RAW_EXTS: &[&str] = &[
|
const RAW_EXTS: &[&str] = &[
|
||||||
"cr2", "cr3", "crw", "nef", "nrw", "arw", "srf", "sr2", "raf", "orf", "rw2", "pef", "srw", "x3f", "3fr", "iiq",
|
"cr2", "cr3", "crw", "nef", "nrw", "arw", "srf", "sr2", "raf", "orf", "rw2", "pef", "srw",
|
||||||
"erf", "kdc", "mrw", "dng", "raw",
|
"x3f", "3fr", "iiq", "erf", "kdc", "mrw", "dng", "raw",
|
||||||
];
|
];
|
||||||
const JPEG_EXTS: &[&str] = &["jpg", "jpeg"];
|
const JPEG_EXTS: &[&str] = &["jpg", "jpeg"];
|
||||||
const OTHER_IMAGE_EXTS: &[&str] = &["heic", "heif", "tif", "tiff", "png"];
|
const OTHER_IMAGE_EXTS: &[&str] = &["heic", "heif", "tif", "tiff", "png"];
|
||||||
@@ -29,7 +29,10 @@ const OTHER_IMAGE_EXTS: &[&str] = &["heic", "heif", "tif", "tiff", "png"];
|
|||||||
const SIDECAR_EXTS: &[&str] = &["wav", "xmp"];
|
const SIDECAR_EXTS: &[&str] = &["wav", "xmp"];
|
||||||
|
|
||||||
fn ext_of(path: &Path) -> String {
|
fn ext_of(path: &Path) -> String {
|
||||||
path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase()
|
path.extension()
|
||||||
|
.and_then(|e| e.to_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_ascii_lowercase()
|
||||||
}
|
}
|
||||||
fn is_raw(ext: &str) -> bool {
|
fn is_raw(ext: &str) -> bool {
|
||||||
RAW_EXTS.contains(&ext)
|
RAW_EXTS.contains(&ext)
|
||||||
@@ -44,7 +47,9 @@ fn is_image(ext: &str) -> bool {
|
|||||||
/// `~/x` -> the home folder; anything else as given.
|
/// `~/x` -> the home folder; anything else as given.
|
||||||
fn expand(p: &str) -> PathBuf {
|
fn expand(p: &str) -> PathBuf {
|
||||||
if let Some(rest) = p.strip_prefix("~/") {
|
if let Some(rest) = p.strip_prefix("~/") {
|
||||||
return dirs::home_dir().unwrap_or_else(std::env::temp_dir).join(rest);
|
return dirs::home_dir()
|
||||||
|
.unwrap_or_else(std::env::temp_dir)
|
||||||
|
.join(rest);
|
||||||
}
|
}
|
||||||
PathBuf::from(p)
|
PathBuf::from(p)
|
||||||
}
|
}
|
||||||
@@ -128,14 +133,21 @@ impl CardState {
|
|||||||
if let Some(dir) = file.parent() {
|
if let Some(dir) = file.parent() {
|
||||||
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||||
}
|
}
|
||||||
std::fs::write(&file, serde_json::to_vec_pretty(&s).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
|
std::fs::write(
|
||||||
|
&file,
|
||||||
|
serde_json::to_vec_pretty(&s).map_err(|e| e.to_string())?,
|
||||||
|
)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
*self.settings.lock().unwrap() = Some(s);
|
*self.settings.lock().unwrap() = Some(s);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn begin(&self, job_id: &str) -> Arc<AtomicBool> {
|
fn begin(&self, job_id: &str) -> Arc<AtomicBool> {
|
||||||
let flag = Arc::new(AtomicBool::new(false));
|
let flag = Arc::new(AtomicBool::new(false));
|
||||||
self.cancel.lock().unwrap().insert(job_id.to_string(), flag.clone());
|
self.cancel
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.insert(job_id.to_string(), flag.clone());
|
||||||
flag
|
flag
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,9 +314,13 @@ pub async fn card_scan(source: String, settings: Option<CardSettings>) -> Result
|
|||||||
}
|
}
|
||||||
let mut files = Vec::new();
|
let mut files = Vec::new();
|
||||||
collect(&root, &mut files);
|
collect(&root, &mut files);
|
||||||
let mode = settings.as_ref().map(|s| s.raw_jpeg).unwrap_or(RawJpeg::Both);
|
let mode = settings
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| s.raw_jpeg)
|
||||||
|
.unwrap_or(RawJpeg::Both);
|
||||||
let with_sidecars = settings.as_ref().map(|s| s.sidecars).unwrap_or(false);
|
let with_sidecars = settings.as_ref().map(|s| s.sidecars).unwrap_or(false);
|
||||||
let (mut raw, mut jpeg, mut other, mut bytes, mut sidecar_bytes) = (0usize, 0usize, 0usize, 0u64, 0u64);
|
let (mut raw, mut jpeg, mut other, mut bytes, mut sidecar_bytes) =
|
||||||
|
(0usize, 0usize, 0usize, 0u64, 0u64);
|
||||||
for f in &files {
|
for f in &files {
|
||||||
let ext = ext_of(f);
|
let ext = ext_of(f);
|
||||||
if !wanted(&ext, mode) {
|
if !wanted(&ext, mode) {
|
||||||
@@ -331,7 +347,14 @@ pub async fn card_scan(source: String, settings: Option<CardSettings>) -> Result
|
|||||||
}
|
}
|
||||||
None => (None, None),
|
None => (None, None),
|
||||||
};
|
};
|
||||||
Ok(CardScan { raw, jpeg, other, bytes, free_bytes, fits })
|
Ok(CardScan {
|
||||||
|
raw,
|
||||||
|
jpeg,
|
||||||
|
other,
|
||||||
|
bytes,
|
||||||
|
free_bytes,
|
||||||
|
fits,
|
||||||
|
})
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|e| e.to_string())?
|
.map_err(|e| e.to_string())?
|
||||||
@@ -428,7 +451,11 @@ fn report(app: Option<&AppHandle>, progress: &Progress) {
|
|||||||
/// Bytes still free for a normal user on the volume that holds `path` (the nearest existing parent).
|
/// Bytes still free for a normal user on the volume that holds `path` (the nearest existing parent).
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn volume_free(path: &Path) -> Option<u64> {
|
fn volume_free(path: &Path) -> Option<u64> {
|
||||||
let mut cursor = if path.as_os_str().is_empty() { PathBuf::from(".") } else { path.to_path_buf() };
|
let mut cursor = if path.as_os_str().is_empty() {
|
||||||
|
PathBuf::from(".")
|
||||||
|
} else {
|
||||||
|
path.to_path_buf()
|
||||||
|
};
|
||||||
loop {
|
loop {
|
||||||
if cursor.exists() {
|
if cursor.exists() {
|
||||||
break;
|
break;
|
||||||
@@ -494,17 +521,26 @@ fn plan_days(photos: &[PathBuf], settings: &CardSettings) -> Vec<DayPlan> {
|
|||||||
let mut rows: Vec<(String, Planned)> = Vec::with_capacity(photos.len());
|
let mut rows: Vec<(String, Planned)> = Vec::with_capacity(photos.len());
|
||||||
for src in photos {
|
for src in photos {
|
||||||
let ext = ext_of(src);
|
let ext = ext_of(src);
|
||||||
let name = src.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
let name = src
|
||||||
|
.file_name()
|
||||||
|
.map(|n| n.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
let when = capture_day(src, &ext);
|
let when = capture_day(src, &ext);
|
||||||
let key = day_key(&when);
|
let key = day_key(&when);
|
||||||
let folder = render_folder(&settings.folder_template, &when, &ext);
|
let folder = render_folder(&settings.folder_template, &when, &ext);
|
||||||
let dir = base.join(folder.trim_start_matches('/'));
|
let dir = base.join(folder.trim_start_matches('/'));
|
||||||
let photo_len = std::fs::metadata(src).map(|m| m.len()).unwrap_or(0);
|
let photo_len = std::fs::metadata(src).map(|m| m.len()).unwrap_or(0);
|
||||||
let target = dir.join(&name);
|
let target = dir.join(&name);
|
||||||
let photo_write = if target.exists() && !settings.overwrite { 0 } else { photo_len };
|
let photo_write = if target.exists() && !settings.overwrite {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
photo_len
|
||||||
|
};
|
||||||
let mut write_len = photo_write;
|
let mut write_len = photo_write;
|
||||||
if settings.sidecars {
|
if settings.sidecars {
|
||||||
if let (Some(stem), Some(parent)) = (src.file_stem().and_then(|s| s.to_str()), src.parent()) {
|
if let (Some(stem), Some(parent)) =
|
||||||
|
(src.file_stem().and_then(|s| s.to_str()), src.parent())
|
||||||
|
{
|
||||||
for ext in SIDECAR_EXTS {
|
for ext in SIDECAR_EXTS {
|
||||||
let side = parent.join(format!("{stem}.{ext}"));
|
let side = parent.join(format!("{stem}.{ext}"));
|
||||||
if !side.is_file() {
|
if !side.is_file() {
|
||||||
@@ -518,13 +554,26 @@ fn plan_days(photos: &[PathBuf], settings: &CardSettings) -> Vec<DayPlan> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
rows.push((key, Planned { src: src.clone(), dir, name, photo_len, write_len }));
|
rows.push((
|
||||||
|
key,
|
||||||
|
Planned {
|
||||||
|
src: src.clone(),
|
||||||
|
dir,
|
||||||
|
name,
|
||||||
|
photo_len,
|
||||||
|
write_len,
|
||||||
|
},
|
||||||
|
));
|
||||||
}
|
}
|
||||||
rows.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.src.cmp(&b.1.src)));
|
rows.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.src.cmp(&b.1.src)));
|
||||||
let mut days: Vec<DayPlan> = Vec::new();
|
let mut days: Vec<DayPlan> = Vec::new();
|
||||||
for (key, item) in rows {
|
for (key, item) in rows {
|
||||||
if days.last().map(|day| day.key.as_str()) != Some(key.as_str()) {
|
if days.last().map(|day| day.key.as_str()) != Some(key.as_str()) {
|
||||||
days.push(DayPlan { key, items: Vec::new(), write_len: 0 });
|
days.push(DayPlan {
|
||||||
|
key,
|
||||||
|
items: Vec::new(),
|
||||||
|
write_len: 0,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
let day = days.last_mut().unwrap();
|
let day = days.last_mut().unwrap();
|
||||||
day.write_len += item.write_len;
|
day.write_len += item.write_len;
|
||||||
@@ -562,17 +611,30 @@ fn room_for(settings: &CardSettings) -> Option<u64> {
|
|||||||
/// usually finish later, not sooner. A second card is a second call, so the two readers work at once.
|
/// usually finish later, not sooner. A second card is a second call, so the two readers work at once.
|
||||||
/// `room` limits how much may be written. Days are copied whole, oldest first; a day that does not fit is
|
/// `room` limits how much may be written. Days are copied whole, oldest first; a day that does not fit is
|
||||||
/// not started, and neither is any day after it. A move deletes a day's sources only once that day is complete.
|
/// not started, and neither is any day after it. A move deletes a day's sources only once that day is complete.
|
||||||
fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job_id: &str, cancel: &AtomicBool, room: Option<u64>) -> Result<CardResult, String> {
|
fn ingest_dir(
|
||||||
|
app: Option<&AppHandle>,
|
||||||
|
root: &Path,
|
||||||
|
settings: &CardSettings,
|
||||||
|
job_id: &str,
|
||||||
|
cancel: &AtomicBool,
|
||||||
|
room: Option<u64>,
|
||||||
|
) -> Result<CardResult, String> {
|
||||||
if !root.is_dir() {
|
if !root.is_dir() {
|
||||||
return Err("not_a_folder".to_string());
|
return Err("not_a_folder".to_string());
|
||||||
}
|
}
|
||||||
let base = expand(&settings.destination);
|
let base = expand(&settings.destination);
|
||||||
let mut files = Vec::new();
|
let mut files = Vec::new();
|
||||||
collect(root, &mut files);
|
collect(root, &mut files);
|
||||||
let photos: Vec<PathBuf> = files.into_iter().filter(|f| wanted(&ext_of(f), settings.raw_jpeg)).collect();
|
let photos: Vec<PathBuf> = files
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| wanted(&ext_of(f), settings.raw_jpeg))
|
||||||
|
.collect();
|
||||||
let (days, held) = days_that_fit(plan_days(&photos, settings), room);
|
let (days, held) = days_that_fit(plan_days(&photos, settings), room);
|
||||||
let total: usize = days.iter().map(|day| day.items.len()).sum();
|
let total: usize = days.iter().map(|day| day.items.len()).sum();
|
||||||
let bytes_total: u64 = days.iter().map(|day| day.items.iter().map(|item| item.photo_len).sum::<u64>()).sum();
|
let bytes_total: u64 = days
|
||||||
|
.iter()
|
||||||
|
.map(|day| day.items.iter().map(|item| item.photo_len).sum::<u64>())
|
||||||
|
.sum();
|
||||||
let mut bytes_done = 0u64;
|
let mut bytes_done = 0u64;
|
||||||
let mut r = CardResult {
|
let mut r = CardResult {
|
||||||
copied: 0,
|
copied: 0,
|
||||||
@@ -585,7 +647,10 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
|
|||||||
held: held.clone(),
|
held: held.clone(),
|
||||||
};
|
};
|
||||||
if let Some(day) = held.first() {
|
if let Some(day) = held.first() {
|
||||||
note(&mut r.notes, &format!("O dia {day} não cabe. Fica no cartão, tal como os dias a seguir."));
|
note(
|
||||||
|
&mut r.notes,
|
||||||
|
&format!("O dia {day} não cabe. Fica no cartão, tal como os dias a seguir."),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
let mut index = 0usize;
|
let mut index = 0usize;
|
||||||
for day in &days {
|
for day in &days {
|
||||||
@@ -603,7 +668,17 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
index += 1;
|
index += 1;
|
||||||
report(app, &Progress { done: index, total, name: item.name.clone(), job_id: job_id.to_string(), bytes_done, bytes_total });
|
report(
|
||||||
|
app,
|
||||||
|
&Progress {
|
||||||
|
done: index,
|
||||||
|
total,
|
||||||
|
name: item.name.clone(),
|
||||||
|
job_id: job_id.to_string(),
|
||||||
|
bytes_done,
|
||||||
|
bytes_total,
|
||||||
|
},
|
||||||
|
);
|
||||||
if let Err(e) = std::fs::create_dir_all(&item.dir) {
|
if let Err(e) = std::fs::create_dir_all(&item.dir) {
|
||||||
r.failed += 1;
|
r.failed += 1;
|
||||||
bytes_done += item.photo_len;
|
bytes_done += item.photo_len;
|
||||||
@@ -628,7 +703,10 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
|
|||||||
// Sidecars (same stem): best effort. A sidecar that fails is noted but does not fail the photo.
|
// Sidecars (same stem): best effort. A sidecar that fails is noted but does not fail the photo.
|
||||||
let mut sidecars_done: Vec<PathBuf> = Vec::new();
|
let mut sidecars_done: Vec<PathBuf> = Vec::new();
|
||||||
if settings.sidecars {
|
if settings.sidecars {
|
||||||
if let (Some(stem), Some(parent)) = (item.src.file_stem().and_then(|s| s.to_str()), item.src.parent()) {
|
if let (Some(stem), Some(parent)) = (
|
||||||
|
item.src.file_stem().and_then(|s| s.to_str()),
|
||||||
|
item.src.parent(),
|
||||||
|
) {
|
||||||
for ext in SIDECAR_EXTS {
|
for ext in SIDECAR_EXTS {
|
||||||
let side = parent.join(format!("{stem}.{ext}"));
|
let side = parent.join(format!("{stem}.{ext}"));
|
||||||
if !side.exists() {
|
if !side.exists() {
|
||||||
@@ -666,7 +744,14 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
|
|||||||
let finished = r.copied + r.moved + r.skipped + r.failed;
|
let finished = r.copied + r.moved + r.skipped + r.failed;
|
||||||
report(
|
report(
|
||||||
app,
|
app,
|
||||||
&Progress { done: finished, total, name: String::new(), job_id: job_id.to_string(), bytes_done, bytes_total },
|
&Progress {
|
||||||
|
done: finished,
|
||||||
|
total,
|
||||||
|
name: String::new(),
|
||||||
|
job_id: job_id.to_string(),
|
||||||
|
bytes_done,
|
||||||
|
bytes_total,
|
||||||
|
},
|
||||||
);
|
);
|
||||||
Ok(r)
|
Ok(r)
|
||||||
}
|
}
|
||||||
@@ -675,7 +760,13 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
|
|||||||
/// `card-progress` events as it goes. `job_id` lets several cards report progress without mixing, and lets
|
/// `card-progress` events as it goes. `job_id` lets several cards report progress without mixing, and lets
|
||||||
/// [`card_cancel`] stop one of them. Omitted, the job is named `default` (one card at a time).
|
/// [`card_cancel`] stop one of them. Omitted, the job is named `default` (one card at a time).
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn card_ingest(app: AppHandle, source: String, settings: CardSettings, job_id: Option<String>, state: tauri::State<'_, CardState>) -> Result<CardResult, String> {
|
pub async fn card_ingest(
|
||||||
|
app: AppHandle,
|
||||||
|
source: String,
|
||||||
|
settings: CardSettings,
|
||||||
|
job_id: Option<String>,
|
||||||
|
state: tauri::State<'_, CardState>,
|
||||||
|
) -> Result<CardResult, String> {
|
||||||
let job_id = job_id.unwrap_or_else(|| "default".to_string());
|
let job_id = job_id.unwrap_or_else(|| "default".to_string());
|
||||||
let cancel = state.begin(&job_id);
|
let cancel = state.begin(&job_id);
|
||||||
let end_id = job_id.clone();
|
let end_id = job_id.clone();
|
||||||
@@ -703,7 +794,10 @@ pub fn card_settings(state: tauri::State<'_, CardState>) -> CardSettings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn card_save_settings(state: tauri::State<'_, CardState>, settings: CardSettings) -> Result<CardSettings, String> {
|
pub fn card_save_settings(
|
||||||
|
state: tauri::State<'_, CardState>,
|
||||||
|
settings: CardSettings,
|
||||||
|
) -> Result<CardSettings, String> {
|
||||||
state.save(settings.clone())?;
|
state.save(settings.clone())?;
|
||||||
Ok(settings)
|
Ok(settings)
|
||||||
}
|
}
|
||||||
@@ -727,7 +821,8 @@ mod tests {
|
|||||||
..CardSettings::default()
|
..CardSettings::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
let stopped = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(true), None).unwrap();
|
let stopped =
|
||||||
|
ingest_dir(None, &src, &settings, "job", &AtomicBool::new(true), None).unwrap();
|
||||||
assert!(stopped.stopped);
|
assert!(stopped.stopped);
|
||||||
assert_eq!(stopped.copied, 0);
|
assert_eq!(stopped.copied, 0);
|
||||||
assert!(!dst.join("a.jpg").exists());
|
assert!(!dst.join("a.jpg").exists());
|
||||||
@@ -751,7 +846,12 @@ mod tests {
|
|||||||
std::fs::write(&old, b"day-one").unwrap();
|
std::fs::write(&old, b"day-one").unwrap();
|
||||||
std::fs::write(&new, b"day-two-is-bigger").unwrap();
|
std::fs::write(&new, b"day-two-is-bigger").unwrap();
|
||||||
let past = std::time::SystemTime::now() - std::time::Duration::from_secs(5 * 24 * 3600);
|
let past = std::time::SystemTime::now() - std::time::Duration::from_secs(5 * 24 * 3600);
|
||||||
std::fs::OpenOptions::new().write(true).open(&old).unwrap().set_modified(past).unwrap();
|
std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.open(&old)
|
||||||
|
.unwrap()
|
||||||
|
.set_modified(past)
|
||||||
|
.unwrap();
|
||||||
let settings = CardSettings {
|
let settings = CardSettings {
|
||||||
destination: dst.to_string_lossy().to_string(),
|
destination: dst.to_string_lossy().to_string(),
|
||||||
folder_template: String::new(),
|
folder_template: String::new(),
|
||||||
@@ -760,7 +860,15 @@ mod tests {
|
|||||||
..CardSettings::default()
|
..CardSettings::default()
|
||||||
};
|
};
|
||||||
let room = std::fs::metadata(&old).unwrap().len();
|
let room = std::fs::metadata(&old).unwrap().len();
|
||||||
let done = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(false), Some(room)).unwrap();
|
let done = ingest_dir(
|
||||||
|
None,
|
||||||
|
&src,
|
||||||
|
&settings,
|
||||||
|
"job",
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
Some(room),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
assert_eq!(done.moved, 1);
|
assert_eq!(done.moved, 1);
|
||||||
assert_eq!(done.held.len(), 1);
|
assert_eq!(done.held.len(), 1);
|
||||||
assert!(dst.join("old.jpg").exists());
|
assert!(dst.join("old.jpg").exists());
|
||||||
|
|||||||
@@ -7,10 +7,10 @@
|
|||||||
//! Results stay on disk (the face, and the name for this game) so opening the same folder again does not
|
//! Results stay on disk (the face, and the name for this game) so opening the same folder again does not
|
||||||
//! read the photos a second time.
|
//! read the photos a second time.
|
||||||
|
|
||||||
|
use std::io::Write;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::io::Write;
|
|
||||||
use std::time::{Duration, Instant, UNIX_EPOCH};
|
use std::time::{Duration, Instant, UNIX_EPOCH};
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -30,7 +30,9 @@ pub struct FaceScan {
|
|||||||
|
|
||||||
impl Default for FaceScan {
|
impl Default for FaceScan {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self { cancel: Arc::new(AtomicBool::new(false)) }
|
Self {
|
||||||
|
cancel: Arc::new(AtomicBool::new(false)),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,7 +102,10 @@ struct Job {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn cache_root() -> PathBuf {
|
fn cache_root() -> PathBuf {
|
||||||
dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join("pt.photoreport.desktop").join("face-scan")
|
dirs::cache_dir()
|
||||||
|
.unwrap_or_else(std::env::temp_dir)
|
||||||
|
.join("pt.photoreport.desktop")
|
||||||
|
.join("face-scan")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn models_dir() -> PathBuf {
|
fn models_dir() -> PathBuf {
|
||||||
@@ -112,9 +117,15 @@ fn file_key(root: &Path, path: &Path) -> String {
|
|||||||
let meta = std::fs::metadata(path).ok();
|
let meta = std::fs::metadata(path).ok();
|
||||||
let len = meta.as_ref().map(|m| m.len()).unwrap_or(0);
|
let len = meta.as_ref().map(|m| m.len()).unwrap_or(0);
|
||||||
let modified = meta.and_then(|m| m.modified().ok()).unwrap_or(UNIX_EPOCH);
|
let modified = meta.and_then(|m| m.modified().ok()).unwrap_or(UNIX_EPOCH);
|
||||||
let secs = modified.duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
let secs = modified
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs())
|
||||||
|
.unwrap_or(0);
|
||||||
let raw = format!("{}\0{len}\0{secs}", rel.to_string_lossy());
|
let raw = format!("{}\0{len}\0{secs}", rel.to_string_lossy());
|
||||||
Sha256::digest(raw.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()
|
Sha256::digest(raw.as_bytes())
|
||||||
|
.iter()
|
||||||
|
.map(|b| format!("{b:02x}"))
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn engine_file(key: &str) -> PathBuf {
|
fn engine_file(key: &str) -> PathBuf {
|
||||||
@@ -126,7 +137,11 @@ fn thumb_file(key: &str) -> PathBuf {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn named_file(org_id: &str, event_id: &str, key: &str) -> PathBuf {
|
fn named_file(org_id: &str, event_id: &str, key: &str) -> PathBuf {
|
||||||
cache_root().join("names").join(org_id).join(event_id).join(format!("{key}.json"))
|
cache_root()
|
||||||
|
.join("names")
|
||||||
|
.join(org_id)
|
||||||
|
.join(event_id)
|
||||||
|
.join(format!("{key}.json"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_json<T: for<'a> Deserialize<'a>>(path: &Path) -> Option<T> {
|
fn read_json<T: for<'a> Deserialize<'a>>(path: &Path) -> Option<T> {
|
||||||
@@ -148,8 +163,14 @@ fn worth_naming(faces: &[FoundFace]) -> Vec<&FoundFace> {
|
|||||||
const MIN_SIDE: f32 = 0.012;
|
const MIN_SIDE: f32 = 0.012;
|
||||||
const MIN_SHARP: f32 = 45.0;
|
const MIN_SHARP: f32 = 45.0;
|
||||||
const RELATIVE: f32 = 0.25;
|
const RELATIVE: f32 = 0.25;
|
||||||
let big: Vec<&FoundFace> = faces.iter().filter(|f| (f.x1 - f.x0).max(f.y1 - f.y0) >= MIN_SIDE).collect();
|
let big: Vec<&FoundFace> = faces
|
||||||
let sharpest = big.iter().filter_map(|f| f.sharpness).fold(0.0_f32, f32::max);
|
.iter()
|
||||||
|
.filter(|f| (f.x1 - f.x0).max(f.y1 - f.y0) >= MIN_SIDE)
|
||||||
|
.collect();
|
||||||
|
let sharpest = big
|
||||||
|
.iter()
|
||||||
|
.filter_map(|f| f.sharpness)
|
||||||
|
.fold(0.0_f32, f32::max);
|
||||||
big.into_iter()
|
big.into_iter()
|
||||||
.filter(|f| match f.sharpness {
|
.filter(|f| match f.sharpness {
|
||||||
None => true,
|
None => true,
|
||||||
@@ -161,10 +182,19 @@ fn worth_naming(faces: &[FoundFace]) -> Vec<&FoundFace> {
|
|||||||
|
|
||||||
fn to_scan(face: &FoundFace, with_embedding: bool) -> ScanFace {
|
fn to_scan(face: &FoundFace, with_embedding: bool) -> ScanFace {
|
||||||
ScanFace {
|
ScanFace {
|
||||||
rect: Rect { x0: face.x0, y0: face.y0, x1: face.x1, y1: face.y1 },
|
rect: Rect {
|
||||||
|
x0: face.x0,
|
||||||
|
y0: face.y0,
|
||||||
|
x1: face.x1,
|
||||||
|
y1: face.y1,
|
||||||
|
},
|
||||||
number: None,
|
number: None,
|
||||||
person: None,
|
person: None,
|
||||||
embedding: if with_embedding { face.embedding.clone() } else { None },
|
embedding: if with_embedding {
|
||||||
|
face.embedding.clone()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,26 +209,46 @@ fn b64(data: &[u8]) -> String {
|
|||||||
let n = (b0 << 16) | (b1.unwrap_or(0) << 8) | b2.unwrap_or(0);
|
let n = (b0 << 16) | (b1.unwrap_or(0) << 8) | b2.unwrap_or(0);
|
||||||
out.push(TABLE[((n >> 18) & 63) as usize] as char);
|
out.push(TABLE[((n >> 18) & 63) as usize] as char);
|
||||||
out.push(TABLE[((n >> 12) & 63) as usize] as char);
|
out.push(TABLE[((n >> 12) & 63) as usize] as char);
|
||||||
out.push(if b1.is_some() { TABLE[((n >> 6) & 63) as usize] as char } else { '=' });
|
out.push(if b1.is_some() {
|
||||||
out.push(if b2.is_some() { TABLE[(n & 63) as usize] as char } else { '=' });
|
TABLE[((n >> 6) & 63) as usize] as char
|
||||||
|
} else {
|
||||||
|
'='
|
||||||
|
});
|
||||||
|
out.push(if b2.is_some() {
|
||||||
|
TABLE[(n & 63) as usize] as char
|
||||||
|
} else {
|
||||||
|
'='
|
||||||
|
});
|
||||||
i += 3;
|
i += 3;
|
||||||
}
|
}
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
fn thumb_jpeg(path: &Path) -> Vec<u8> {
|
fn thumb_jpeg(path: &Path) -> Vec<u8> {
|
||||||
let Ok(reader) = image::ImageReader::open(path).and_then(|r| r.with_guessed_format()) else { return Vec::new() };
|
let Ok(reader) = image::ImageReader::open(path).and_then(|r| r.with_guessed_format()) else {
|
||||||
let Ok(img) = reader.decode() else { return Vec::new() };
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let Ok(img) = reader.decode() else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
let small = img.thumbnail(480, 480);
|
let small = img.thumbnail(480, 480);
|
||||||
let mut bytes = Vec::new();
|
let mut bytes = Vec::new();
|
||||||
if small.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Jpeg).is_err() {
|
if small
|
||||||
|
.write_to(
|
||||||
|
&mut std::io::Cursor::new(&mut bytes),
|
||||||
|
image::ImageFormat::Jpeg,
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
}
|
}
|
||||||
bytes
|
bytes
|
||||||
}
|
}
|
||||||
|
|
||||||
fn jpeg_paths(dir: &Path, out: &mut Vec<PathBuf>) {
|
fn jpeg_paths(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
for entry in entries.flatten() {
|
for entry in entries.flatten() {
|
||||||
let path = entry.path();
|
let path = entry.path();
|
||||||
let name = entry.file_name();
|
let name = entry.file_name();
|
||||||
@@ -208,7 +258,9 @@ fn jpeg_paths(dir: &Path, out: &mut Vec<PathBuf>) {
|
|||||||
}
|
}
|
||||||
if path.is_dir() {
|
if path.is_dir() {
|
||||||
jpeg_paths(&path, out);
|
jpeg_paths(&path, out);
|
||||||
} else if name.to_ascii_lowercase().ends_with(".jpg") || name.to_ascii_lowercase().ends_with(".jpeg") {
|
} else if name.to_ascii_lowercase().ends_with(".jpg")
|
||||||
|
|| name.to_ascii_lowercase().ends_with(".jpeg")
|
||||||
|
{
|
||||||
out.push(path);
|
out.push(path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -226,7 +278,9 @@ fn memory_gb() -> f64 {
|
|||||||
/// One engine per core, and only as many as memory can hold (each copy of the model is large).
|
/// One engine per core, and only as many as memory can hold (each copy of the model is large).
|
||||||
/// `extra_gb` is RAM already taken by the accelerator, so the CPU copies leave room for it.
|
/// `extra_gb` is RAM already taken by the accelerator, so the CPU copies leave room for it.
|
||||||
fn engine_cap(extra_gb: f64) -> usize {
|
fn engine_cap(extra_gb: f64) -> usize {
|
||||||
let cpus = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(2);
|
let cpus = std::thread::available_parallelism()
|
||||||
|
.map(|n| n.get())
|
||||||
|
.unwrap_or(2);
|
||||||
let spare = (memory_gb() - 2.0 - extra_gb).max(0.7);
|
let spare = (memory_gb() - 2.0 - extra_gb).max(0.7);
|
||||||
let by_mem = (spare / 0.7).floor().max(1.0) as usize;
|
let by_mem = (spare / 0.7).floor().max(1.0) as usize;
|
||||||
cpus.max(1).min(by_mem.max(1))
|
cpus.max(1).min(by_mem.max(1))
|
||||||
@@ -244,7 +298,14 @@ fn cpu_ticks() -> Option<(u64, u64)> {
|
|||||||
}
|
}
|
||||||
let mut info = Load { ticks: [0; 4] };
|
let mut info = Load { ticks: [0; 4] };
|
||||||
let mut count = 4u32;
|
let mut count = 4u32;
|
||||||
let rc = unsafe { host_statistics(mach_host_self(), 3, (&mut info as *mut Load).cast(), &mut count) };
|
let rc = unsafe {
|
||||||
|
host_statistics(
|
||||||
|
mach_host_self(),
|
||||||
|
3,
|
||||||
|
(&mut info as *mut Load).cast(),
|
||||||
|
&mut count,
|
||||||
|
)
|
||||||
|
};
|
||||||
if rc != 0 {
|
if rc != 0 {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -266,7 +327,11 @@ fn cpu_ticks() -> Option<(u64, u64)> {
|
|||||||
idle = n;
|
idle = n;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if total == 0 { None } else { Some((idle, total)) }
|
if total == 0 {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some((idle, total))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
||||||
@@ -279,7 +344,11 @@ fn cpu_used(prev: &mut Option<(u64, u64)>) -> Option<f64> {
|
|||||||
let used = prev.and_then(|(idle, total)| {
|
let used = prev.and_then(|(idle, total)| {
|
||||||
let idle_d = now.0.saturating_sub(idle);
|
let idle_d = now.0.saturating_sub(idle);
|
||||||
let total_d = now.1.saturating_sub(total);
|
let total_d = now.1.saturating_sub(total);
|
||||||
if total_d == 0 { None } else { Some(1.0 - (idle_d as f64) / (total_d as f64)) }
|
if total_d == 0 {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(1.0 - (idle_d as f64) / (total_d as f64))
|
||||||
|
}
|
||||||
});
|
});
|
||||||
*prev = Some(now);
|
*prev = Some(now);
|
||||||
used
|
used
|
||||||
@@ -297,9 +366,23 @@ fn emit_prepare(app: &AppHandle, step: &'static str, done: u64, total: u64) {
|
|||||||
let _ = app.emit("faces-prepare", Prepare { step, done, total });
|
let _ = app.emit("faces-prepare", Prepare { step, done, total });
|
||||||
}
|
}
|
||||||
|
|
||||||
fn emit_one(app: &AppHandle, done: &AtomicUsize, total: usize, path: &Path, cached: bool, needs_name: bool, error: bool, roster: Option<i32>, thumb: &[u8], faces: Vec<ScanFace>) {
|
fn emit_one(
|
||||||
|
app: &AppHandle,
|
||||||
|
done: &AtomicUsize,
|
||||||
|
total: usize,
|
||||||
|
path: &Path,
|
||||||
|
cached: bool,
|
||||||
|
needs_name: bool,
|
||||||
|
error: bool,
|
||||||
|
roster: Option<i32>,
|
||||||
|
thumb: &[u8],
|
||||||
|
faces: Vec<ScanFace>,
|
||||||
|
) {
|
||||||
let n = done.fetch_add(1, Ordering::Relaxed) + 1;
|
let n = done.fetch_add(1, Ordering::Relaxed) + 1;
|
||||||
let name = path.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
|
let name = path
|
||||||
|
.file_name()
|
||||||
|
.map(|s| s.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
let _ = app.emit(
|
let _ = app.emit(
|
||||||
"faces-photo",
|
"faces-photo",
|
||||||
Progress {
|
Progress {
|
||||||
@@ -311,13 +394,23 @@ fn emit_one(app: &AppHandle, done: &AtomicUsize, total: usize, path: &Path, cach
|
|||||||
needs_name,
|
needs_name,
|
||||||
error,
|
error,
|
||||||
roster,
|
roster,
|
||||||
thumb: if thumb.is_empty() { String::new() } else { b64(thumb) },
|
thumb: if thumb.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
b64(thumb)
|
||||||
|
},
|
||||||
faces,
|
faces,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn ensure_models(app: &AppHandle, cancel: &AtomicBool, api: &str, token: &str, org_id: &str) -> Result<PathBuf, String> {
|
async fn ensure_models(
|
||||||
|
app: &AppHandle,
|
||||||
|
cancel: &AtomicBool,
|
||||||
|
api: &str,
|
||||||
|
token: &str,
|
||||||
|
org_id: &str,
|
||||||
|
) -> Result<PathBuf, String> {
|
||||||
let dir = models_dir();
|
let dir = models_dir();
|
||||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||||
if MODEL_FILES.iter().all(|name| dir.join(name).is_file()) {
|
if MODEL_FILES.iter().all(|name| dir.join(name).is_file()) {
|
||||||
@@ -332,7 +425,10 @@ async fn ensure_models(app: &AppHandle, cancel: &AtomicBool, api: &str, token: &
|
|||||||
if dest.is_file() {
|
if dest.is_file() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let url = format!("{}/v1/orgs/{org_id}/faces/models/{name}", api.trim_end_matches('/'));
|
let url = format!(
|
||||||
|
"{}/v1/orgs/{org_id}/faces/models/{name}",
|
||||||
|
api.trim_end_matches('/')
|
||||||
|
);
|
||||||
download_model(app, cancel, &http, &url, &dest, token).await?;
|
download_model(app, cancel, &http, &url, &dest, token).await?;
|
||||||
}
|
}
|
||||||
Ok(dir)
|
Ok(dir)
|
||||||
@@ -340,8 +436,20 @@ async fn ensure_models(app: &AppHandle, cancel: &AtomicBool, api: &str, token: &
|
|||||||
|
|
||||||
/// The recogniser is about 250 MB. Report bytes so the wait is not a frozen sentence.
|
/// The recogniser is about 250 MB. Report bytes so the wait is not a frozen sentence.
|
||||||
/// The recogniser is about 250 MB. Report bytes so the wait is not a frozen sentence.
|
/// The recogniser is about 250 MB. Report bytes so the wait is not a frozen sentence.
|
||||||
async fn download_model(app: &AppHandle, cancel: &AtomicBool, http: &reqwest::Client, url: &str, dest: &Path, token: &str) -> Result<(), String> {
|
async fn download_model(
|
||||||
let mut res = http.get(url).bearer_auth(token).send().await.map_err(|e| e.to_string())?;
|
app: &AppHandle,
|
||||||
|
cancel: &AtomicBool,
|
||||||
|
http: &reqwest::Client,
|
||||||
|
url: &str,
|
||||||
|
dest: &Path,
|
||||||
|
token: &str,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let mut res = http
|
||||||
|
.get(url)
|
||||||
|
.bearer_auth(token)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
if !res.status().is_success() {
|
if !res.status().is_success() {
|
||||||
return Err(format!("models_{}", res.status().as_u16()));
|
return Err(format!("models_{}", res.status().as_u16()));
|
||||||
}
|
}
|
||||||
@@ -370,7 +478,15 @@ async fn download_model(app: &AppHandle, cancel: &AtomicBool, http: &reqwest::Cl
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_jobs(dir: PathBuf, jobs: Arc<Mutex<Vec<Job>>>, cancel: Arc<AtomicBool>, app: AppHandle, done: Arc<AtomicUsize>, total: usize, accel: Option<Arc<Accel>>) {
|
fn run_jobs(
|
||||||
|
dir: PathBuf,
|
||||||
|
jobs: Arc<Mutex<Vec<Job>>>,
|
||||||
|
cancel: Arc<AtomicBool>,
|
||||||
|
app: AppHandle,
|
||||||
|
done: Arc<AtomicUsize>,
|
||||||
|
total: usize,
|
||||||
|
accel: Option<Arc<Accel>>,
|
||||||
|
) {
|
||||||
emit_prepare(&app, "load", 0, 0);
|
emit_prepare(&app, "load", 0, 0);
|
||||||
let engine = match Engine::load(&dir, "auraface", 0.6) {
|
let engine = match Engine::load(&dir, "auraface", 0.6) {
|
||||||
Ok(engine) => engine,
|
Ok(engine) => engine,
|
||||||
@@ -386,27 +502,62 @@ fn run_jobs(dir: PathBuf, jobs: Arc<Mutex<Vec<Job>>>, cancel: Arc<AtomicBool>, a
|
|||||||
let job = jobs.lock().ok().and_then(|mut q| q.pop());
|
let job = jobs.lock().ok().and_then(|mut q| q.pop());
|
||||||
let Some(job) = job else { return };
|
let Some(job) = job else { return };
|
||||||
if let Some(cached) = read_json::<EngineCache>(&engine_file(&job.key)) {
|
if let Some(cached) = read_json::<EngineCache>(&engine_file(&job.key)) {
|
||||||
let faces = worth_naming(&cached.faces).into_iter().map(|f| to_scan(f, true)).collect();
|
let faces = worth_naming(&cached.faces)
|
||||||
|
.into_iter()
|
||||||
|
.map(|f| to_scan(f, true))
|
||||||
|
.collect();
|
||||||
let thumb = std::fs::read(thumb_file(&job.key)).unwrap_or_default();
|
let thumb = std::fs::read(thumb_file(&job.key)).unwrap_or_default();
|
||||||
emit_one(&app, &done, total, &job.path, true, true, false, None, &thumb, faces);
|
emit_one(
|
||||||
|
&app, &done, total, &job.path, true, true, false, None, &thumb, faces,
|
||||||
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
match engine.analyse_with(&job.path, &mut |rgb| accel.as_ref().and_then(|device| device.embed(rgb).ok())) {
|
match engine.analyse_with(&job.path, &mut |rgb| {
|
||||||
|
accel.as_ref().and_then(|device| device.embed(rgb).ok())
|
||||||
|
}) {
|
||||||
Ok(read) => {
|
Ok(read) => {
|
||||||
let _ = write_json(&engine_file(&job.key), &EngineCache { faces: read.faces.clone() });
|
let _ = write_json(
|
||||||
|
&engine_file(&job.key),
|
||||||
|
&EngineCache {
|
||||||
|
faces: read.faces.clone(),
|
||||||
|
},
|
||||||
|
);
|
||||||
let thumb = thumb_jpeg(&job.path);
|
let thumb = thumb_jpeg(&job.path);
|
||||||
if !thumb.is_empty() {
|
if !thumb.is_empty() {
|
||||||
let _ = std::fs::write(thumb_file(&job.key), &thumb);
|
let _ = std::fs::write(thumb_file(&job.key), &thumb);
|
||||||
}
|
}
|
||||||
let faces = worth_naming(&read.faces).into_iter().map(|f| to_scan(f, true)).collect();
|
let faces = worth_naming(&read.faces)
|
||||||
emit_one(&app, &done, total, &job.path, false, true, false, None, &thumb, faces);
|
.into_iter()
|
||||||
|
.map(|f| to_scan(f, true))
|
||||||
|
.collect();
|
||||||
|
emit_one(
|
||||||
|
&app, &done, total, &job.path, false, true, false, None, &thumb, faces,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
Err(_) => emit_one(&app, &done, total, &job.path, false, false, true, None, &[], Vec::new()),
|
Err(_) => emit_one(
|
||||||
|
&app,
|
||||||
|
&done,
|
||||||
|
total,
|
||||||
|
&job.path,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
None,
|
||||||
|
&[],
|
||||||
|
Vec::new(),
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String, models: PathBuf, cancel: Arc<AtomicBool>) -> Result<(), String> {
|
fn scan_folder(
|
||||||
|
app: AppHandle,
|
||||||
|
folder: String,
|
||||||
|
org_id: String,
|
||||||
|
event_id: String,
|
||||||
|
models: PathBuf,
|
||||||
|
cancel: Arc<AtomicBool>,
|
||||||
|
) -> Result<(), String> {
|
||||||
let root = PathBuf::from(&folder);
|
let root = PathBuf::from(&folder);
|
||||||
if !root.is_dir() {
|
if !root.is_dir() {
|
||||||
return Err("not_a_folder".into());
|
return Err("not_a_folder".into());
|
||||||
@@ -421,7 +572,18 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String,
|
|||||||
let key = file_key(&root, &path);
|
let key = file_key(&root, &path);
|
||||||
if let Some(named) = read_json::<NamedCache>(&named_file(&org_id, &event_id, &key)) {
|
if let Some(named) = read_json::<NamedCache>(&named_file(&org_id, &event_id, &key)) {
|
||||||
let thumb = std::fs::read(thumb_file(&key)).unwrap_or_default();
|
let thumb = std::fs::read(thumb_file(&key)).unwrap_or_default();
|
||||||
emit_one(&app, &done, total, &path, true, false, false, named.roster, &thumb, named.faces);
|
emit_one(
|
||||||
|
&app,
|
||||||
|
&done,
|
||||||
|
total,
|
||||||
|
&path,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
named.roster,
|
||||||
|
&thumb,
|
||||||
|
named.faces,
|
||||||
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
pending.push(Job { path, key });
|
pending.push(Job { path, key });
|
||||||
@@ -448,9 +610,23 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String,
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if alive == 0 && !handles.is_empty() && left > 0 {
|
if alive == 0 && !handles.is_empty() && left > 0 {
|
||||||
let rest = jobs.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();
|
let rest = jobs
|
||||||
|
.lock()
|
||||||
|
.map(|mut q| std::mem::take(&mut *q))
|
||||||
|
.unwrap_or_default();
|
||||||
for job in rest {
|
for job in rest {
|
||||||
emit_one(&app, &done, total, &job.path, false, false, true, None, &[], Vec::new());
|
emit_one(
|
||||||
|
&app,
|
||||||
|
&done,
|
||||||
|
total,
|
||||||
|
&job.path,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
None,
|
||||||
|
&[],
|
||||||
|
Vec::new(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -459,7 +635,11 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String,
|
|||||||
let used = cpu_used(&mut sample).unwrap_or(0.0);
|
let used = cpu_used(&mut sample).unwrap_or(0.0);
|
||||||
let busy = handles.is_empty() || used < CPU_TARGET;
|
let busy = handles.is_empty() || used < CPU_TARGET;
|
||||||
if busy {
|
if busy {
|
||||||
let batch = if handles.is_empty() { 2.min(cap) } else { 2.min(cap - handles.len()) };
|
let batch = if handles.is_empty() {
|
||||||
|
2.min(cap)
|
||||||
|
} else {
|
||||||
|
2.min(cap - handles.len())
|
||||||
|
};
|
||||||
for _ in 0..batch {
|
for _ in 0..batch {
|
||||||
let jobs = jobs.clone();
|
let jobs = jobs.clone();
|
||||||
let cancel = cancel.clone();
|
let cancel = cancel.clone();
|
||||||
@@ -467,7 +647,9 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String,
|
|||||||
let done = done.clone();
|
let done = done.clone();
|
||||||
let dir = models.clone();
|
let dir = models.clone();
|
||||||
let accel = accel.clone();
|
let accel = accel.clone();
|
||||||
handles.push(std::thread::spawn(move || run_jobs(dir, jobs, cancel, app, done, total, accel)));
|
handles.push(std::thread::spawn(move || {
|
||||||
|
run_jobs(dir, jobs, cancel, app, done, total, accel)
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -493,7 +675,15 @@ pub fn faces_cancel(state: tauri::State<'_, FaceScan>) {
|
|||||||
/// Reads every JPEG under `folder` on this computer. Emits `faces-photo` as each one finishes.
|
/// Reads every JPEG under `folder` on this computer. Emits `faces-photo` as each one finishes.
|
||||||
/// A photo already named for this game is not read again. The models are downloaded once.
|
/// A photo already named for this game is not read again. The models are downloaded once.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn faces_scan(app: AppHandle, state: tauri::State<'_, FaceScan>, folder: String, org_id: String, event_id: String, api: String, token: String) -> Result<(), String> {
|
pub async fn faces_scan(
|
||||||
|
app: AppHandle,
|
||||||
|
state: tauri::State<'_, FaceScan>,
|
||||||
|
folder: String,
|
||||||
|
org_id: String,
|
||||||
|
event_id: String,
|
||||||
|
api: String,
|
||||||
|
token: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
state.cancel.store(false, Ordering::Relaxed);
|
state.cancel.store(false, Ordering::Relaxed);
|
||||||
let cancel = state.cancel.clone();
|
let cancel = state.cancel.clone();
|
||||||
let models = match ensure_models(&app, &cancel, &api, &token, &org_id).await {
|
let models = match ensure_models(&app, &cancel, &api, &token, &org_id).await {
|
||||||
@@ -501,14 +691,23 @@ pub async fn faces_scan(app: AppHandle, state: tauri::State<'_, FaceScan>, folde
|
|||||||
other => other?,
|
other => other?,
|
||||||
};
|
};
|
||||||
let cancel2 = cancel.clone();
|
let cancel2 = cancel.clone();
|
||||||
tauri::async_runtime::spawn_blocking(move || scan_folder(app, folder, org_id, event_id, models, cancel2))
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
.await
|
scan_folder(app, folder, org_id, event_id, models, cancel2)
|
||||||
.map_err(|e| e.to_string())?
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remembers the names for one photo of this game, so the next search of the same file skips the server too.
|
/// Remembers the names for one photo of this game, so the next search of the same file skips the server too.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn faces_remember(folder: String, path: String, org_id: String, event_id: String, roster: Option<i32>, faces: Vec<ScanFace>) -> Result<(), String> {
|
pub fn faces_remember(
|
||||||
|
folder: String,
|
||||||
|
path: String,
|
||||||
|
org_id: String,
|
||||||
|
event_id: String,
|
||||||
|
roster: Option<i32>,
|
||||||
|
faces: Vec<ScanFace>,
|
||||||
|
) -> Result<(), String> {
|
||||||
let root = PathBuf::from(&folder);
|
let root = PathBuf::from(&folder);
|
||||||
let file = PathBuf::from(&path);
|
let file = PathBuf::from(&path);
|
||||||
let key = file_key(&root, &file);
|
let key = file_key(&root, &file);
|
||||||
@@ -519,14 +718,20 @@ pub fn faces_remember(folder: String, path: String, org_id: String, event_id: St
|
|||||||
face
|
face
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
write_json(&named_file(&org_id, &event_id, &key), &NamedCache { roster, faces })
|
write_json(
|
||||||
|
&named_file(&org_id, &event_id, &key),
|
||||||
|
&NamedCache { roster, faces },
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The original JPEG, for importing the photos the photographer picked. Only a JPEG, and only after a scan.
|
/// The original JPEG, for importing the photos the photographer picked. Only a JPEG, and only after a scan.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn faces_read(path: String) -> Result<tauri::ipc::Response, String> {
|
pub fn faces_read(path: String) -> Result<tauri::ipc::Response, String> {
|
||||||
let file = PathBuf::from(&path);
|
let file = PathBuf::from(&path);
|
||||||
let name = file.file_name().map(|s| s.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
let name = file
|
||||||
|
.file_name()
|
||||||
|
.map(|s| s.to_string_lossy().to_ascii_lowercase())
|
||||||
|
.unwrap_or_default();
|
||||||
if !name.ends_with(".jpg") && !name.ends_with(".jpeg") {
|
if !name.ends_with(".jpg") && !name.ends_with(".jpeg") {
|
||||||
return Err("not_a_jpeg".into());
|
return Err("not_a_jpeg".into());
|
||||||
}
|
}
|
||||||
@@ -561,7 +766,11 @@ mod tests {
|
|||||||
sharpness: Some(300.0),
|
sharpness: Some(300.0),
|
||||||
embedding: Some(vec![1.0]),
|
embedding: Some(vec![1.0]),
|
||||||
};
|
};
|
||||||
let soft = FoundFace { sharpness: Some(10.0), embedding: Some(vec![1.0]), ..sharp.clone() };
|
let soft = FoundFace {
|
||||||
|
sharpness: Some(10.0),
|
||||||
|
embedding: Some(vec![1.0]),
|
||||||
|
..sharp.clone()
|
||||||
|
};
|
||||||
let faces = [sharp.clone(), soft];
|
let faces = [sharp.clone(), soft];
|
||||||
let named = worth_naming(&faces);
|
let named = worth_naming(&faces);
|
||||||
assert_eq!(named.len(), 1);
|
assert_eq!(named.len(), 1);
|
||||||
|
|||||||
@@ -111,6 +111,14 @@ pub fn run() {
|
|||||||
.build()?;
|
.build()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
|
// The main window is the window's own webview, so a drop arrives as a window event. Noting it only on
|
||||||
|
// the webview event left the folder unrecorded, and opening it was refused.
|
||||||
|
.on_window_event(|window, event| {
|
||||||
|
use tauri::Manager;
|
||||||
|
if let tauri::WindowEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event {
|
||||||
|
window.state::<browse::OpenFolders>().note(paths);
|
||||||
|
}
|
||||||
|
})
|
||||||
.on_webview_event(|webview, event| {
|
.on_webview_event(|webview, event| {
|
||||||
use tauri::Manager;
|
use tauri::Manager;
|
||||||
if let tauri::WebviewEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event {
|
if let tauri::WebviewEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event {
|
||||||
@@ -137,6 +145,12 @@ pub fn run() {
|
|||||||
browse::folder_drop,
|
browse::folder_drop,
|
||||||
browse::folder_open,
|
browse::folder_open,
|
||||||
browse::folder_thumb,
|
browse::folder_thumb,
|
||||||
|
browse::folder_read,
|
||||||
|
browse::folder_meta,
|
||||||
|
browse::folder_merge_dng,
|
||||||
|
browse::folder_save_dng,
|
||||||
|
browse::folder_save_jpeg,
|
||||||
|
browse::folder_save_xmp,
|
||||||
ftp::ftp_preview,
|
ftp::ftp_preview,
|
||||||
ftp::ftp_info,
|
ftp::ftp_info,
|
||||||
catalog::catalog_folders,
|
catalog::catalog_folders,
|
||||||
|
|||||||
@@ -108,11 +108,19 @@ pub fn exif_date(jpeg: &[u8]) -> Option<(i32, u32, u32)> {
|
|||||||
let le = &tiff[..2] == b"II";
|
let le = &tiff[..2] == b"II";
|
||||||
let u16_at = |o: usize| -> Option<u16> {
|
let u16_at = |o: usize| -> Option<u16> {
|
||||||
let b = tiff.get(o..o + 2)?;
|
let b = tiff.get(o..o + 2)?;
|
||||||
Some(if le { u16::from_le_bytes([b[0], b[1]]) } else { u16::from_be_bytes([b[0], b[1]]) })
|
Some(if le {
|
||||||
|
u16::from_le_bytes([b[0], b[1]])
|
||||||
|
} else {
|
||||||
|
u16::from_be_bytes([b[0], b[1]])
|
||||||
|
})
|
||||||
};
|
};
|
||||||
let u32_at = |o: usize| -> Option<u32> {
|
let u32_at = |o: usize| -> Option<u32> {
|
||||||
let b = tiff.get(o..o + 4)?;
|
let b = tiff.get(o..o + 4)?;
|
||||||
Some(if le { u32::from_le_bytes([b[0], b[1], b[2], b[3]]) } else { u32::from_be_bytes([b[0], b[1], b[2], b[3]]) })
|
Some(if le {
|
||||||
|
u32::from_le_bytes([b[0], b[1], b[2], b[3]])
|
||||||
|
} else {
|
||||||
|
u32::from_be_bytes([b[0], b[1], b[2], b[3]])
|
||||||
|
})
|
||||||
};
|
};
|
||||||
let ifd0 = u32_at(4)? as usize;
|
let ifd0 = u32_at(4)? as usize;
|
||||||
let count0 = u16_at(ifd0)? as usize;
|
let count0 = u16_at(ifd0)? as usize;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "PhotoReport",
|
"productName": "PhotoReport",
|
||||||
"version": "0.3.22",
|
"version": "0.3.24",
|
||||||
"identifier": "pt.photoreport.desktop",
|
"identifier": "pt.photoreport.desktop",
|
||||||
"build": {
|
"build": {
|
||||||
"devUrl": "http://localhost:5173",
|
"devUrl": "http://localhost:5173",
|
||||||
|
|||||||
@@ -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.
|
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).
|
- Desktop = Tauri around the same React SPA (replaces the Flutter Studio).
|
||||||
- Develop engine = LightCraft crates (`lightcraft-develop`, `lightcraft-pipeline`, `lightcraft-raw`,
|
- Develop engine = LightCraft crates (`lightcraft-develop`, `lightcraft-pipeline`, `lightcraft-raw`,
|
||||||
`lightcraft-codecs`, `lightcraft-faces`), pinned, behind `engine/core`. Not `lightcraft-engine`/`catalog`:
|
`lightcraft-codecs`, `lightcraft-faces`), pinned, behind `engine/core`. Not `lightcraft-engine`/`catalog`
|
||||||
our catalog is the API.
|
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
|
- 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.
|
`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.
|
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
|
## 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,
|
(`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
|
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`).
|
(`apps/site`) · Tauri 2 (`apps/desktop`) · Rust (`engine`, `workers/render`) · Python (`workers/ml`).
|
||||||
|
|||||||
+21
-1
@@ -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/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). |
|
| `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
|
## First-time setup of a container
|
||||||
|
|
||||||
1. Clone the repo to `/srv/photoreport` (read-only deploy key from Gitea).
|
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.
|
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
|
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.
|
`photoreport-deploy-receiver.service` and include `infra/nginx/deploy-receiver.conf` in the site.
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ default = ["parallel"]
|
|||||||
parallel = ["lightcraft-codecs/parallel"]
|
parallel = ["lightcraft-codecs/parallel"]
|
||||||
# Camera JPEG inside a raw, for the desktop filmstrip. Off in the browser build.
|
# Camera JPEG inside a raw, for the desktop filmstrip. Off in the browser build.
|
||||||
embedded-preview = []
|
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]
|
[dependencies]
|
||||||
lightcraft-develop = { workspace = true }
|
lightcraft-develop = { workspace = true }
|
||||||
@@ -22,6 +25,8 @@ lightcraft-merge = { workspace = true }
|
|||||||
lightcraft-raw = { workspace = true }
|
lightcraft-raw = { workspace = true }
|
||||||
lightcraft-color = { workspace = true }
|
lightcraft-color = { workspace = true }
|
||||||
lightcraft-meta = { workspace = true }
|
lightcraft-meta = { workspace = true }
|
||||||
|
lightcraft-engine = { workspace = true, optional = true }
|
||||||
|
lightcraft-catalog = { workspace = true, optional = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
@@ -151,6 +151,12 @@ pub fn apply_command(
|
|||||||
match command {
|
match command {
|
||||||
EditCommand::DevelopSet { values } => {
|
EditCommand::DevelopSet { values } => {
|
||||||
let mut next = settings.clone();
|
let mut next = settings.clone();
|
||||||
|
// A temperature or tint write is a chosen white, not the camera's as-shot. Leaving the
|
||||||
|
// mode on As Shot makes the pipeline ignore the number.
|
||||||
|
if values.contains_key("wb.temp") || values.contains_key("wb.tint") {
|
||||||
|
next.wb.mode = lightcraft_develop::WbMode::Custom;
|
||||||
|
next.wb.scale = lightcraft_develop::WbScale::Kelvin;
|
||||||
|
}
|
||||||
for (id, raw) in values {
|
for (id, raw) in values {
|
||||||
let v = raw
|
let v = raw
|
||||||
.as_f64()
|
.as_f64()
|
||||||
@@ -245,6 +251,29 @@ mod tests {
|
|||||||
assert_eq!(get_control(&s, "light.exposure"), max);
|
assert_eq!(get_control(&s, "light.exposure"), max);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn white_balance_numbers_leave_as_shot() {
|
||||||
|
let c = cmd(
|
||||||
|
json!({"command": "develop.set", "params": {"values": {"wb.temp": 5500.0, "wb.tint": 10.0}}}),
|
||||||
|
);
|
||||||
|
let s = apply_command(&DevelopSettings::default(), &c).expect("wb");
|
||||||
|
assert_eq!(s.wb.mode, lightcraft_develop::WbMode::Custom);
|
||||||
|
assert_eq!(s.wb.temp, 5500.0);
|
||||||
|
assert_eq!(s.wb.tint, 10.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn daylight_merge_keeps_the_preset() {
|
||||||
|
let c = cmd(json!({"command": "develop.merge", "params": {"partial": {
|
||||||
|
"wb": {"mode": "daylight", "temp": 5500.0, "tint": 10.0, "scale": "kelvin"},
|
||||||
|
"light": {"shadows": 100.0, "highlights": -100.0}
|
||||||
|
}}}));
|
||||||
|
let s = apply_command(&DevelopSettings::default(), &c).expect("merge");
|
||||||
|
assert_eq!(s.wb.mode, lightcraft_develop::WbMode::Daylight);
|
||||||
|
assert_eq!(s.light.shadows, 100.0);
|
||||||
|
assert_eq!(s.light.highlights, -100.0);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_unknown_controls() {
|
fn rejects_unknown_controls() {
|
||||||
let c = cmd(json!({"command": "develop.set", "params": {"values": {"light.nope": 1.0}}}));
|
let c = cmd(json!({"command": "develop.set", "params": {"values": {"light.nope": 1.0}}}));
|
||||||
|
|||||||
+312
-8
@@ -7,13 +7,12 @@
|
|||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use lightcraft_color::Xy;
|
use lightcraft_color::{Mat3, Xy};
|
||||||
use lightcraft_develop::DevelopSettings;
|
use lightcraft_develop::DevelopSettings;
|
||||||
use lightcraft_merge::frame::Frame;
|
use lightcraft_merge::frame::Frame;
|
||||||
use lightcraft_merge::{
|
use lightcraft_merge::{Deghost, FrameColor, HdrOptions, HdrResult, merge_hdr, no_progress};
|
||||||
Deghost, DngSamples, FrameColor, HdrOptions, HdrResult, merge_hdr, no_progress,
|
#[cfg(not(feature = "photo-merge"))]
|
||||||
write_linear_dng,
|
use lightcraft_merge::{DngSamples, write_linear_dng};
|
||||||
};
|
|
||||||
use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, auto};
|
use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, auto};
|
||||||
use lightcraft_raster::Rgb32f;
|
use lightcraft_raster::Rgb32f;
|
||||||
use lightcraft_raster::resample::{Filter, fit};
|
use lightcraft_raster::resample::{Filter, fit};
|
||||||
@@ -233,7 +232,66 @@ pub fn merge_linear_dng(files: &[&[u8]], max_edge: u32) -> Result<Vec<u8>, Engin
|
|||||||
"a bracket needs at least two exposures".into(),
|
"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 mut dng = out.dng;
|
||||||
|
// The fitted ForwardMatrix is the look. Camera Raw only opens it when camera white lands on D50.
|
||||||
|
pin_forward_matrices_to_d50(&mut dng);
|
||||||
|
let raw = lightcraft_raw::decode(&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(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());
|
let mut frames = Vec::with_capacity(files.len());
|
||||||
for file in files {
|
for file in files {
|
||||||
frames.push(load_bracket_frame(file, edge)?);
|
frames.push(load_bracket_frame(file, edge)?);
|
||||||
@@ -247,7 +305,7 @@ pub fn merge_linear_dng(files: &[&[u8]], max_edge: u32) -> Result<Vec<u8>, Engin
|
|||||||
&no_progress,
|
&no_progress,
|
||||||
)
|
)
|
||||||
.map_err(|e| EngineError::Decode(e.to_string()))?;
|
.map_err(|e| EngineError::Decode(e.to_string()))?;
|
||||||
write_linear_dng(
|
let mut dng = write_linear_dng(
|
||||||
&merged.radiance,
|
&merged.radiance,
|
||||||
&merged.color,
|
&merged.color,
|
||||||
merged.orientation,
|
merged.orientation,
|
||||||
@@ -256,7 +314,145 @@ pub fn merge_linear_dng(files: &[&[u8]], max_edge: u32) -> Result<Vec<u8>, Engin
|
|||||||
DngSamples::Half,
|
DngSamples::Half,
|
||||||
&merged.lens,
|
&merged.lens,
|
||||||
)
|
)
|
||||||
.map_err(|e| EngineError::Decode(e.to_string()))
|
.map_err(|e| EngineError::Decode(e.to_string()))?;
|
||||||
|
pin_forward_matrices_to_d50(&mut dng);
|
||||||
|
Ok(dng)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ForwardMatrix1` and `ForwardMatrix2` (DNG). A fitted matrix is stored as nine signed rationals.
|
||||||
|
const FORWARD_MATRIX_1: u16 = 50964;
|
||||||
|
const FORWARD_MATRIX_2: u16 = 50965;
|
||||||
|
const TIFF_SRATIONAL: u16 = 10;
|
||||||
|
/// Chromaticity, not the matrix coefficients: closer than this, the white already is D50.
|
||||||
|
const D50_XY_EPSILON: f64 = 1e-4;
|
||||||
|
const RATIONAL_DENOMINATOR: i32 = 1_000_000;
|
||||||
|
|
||||||
|
/// Camera Raw refuses a linear DNG when `ForwardMatrix * (1, 1, 1)` is more than a few thousandths
|
||||||
|
/// of chromaticity away from XYZ D50 — the import stops at "cannot get initial image info" and the
|
||||||
|
/// file never enters the catalog. The spec requires that product to be D50. Bradford-adapt the
|
||||||
|
/// fitted white onto D50 so the relative colour stays and the white point is the one the spec names.
|
||||||
|
fn pin_forward_matrices_to_d50(dng: &mut [u8]) {
|
||||||
|
if dng.len() < 8 || dng[0] != b'I' || dng[1] != b'I' || dng[2] != b'*' || dng[3] != 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(ifd) = read_u32(dng, 4) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let ifd = ifd as usize;
|
||||||
|
let Some(count) = read_u16(dng, ifd) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let count = count as usize;
|
||||||
|
for index in 0..count {
|
||||||
|
let entry = ifd + 2 + index * 12;
|
||||||
|
let Some(tag) = read_u16(dng, entry) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if tag != FORWARD_MATRIX_1 && tag != FORWARD_MATRIX_2 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(kind) = read_u16(dng, entry + 2) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(values) = read_u32(dng, entry + 4) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(offset) = read_u32(dng, entry + 8) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if kind != TIFF_SRATIONAL || values != 9 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let offset = offset as usize;
|
||||||
|
let Some(matrix) = read_matrix(dng, offset) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(pinned) = adapted_forward(matrix) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
write_matrix(dng, offset, pinned);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `None` when `matrix` already maps camera white to D50, or when the white cannot be adapted.
|
||||||
|
fn adapted_forward(matrix: Mat3) -> Option<Mat3> {
|
||||||
|
let white = matrix.apply([1.0, 1.0, 1.0]);
|
||||||
|
if white
|
||||||
|
.iter()
|
||||||
|
.any(|channel| !channel.is_finite() || *channel <= 1e-8)
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let white_xy = Xy::from_xyz(white);
|
||||||
|
let dx = white_xy.x - lightcraft_color::D50.x;
|
||||||
|
let dy = white_xy.y - lightcraft_color::D50.y;
|
||||||
|
if (dx * dx + dy * dy).sqrt() < D50_XY_EPSILON {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let source_cones = lightcraft_color::BRADFORD.apply(white);
|
||||||
|
let d50_cones = lightcraft_color::BRADFORD.apply(lightcraft_color::D50.to_xyz());
|
||||||
|
if source_cones
|
||||||
|
.iter()
|
||||||
|
.any(|cone| !cone.is_finite() || cone.abs() < 1e-8)
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let scale = Mat3::diag(
|
||||||
|
d50_cones[0] / source_cones[0],
|
||||||
|
d50_cones[1] / source_cones[1],
|
||||||
|
d50_cones[2] / source_cones[2],
|
||||||
|
);
|
||||||
|
let inverse = lightcraft_color::BRADFORD.inverse()?;
|
||||||
|
Some(
|
||||||
|
inverse
|
||||||
|
.mul(&scale)
|
||||||
|
.mul(&lightcraft_color::BRADFORD)
|
||||||
|
.mul(&matrix),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_matrix(dng: &[u8], offset: usize) -> Option<Mat3> {
|
||||||
|
let mut rows = [[0.0; 3]; 3];
|
||||||
|
for index in 0..9 {
|
||||||
|
let at = offset + index * 8;
|
||||||
|
let numerator = read_i32(dng, at)?;
|
||||||
|
let denominator = read_i32(dng, at + 4)?;
|
||||||
|
if denominator == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
rows[index / 3][index % 3] = f64::from(numerator) / f64::from(denominator);
|
||||||
|
}
|
||||||
|
Some(Mat3(rows))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_matrix(dng: &mut [u8], offset: usize, matrix: Mat3) {
|
||||||
|
for index in 0..9 {
|
||||||
|
let value = matrix.0[index / 3][index % 3];
|
||||||
|
let numerator = (value * f64::from(RATIONAL_DENOMINATOR))
|
||||||
|
.round()
|
||||||
|
.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32;
|
||||||
|
let at = offset + index * 8;
|
||||||
|
if at + 8 > dng.len() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dng[at..at + 4].copy_from_slice(&numerator.to_le_bytes());
|
||||||
|
dng[at + 4..at + 8].copy_from_slice(&RATIONAL_DENOMINATOR.to_le_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_u16(bytes: &[u8], offset: usize) -> Option<u16> {
|
||||||
|
let end = offset.checked_add(2)?;
|
||||||
|
Some(u16::from_le_bytes(bytes.get(offset..end)?.try_into().ok()?))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_u32(bytes: &[u8], offset: usize) -> Option<u32> {
|
||||||
|
let end = offset.checked_add(4)?;
|
||||||
|
Some(u32::from_le_bytes(bytes.get(offset..end)?.try_into().ok()?))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_i32(bytes: &[u8], offset: usize) -> Option<i32> {
|
||||||
|
let end = offset.checked_add(4)?;
|
||||||
|
Some(i32::from_le_bytes(bytes.get(offset..end)?.try_into().ok()?))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_mat(m: &[[f32; 3]; 3], p: [f32; 3]) -> [f32; 3] {
|
fn apply_mat(m: &[[f32; 3]; 3], p: [f32; 3]) -> [f32; 3] {
|
||||||
@@ -360,6 +556,12 @@ mod tests {
|
|||||||
let files = [dark.as_slice(), mid.as_slice(), bright.as_slice()];
|
let files = [dark.as_slice(), mid.as_slice(), bright.as_slice()];
|
||||||
let dng = merge_linear_dng(&files, 256).expect("dng");
|
let dng = merge_linear_dng(&files, 256).expect("dng");
|
||||||
assert!(dng.len() > 64);
|
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"
|
||||||
|
);
|
||||||
|
assert_forward_white_is_d50(&raw.color);
|
||||||
let source = crate::render::Source::decode(&dng, 256).expect("decode");
|
let source = crate::render::Source::decode(&dng, 256).expect("decode");
|
||||||
let (w, h) = source.size();
|
let (w, h) = source.size();
|
||||||
assert!(w >= 64 && h >= 64, "{w}x{h}");
|
assert!(w >= 64 && h >= 64, "{w}x{h}");
|
||||||
@@ -370,6 +572,108 @@ 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"
|
||||||
|
);
|
||||||
|
assert_forward_white_is_d50(&raw.color);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The matrix Camera Raw rejected: `ForwardMatrix * (1, 1, 1)` lands far from D50.
|
||||||
|
fn off_d50_matrix() -> [[f64; 3]; 3] {
|
||||||
|
[
|
||||||
|
[0.30088, 0.49883, 0.07118],
|
||||||
|
[0.13496, 0.71615, 0.04585],
|
||||||
|
[0.08228, 0.32064, 0.63143],
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tiff_with_forward(matrix: [[f64; 3]; 3]) -> Vec<u8> {
|
||||||
|
let mut rats = Vec::with_capacity(72);
|
||||||
|
for row in matrix {
|
||||||
|
for value in row {
|
||||||
|
let numerator = (value * 1_000_000.0).round() as i32;
|
||||||
|
rats.extend_from_slice(&numerator.to_le_bytes());
|
||||||
|
rats.extend_from_slice(&1_000_000i32.to_le_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let rats_at = 8u32;
|
||||||
|
let ifd_at = (8 + rats.len()) as u32;
|
||||||
|
let mut bytes = vec![b'I', b'I', b'*', 0];
|
||||||
|
bytes.extend_from_slice(&ifd_at.to_le_bytes());
|
||||||
|
bytes.extend_from_slice(&rats);
|
||||||
|
bytes.extend_from_slice(&1u16.to_le_bytes());
|
||||||
|
bytes.extend_from_slice(&50964u16.to_le_bytes());
|
||||||
|
bytes.extend_from_slice(&10u16.to_le_bytes());
|
||||||
|
bytes.extend_from_slice(&9u32.to_le_bytes());
|
||||||
|
bytes.extend_from_slice(&rats_at.to_le_bytes());
|
||||||
|
bytes.extend_from_slice(&0u32.to_le_bytes());
|
||||||
|
bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_forward_white_is_d50(color: &ColorData) {
|
||||||
|
let Some(matrix) = color.forward_matrix[0] else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let white = matrix.apply([1.0, 1.0, 1.0]);
|
||||||
|
let xy = Xy::from_xyz(white);
|
||||||
|
assert!(
|
||||||
|
(xy.x - lightcraft_color::D50.x).abs() < 1e-3
|
||||||
|
&& (xy.y - lightcraft_color::D50.y).abs() < 1e-3,
|
||||||
|
"forward white {xy:?} is not D50"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_forward_matrix_off_d50_is_pinned_and_one_on_d50_is_left_alone() {
|
||||||
|
let mut off = tiff_with_forward(off_d50_matrix());
|
||||||
|
let before = off.clone();
|
||||||
|
pin_forward_matrices_to_d50(&mut off);
|
||||||
|
assert_ne!(off, before);
|
||||||
|
let pinned = read_matrix(&off, 8).expect("matrix");
|
||||||
|
let white = pinned.apply([1.0, 1.0, 1.0]);
|
||||||
|
let xy = Xy::from_xyz(white);
|
||||||
|
assert!(
|
||||||
|
(xy.x - lightcraft_color::D50.x).abs() < 1e-4
|
||||||
|
&& (xy.y - lightcraft_color::D50.y).abs() < 1e-4,
|
||||||
|
"{xy:?} {white:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
let d50 = lightcraft_color::D50.to_xyz();
|
||||||
|
let already =
|
||||||
|
tiff_with_forward([[d50[0], 0.0, 0.0], [0.0, d50[1], 0.0], [0.0, 0.0, d50[2]]]);
|
||||||
|
let mut untouched = already.clone();
|
||||||
|
pin_forward_matrices_to_d50(&mut untouched);
|
||||||
|
assert_eq!(untouched, already);
|
||||||
|
pin_forward_matrices_to_d50(&mut []);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn one_photo_is_not_a_bracket() {
|
fn one_photo_is_not_a_bracket() {
|
||||||
let mid = exposure_dng(0.0);
|
let mid = exposure_dng(0.0);
|
||||||
|
|||||||
+5
-3
@@ -1,8 +1,10 @@
|
|||||||
{
|
{
|
||||||
"name": "photoreport",
|
"name": "photoreport",
|
||||||
"private": true,
|
"private": true,
|
||||||
"packageManager": "[email protected]",
|
"packageManager": "[email protected]+sha512.f0dda8580f0ee9481c5c79a1d927b9164f2c478e90992ad268bbb2465a736984391d6333d2c327913578b2804af33474ca554ba29c04a8b13060a717675ae3ac",
|
||||||
"engines": { "node": ">=22" },
|
"engines": {
|
||||||
|
"node": ">=24.22.1"
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "pnpm -r build",
|
"build": "pnpm -r build",
|
||||||
"typecheck": "pnpm -r typecheck",
|
"typecheck": "pnpm -r typecheck",
|
||||||
@@ -13,6 +15,6 @@
|
|||||||
"typescript": "^5.9.2",
|
"typescript": "^5.9.2",
|
||||||
"vitest": "4.1.11",
|
"vitest": "4.1.11",
|
||||||
"tsx": "^4.20.3",
|
"tsx": "^4.20.3",
|
||||||
"@types/node": "^22.15.0"
|
"@types/node": "^24.9.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Generated
+47
-47
@@ -15,8 +15,8 @@ importers:
|
|||||||
.:
|
.:
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@types/node':
|
'@types/node':
|
||||||
specifier: ^22.15.0
|
specifier: ^24.9.1
|
||||||
version: 22.20.5
|
version: 24.19.2
|
||||||
tsx:
|
tsx:
|
||||||
specifier: ^4.20.3
|
specifier: ^4.20.3
|
||||||
version: 4.23.15
|
version: 4.23.15
|
||||||
@@ -25,7 +25,7 @@ importers:
|
|||||||
version: 5.9.3
|
version: 5.9.3
|
||||||
vitest:
|
vitest:
|
||||||
specifier: 4.1.11
|
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:
|
apps/api:
|
||||||
dependencies:
|
dependencies:
|
||||||
@@ -55,7 +55,7 @@ importers:
|
|||||||
version: 7.10.0
|
version: 7.10.0
|
||||||
'@prisma/client':
|
'@prisma/client':
|
||||||
specifier: ^7.10.0
|
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:
|
basic-ftp:
|
||||||
specifier: 6.2.1
|
specifier: 6.2.1
|
||||||
version: 6.2.1
|
version: 6.2.1
|
||||||
@@ -79,7 +79,7 @@ importers:
|
|||||||
version: 6.2.12
|
version: 6.2.12
|
||||||
mysql2:
|
mysql2:
|
||||||
specifier: 3.24.4
|
specifier: 3.24.4
|
||||||
version: 3.24.4(@types/node@22.20.5)
|
version: 3.24.4(@types/node@24.19.2)
|
||||||
nodemailer:
|
nodemailer:
|
||||||
specifier: 10.0.13
|
specifier: 10.0.13
|
||||||
version: 10.0.13
|
version: 10.0.13
|
||||||
@@ -94,7 +94,7 @@ importers:
|
|||||||
version: 10.4.0
|
version: 10.4.0
|
||||||
sharp:
|
sharp:
|
||||||
specifier: ^0.35.5
|
specifier: ^0.35.5
|
||||||
version: 0.35.5(@types/node@22.20.5)
|
version: 0.35.5(@types/node@24.19.2)
|
||||||
socket.io:
|
socket.io:
|
||||||
specifier: ^4.8.4
|
specifier: ^4.8.4
|
||||||
version: 4.8.4
|
version: 4.8.4
|
||||||
@@ -122,7 +122,7 @@ importers:
|
|||||||
version: 4.6.3
|
version: 4.6.3
|
||||||
prisma:
|
prisma:
|
||||||
specifier: ^7.10.0
|
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:
|
socket.io-client:
|
||||||
specifier: ^4.8.4
|
specifier: ^4.8.4
|
||||||
version: 4.8.4
|
version: 4.8.4
|
||||||
@@ -177,7 +177,7 @@ importers:
|
|||||||
devDependencies:
|
devDependencies:
|
||||||
'@tailwindcss/vite':
|
'@tailwindcss/vite':
|
||||||
specifier: ^4.3.3
|
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':
|
'@testing-library/react':
|
||||||
specifier: ^16.3.3
|
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])
|
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])
|
version: 19.3.0(@types/[email protected])
|
||||||
'@vitejs/plugin-react':
|
'@vitejs/plugin-react':
|
||||||
specifier: ^5.2.0
|
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:
|
jsdom:
|
||||||
specifier: ^30.1.2
|
specifier: ^30.1.2
|
||||||
version: 30.1.2
|
version: 30.1.2
|
||||||
@@ -204,7 +204,7 @@ importers:
|
|||||||
version: 4.3.3
|
version: 4.3.3
|
||||||
vite:
|
vite:
|
||||||
specifier: ^7.3.7
|
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:
|
apps/desktop:
|
||||||
devDependencies:
|
devDependencies:
|
||||||
@@ -243,7 +243,7 @@ importers:
|
|||||||
version: link:../../packages/contracts
|
version: link:../../packages/contracts
|
||||||
next:
|
next:
|
||||||
specifier: 15.5.27
|
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:
|
react:
|
||||||
specifier: ^19.3.0
|
specifier: ^19.3.0
|
||||||
version: 19.3.0
|
version: 19.3.0
|
||||||
@@ -1527,8 +1527,8 @@ packages:
|
|||||||
'@types/[email protected]':
|
'@types/[email protected]':
|
||||||
resolution: {integrity: sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==}
|
resolution: {integrity: sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==}
|
||||||
|
|
||||||
'@types/node@22.20.5':
|
'@types/node@24.19.2':
|
||||||
resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==}
|
resolution: {integrity: sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==}
|
||||||
|
|
||||||
'@types/[email protected]':
|
'@types/[email protected]':
|
||||||
resolution: {integrity: sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==}
|
resolution: {integrity: sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==}
|
||||||
@@ -2974,8 +2974,8 @@ packages:
|
|||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==}
|
resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==}
|
||||||
|
|
||||||
undici-types@6.21.0:
|
undici-types@7.24.6:
|
||||||
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
|
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==}
|
resolution: {integrity: sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==}
|
||||||
@@ -3727,11 +3727,11 @@ snapshots:
|
|||||||
|
|
||||||
'@prisma/[email protected]': {}
|
'@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:
|
dependencies:
|
||||||
'@prisma/client-runtime-utils': 7.10.0
|
'@prisma/client-runtime-utils': 7.10.0
|
||||||
optionalDependencies:
|
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
|
typescript: 5.9.3
|
||||||
|
|
||||||
'@prisma/[email protected]':
|
'@prisma/[email protected]':
|
||||||
@@ -4044,12 +4044,12 @@ snapshots:
|
|||||||
'@tailwindcss/oxide-win32-arm64-msvc': 4.3.3
|
'@tailwindcss/oxide-win32-arm64-msvc': 4.3.3
|
||||||
'@tailwindcss/oxide-win32-x64-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:
|
dependencies:
|
||||||
'@tailwindcss/node': 4.3.3
|
'@tailwindcss/node': 4.3.3
|
||||||
'@tailwindcss/oxide': 4.3.3
|
'@tailwindcss/oxide': 4.3.3
|
||||||
tailwindcss: 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]': {}
|
'@tauri-apps/[email protected]': {}
|
||||||
|
|
||||||
@@ -4159,7 +4159,7 @@ snapshots:
|
|||||||
|
|
||||||
'@types/[email protected]':
|
'@types/[email protected]':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/node': 22.20.5
|
'@types/node': 24.19.2
|
||||||
|
|
||||||
'@types/[email protected]': {}
|
'@types/[email protected]': {}
|
||||||
|
|
||||||
@@ -4205,23 +4205,23 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
undici-types: 5.26.5
|
undici-types: 5.26.5
|
||||||
|
|
||||||
'@types/node@22.20.5':
|
'@types/node@24.19.2':
|
||||||
dependencies:
|
dependencies:
|
||||||
undici-types: 6.21.0
|
undici-types: 7.24.6
|
||||||
|
|
||||||
'@types/[email protected]':
|
'@types/[email protected]':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/node': 22.20.5
|
'@types/node': 24.19.2
|
||||||
|
|
||||||
'@types/[email protected]':
|
'@types/[email protected]':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/node': 22.20.5
|
'@types/node': 24.19.2
|
||||||
pg-protocol: 1.16.1
|
pg-protocol: 1.16.1
|
||||||
pg-types: 2.2.0
|
pg-types: 2.2.0
|
||||||
|
|
||||||
'@types/[email protected]':
|
'@types/[email protected]':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/node': 22.20.5
|
'@types/node': 24.19.2
|
||||||
|
|
||||||
'@types/[email protected](@types/[email protected])':
|
'@types/[email protected](@types/[email protected])':
|
||||||
dependencies:
|
dependencies:
|
||||||
@@ -4241,7 +4241,7 @@ snapshots:
|
|||||||
|
|
||||||
'@types/[email protected]':
|
'@types/[email protected]':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/node': 22.20.5
|
'@types/node': 24.19.2
|
||||||
|
|
||||||
'@visx/[email protected]':
|
'@visx/[email protected]':
|
||||||
dependencies:
|
dependencies:
|
||||||
@@ -4320,7 +4320,7 @@ snapshots:
|
|||||||
d3-time-format: 4.1.0
|
d3-time-format: 4.1.0
|
||||||
internmap: 2.0.3
|
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:
|
dependencies:
|
||||||
'@babel/core': 7.29.7
|
'@babel/core': 7.29.7
|
||||||
'@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/[email protected])
|
'@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/[email protected])
|
||||||
@@ -4328,7 +4328,7 @@ snapshots:
|
|||||||
'@rolldown/pluginutils': 1.0.0-rc.3
|
'@rolldown/pluginutils': 1.0.0-rc.3
|
||||||
'@types/babel__core': 7.20.5
|
'@types/babel__core': 7.20.5
|
||||||
react-refresh: 0.18.0
|
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:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
@@ -4341,13 +4341,13 @@ snapshots:
|
|||||||
chai: 6.3.0
|
chai: 6.3.0
|
||||||
tinyrainbow: 3.2.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:
|
dependencies:
|
||||||
'@vitest/spy': 4.1.11
|
'@vitest/spy': 4.1.11
|
||||||
estree-walker: 3.0.3
|
estree-walker: 3.0.3
|
||||||
magic-string: 0.30.21
|
magic-string: 0.30.21
|
||||||
optionalDependencies:
|
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]':
|
'@vitest/[email protected]':
|
||||||
dependencies:
|
dependencies:
|
||||||
@@ -4742,7 +4742,7 @@ snapshots:
|
|||||||
[email protected]:
|
[email protected]:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/cors': 2.8.19
|
'@types/cors': 2.8.19
|
||||||
'@types/node': 22.20.5
|
'@types/node': 24.19.2
|
||||||
'@types/ws': 8.18.2
|
'@types/ws': 8.18.2
|
||||||
accepts: 1.3.8
|
accepts: 1.3.8
|
||||||
cookie: 0.7.2
|
cookie: 0.7.2
|
||||||
@@ -5177,9 +5177,9 @@ snapshots:
|
|||||||
rimraf: 2.4.5
|
rimraf: 2.4.5
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
[email protected](@types/node@22.20.5):
|
[email protected](@types/node@24.19.2):
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/node': 22.20.5
|
'@types/node': 24.19.2
|
||||||
aws-ssl-profiles: 1.1.2
|
aws-ssl-profiles: 1.1.2
|
||||||
generate-function: 2.3.1
|
generate-function: 2.3.1
|
||||||
iconv-lite: 0.7.3
|
iconv-lite: 0.7.3
|
||||||
@@ -5202,7 +5202,7 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[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:
|
dependencies:
|
||||||
'@next/env': 15.5.27
|
'@next/env': 15.5.27
|
||||||
'@swc/helpers': 0.5.15
|
'@swc/helpers': 0.5.15
|
||||||
@@ -5220,7 +5220,7 @@ snapshots:
|
|||||||
'@next/swc-linux-x64-musl': 15.5.27
|
'@next/swc-linux-x64-musl': 15.5.27
|
||||||
'@next/swc-win32-arm64-msvc': 15.5.27
|
'@next/swc-win32-arm64-msvc': 15.5.27
|
||||||
'@next/swc-win32-x64-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:
|
transitivePeerDependencies:
|
||||||
- '@babel/core'
|
- '@babel/core'
|
||||||
- '@types/node'
|
- '@types/node'
|
||||||
@@ -5399,13 +5399,13 @@ snapshots:
|
|||||||
ansi-styles: 5.2.0
|
ansi-styles: 5.2.0
|
||||||
react-is: 17.0.2
|
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:
|
dependencies:
|
||||||
'@prisma/config': 7.10.0
|
'@prisma/config': 7.10.0
|
||||||
'@prisma/dev': 0.24.17([email protected])
|
'@prisma/dev': 0.24.17([email protected])
|
||||||
'@prisma/engines': 7.10.0
|
'@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])
|
'@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
|
postgres: 3.4.7
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
typescript: 5.9.3
|
typescript: 5.9.3
|
||||||
@@ -5436,7 +5436,7 @@ snapshots:
|
|||||||
'@protobufjs/path': 1.1.2
|
'@protobufjs/path': 1.1.2
|
||||||
'@protobufjs/pool': 1.1.0
|
'@protobufjs/pool': 1.1.0
|
||||||
'@protobufjs/utf8': 1.1.2
|
'@protobufjs/utf8': 1.1.2
|
||||||
'@types/node': 22.20.5
|
'@types/node': 24.19.2
|
||||||
long: 5.3.2
|
long: 5.3.2
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
@@ -5575,7 +5575,7 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected](@types/node@22.20.5):
|
[email protected](@types/node@24.19.2):
|
||||||
dependencies:
|
dependencies:
|
||||||
'@img/colour': 1.1.0
|
'@img/colour': 1.1.0
|
||||||
detect-libc: 2.1.2
|
detect-libc: 2.1.2
|
||||||
@@ -5606,7 +5606,7 @@ snapshots:
|
|||||||
'@img/sharp-win32-arm64': 0.35.5
|
'@img/sharp-win32-arm64': 0.35.5
|
||||||
'@img/sharp-win32-ia32': 0.35.5
|
'@img/sharp-win32-ia32': 0.35.5
|
||||||
'@img/sharp-win32-x64': 0.35.5
|
'@img/sharp-win32-x64': 0.35.5
|
||||||
'@types/node': 22.20.5
|
'@types/node': 24.19.2
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
dependencies:
|
dependencies:
|
||||||
@@ -5761,7 +5761,7 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
undici-types@6.21.0: {}
|
undici-types@7.24.6: {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
@@ -5783,7 +5783,7 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[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:
|
dependencies:
|
||||||
esbuild: 0.28.2
|
esbuild: 0.28.2
|
||||||
fdir: 6.5.0([email protected])
|
fdir: 6.5.0([email protected])
|
||||||
@@ -5792,16 +5792,16 @@ snapshots:
|
|||||||
rollup: 4.64.5
|
rollup: 4.64.5
|
||||||
tinyglobby: 0.2.17
|
tinyglobby: 0.2.17
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/node': 22.20.5
|
'@types/node': 24.19.2
|
||||||
fsevents: 2.3.3
|
fsevents: 2.3.3
|
||||||
jiti: 2.7.0
|
jiti: 2.7.0
|
||||||
lightningcss: 1.32.0
|
lightningcss: 1.32.0
|
||||||
tsx: 4.23.15
|
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:
|
dependencies:
|
||||||
'@vitest/expect': 4.1.11
|
'@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/pretty-format': 4.1.11
|
||||||
'@vitest/runner': 4.1.11
|
'@vitest/runner': 4.1.11
|
||||||
'@vitest/snapshot': 4.1.11
|
'@vitest/snapshot': 4.1.11
|
||||||
@@ -5818,10 +5818,10 @@ snapshots:
|
|||||||
tinyexec: 1.3.1
|
tinyexec: 1.3.1
|
||||||
tinyglobby: 0.2.17
|
tinyglobby: 0.2.17
|
||||||
tinyrainbow: 3.2.0
|
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
|
why-is-node-running: 2.3.0
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/node': 22.20.5
|
'@types/node': 24.19.2
|
||||||
jsdom: 30.1.2
|
jsdom: 30.1.2
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- msw
|
- msw
|
||||||
|
|||||||
Reference in new issue
Block a user