Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91bc9aefc7 | ||
|
|
6ba556ba9f |
No files matched your search
@@ -32,6 +32,17 @@ Read `docs/ARCHITECTURE.md` before any task. One task id per branch/PR (`task/BI
|
||||
13. **Prefer Rust for local heavy work.** Detection, measure, level, develop and anything CPU-bound on the
|
||||
desktop should live in `engine/` (native / WASM), not in ad-hoc TypeScript, when practical. TypeScript
|
||||
orchestrates; Rust does the pixels and the scores. Safer, faster, one implementation with the workers.
|
||||
14. **Start from the latest `origin/main`.** Paperclip, Claude Code and Cursor fetch and fast-forward this
|
||||
checkout before editing. Do not leave the work only on an old branch or another folder. A pinned engine
|
||||
revision is the LightCraft `rev` in the root `Cargo.toml`, not a stale checkout of this repo.
|
||||
15. **The photograph's aspect is not a dial.** The autopilot and every automatic file write keep the original
|
||||
aspect (`docs/photo-editing-rules.md`). A straightened crop is written as the corners Lightroom turns back
|
||||
around the crop centre (`apps/app/src/desktop/lightroomCrop.ts`). Writing the levelled rectangle plus the
|
||||
angle makes Lightroom show Custom. Do not invent another ratio to satisfy a framing rule.
|
||||
16. **Lightroom round-trip is the file, not the catalog.** While the desktop app is open it reads crop, pick,
|
||||
stars and colour back from the work-folder original and sends them to the server. Exposure and the other
|
||||
develop sliders are written out and are not read back. A change that Lightroom has not written into the
|
||||
file is invisible. Newsroom fields (caption, title, keywords, creator) go on the first `rdf:Description`.
|
||||
|
||||
## Porting from the old projects
|
||||
|
||||
|
||||
@@ -5,7 +5,11 @@ import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { App } from "./App.js";
|
||||
|
||||
vi.mock("./library/realtime.js", () => ({ useLibraryLive: () => "live", onSocketLive: () => () => {} }));
|
||||
vi.mock("./library/realtime.js", () => ({
|
||||
useLibraryLive: () => "live",
|
||||
onSocketLive: () => () => {},
|
||||
isSocketLive: () => false,
|
||||
}));
|
||||
|
||||
const ME: Me = {
|
||||
user: { id: "u1", email: "[email protected]", name: "Ana", locale: "pt-PT" },
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { ApiClient, EventSummary } from "@photoreport/sdk";
|
||||
import { useEffect } from "react";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
import { rememberPhotoFrame } from "./lightroomCrop.js";
|
||||
import { flushFailedPhotoFiles, flushRecentPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js";
|
||||
|
||||
const LOCAL = "local:";
|
||||
@@ -54,6 +55,11 @@ function diskSha(photoId: string, apiSha: string | null | undefined): string | n
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The original Lightroom has open. The server hash can be the preview, which is not in the work folder. */
|
||||
export function fileShaForPhoto(photoId: string, apiSha: string | null | undefined): string | null {
|
||||
return diskSha(photoId, apiSha);
|
||||
}
|
||||
|
||||
function shaOf(id: string): string | null {
|
||||
if (id.startsWith(LOCAL)) return id.slice(LOCAL.length);
|
||||
const onDisk = originalSha(id);
|
||||
@@ -226,6 +232,7 @@ export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise<v
|
||||
for (const photo of page.photos) {
|
||||
const sha = diskSha(photo.id, photo.sha256);
|
||||
if (!sha) continue;
|
||||
rememberPhotoFrame(sha, photo.width, photo.height);
|
||||
remember(photo.id, sha);
|
||||
const sent = photo.delivery === "DONE";
|
||||
const marks = marksOf(photo.flag, photo.rating, photo.colorLabel, sent);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fromLightroomEdges, toLightroomEdges } from "./lightroomCrop.js";
|
||||
|
||||
/** PSR12211.JPG: a 3:2 crop with a strong straighten. Written raw, Lightroom levelled it to about 1.21. */
|
||||
const shot = { left: 0.024609, top: 0.078821, right: 0.799609, bottom: 0.853821 };
|
||||
const angle = -5.9;
|
||||
const width = 6000;
|
||||
const height = 4000;
|
||||
|
||||
function sides(rect: { left: number; top: number; right: number; bottom: number }): { w: number; h: number } {
|
||||
return { w: rect.right - rect.left, h: rect.bottom - rect.top };
|
||||
}
|
||||
|
||||
describe("Lightroom crop corners", () => {
|
||||
it("keeps the photograph's aspect after Lightroom levels the straighten", () => {
|
||||
const stored = toLightroomEdges(shot, angle, width, height);
|
||||
const shown = fromLightroomEdges(stored, angle, width, height);
|
||||
const got = sides(shown);
|
||||
expect(Math.abs(got.w - got.h)).toBeLessThan(0.0001);
|
||||
expect(stored.left).toBeGreaterThanOrEqual(0);
|
||||
expect(stored.top).toBeGreaterThanOrEqual(0);
|
||||
expect(stored.right).toBeLessThanOrEqual(1);
|
||||
expect(stored.bottom).toBeLessThanOrEqual(1);
|
||||
const pxW = got.w * width;
|
||||
const pxH = got.h * height;
|
||||
expect(pxW / pxH).toBeCloseTo(width / height, 3);
|
||||
});
|
||||
|
||||
it("shrinks a crop that would leave the photo once it is turned", () => {
|
||||
const full = { left: 0.01, top: 0.01, right: 0.99, bottom: 0.99 };
|
||||
const stored = toLightroomEdges(full, 2.64, width, height);
|
||||
expect(stored.left).toBeGreaterThanOrEqual(0);
|
||||
expect(stored.top).toBeGreaterThanOrEqual(0);
|
||||
expect(stored.right).toBeLessThanOrEqual(1);
|
||||
expect(stored.bottom).toBeLessThanOrEqual(1);
|
||||
const shown = fromLightroomEdges(stored, 2.64, width, height);
|
||||
const got = sides(shown);
|
||||
expect(Math.abs(got.w - got.h)).toBeLessThan(0.0001);
|
||||
expect(got.w).toBeLessThan(0.98);
|
||||
});
|
||||
|
||||
it("leaves a level crop untouched", () => {
|
||||
const rect = { left: 0.1, top: 0.1, right: 0.8, bottom: 0.8 };
|
||||
expect(toLightroomEdges(rect, 0, width, height)).toEqual(rect);
|
||||
expect(fromLightroomEdges(rect, 0, width, height)).toEqual(rect);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Lightroom stores a crop as two opposite corners plus an angle. It then turns those corners
|
||||
* back around the crop centre, and the levelled rectangle is what the crop tool shows.
|
||||
* The app's crop is already that levelled rectangle (the photograph's own aspect: equal
|
||||
* width and height in frame fractions). Writing it straight through makes the levelled
|
||||
* result a different proportion, which the crop tool labels Custom.
|
||||
*/
|
||||
|
||||
export interface CropEdges {
|
||||
left: number;
|
||||
top: number;
|
||||
right: number;
|
||||
bottom: number;
|
||||
}
|
||||
|
||||
export interface PhotoFrame {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
const frames = new Map<string, PhotoFrame>();
|
||||
|
||||
/** Pixel size of a local original, so a later read can turn Lightroom's corners back into the levelled crop. */
|
||||
export function rememberPhotoFrame(sha256: string, width: number | null | undefined, height: number | null | undefined): void {
|
||||
if (!sha256) return;
|
||||
if (typeof width !== "number" || typeof height !== "number") return;
|
||||
if (!(width > 0) || !(height > 0)) return;
|
||||
frames.set(sha256, { width, height });
|
||||
}
|
||||
|
||||
export function photoFrame(sha256: string): PhotoFrame | null {
|
||||
return frames.get(sha256) ?? null;
|
||||
}
|
||||
|
||||
function turn(x: number, y: number, cx: number, cy: number, deg: number): [number, number] {
|
||||
const th = (deg * Math.PI) / 180;
|
||||
const dx = x - cx;
|
||||
const dy = y - cy;
|
||||
const c = Math.cos(th);
|
||||
const s = Math.sin(th);
|
||||
return [dx * c - dy * s + cx, dx * s + dy * c + cy];
|
||||
}
|
||||
|
||||
/** Top-left frame fractions as pixels with y growing up, the space the corner rotation is defined in. */
|
||||
function pixel(x: number, yTop: number, width: number, height: number): [number, number] {
|
||||
return [x * width, (1 - yTop) * height];
|
||||
}
|
||||
|
||||
function shrunk(rect: CropEdges, scale: number): CropEdges {
|
||||
const cx = (rect.left + rect.right) / 2;
|
||||
const cy = (rect.top + rect.bottom) / 2;
|
||||
const halfW = ((rect.right - rect.left) / 2) * scale;
|
||||
const halfH = ((rect.bottom - rect.top) / 2) * scale;
|
||||
return {
|
||||
left: cx - halfW,
|
||||
top: cy - halfH,
|
||||
right: cx + halfW,
|
||||
bottom: cy + halfH,
|
||||
};
|
||||
}
|
||||
|
||||
function cornersFit(rect: CropEdges, angle: number, width: number, height: number): boolean {
|
||||
const ul = pixel(rect.left, rect.top, width, height);
|
||||
const lr = pixel(rect.right, rect.bottom, width, height);
|
||||
const cx = (ul[0] + lr[0]) / 2;
|
||||
const cy = (ul[1] + lr[1]) / 2;
|
||||
const a = -angle;
|
||||
const pts: Array<[number, number]> = [
|
||||
pixel(rect.left, rect.top, width, height),
|
||||
pixel(rect.right, rect.top, width, height),
|
||||
pixel(rect.right, rect.bottom, width, height),
|
||||
pixel(rect.left, rect.bottom, width, height),
|
||||
];
|
||||
const eps = 0.5;
|
||||
for (const [x, y] of pts) {
|
||||
const [rx, ry] = turn(x, y, cx, cy, a);
|
||||
if (rx < -eps || ry < -eps || rx > width + eps || ry > height + eps) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function storedEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
|
||||
const ul = pixel(rect.left, rect.top, width, height);
|
||||
const lr = pixel(rect.right, rect.bottom, width, height);
|
||||
const cx = (ul[0] + lr[0]) / 2;
|
||||
const cy = (ul[1] + lr[1]) / 2;
|
||||
const a = -angle;
|
||||
const sul = turn(ul[0], ul[1], cx, cy, a);
|
||||
const slr = turn(lr[0], lr[1], cx, cy, a);
|
||||
return {
|
||||
left: sul[0] / width,
|
||||
top: 1 - sul[1] / height,
|
||||
right: slr[0] / width,
|
||||
bottom: 1 - slr[1] / height,
|
||||
};
|
||||
}
|
||||
|
||||
function ordered(rect: CropEdges): boolean {
|
||||
if (!(rect.left < rect.right && rect.top < rect.bottom)) return false;
|
||||
if (rect.left < -0.000001 || rect.top < -0.000001) return false;
|
||||
if (rect.right > 1.000001 || rect.bottom > 1.000001) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Corners to write for `crs:Crop*`. `rect` is the levelled crop (what the tool should show).
|
||||
* A non-zero angle turns those corners about the crop centre, then shrinks until they stay on the photo.
|
||||
*/
|
||||
export function toLightroomEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
|
||||
if (!(width > 0) || !(height > 0)) return rect;
|
||||
if (!Number.isFinite(angle) || Math.abs(angle) < 0.05) return rect;
|
||||
let scale = 1;
|
||||
let fitted = rect;
|
||||
for (let i = 0; i < 80; i++) {
|
||||
fitted = shrunk(rect, scale);
|
||||
const stored = storedEdges(fitted, angle, width, height);
|
||||
if (cornersFit(fitted, angle, width, height) && ordered(stored)) return stored;
|
||||
scale -= 0.012;
|
||||
if (scale < 0.08) break;
|
||||
}
|
||||
return storedEdges(fitted, angle, width, height);
|
||||
}
|
||||
|
||||
/** The levelled crop Lightroom shows for corners it stored. Inverse of `toLightroomEdges` when nothing was shrunk. */
|
||||
export function fromLightroomEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
|
||||
if (!(width > 0) || !(height > 0)) return rect;
|
||||
if (!Number.isFinite(angle) || Math.abs(angle) < 0.05) return rect;
|
||||
const ul = pixel(rect.left, rect.top, width, height);
|
||||
const lr = pixel(rect.right, rect.bottom, width, height);
|
||||
const cx = (ul[0] + lr[0]) / 2;
|
||||
const cy = (ul[1] + lr[1]) / 2;
|
||||
const a = -angle;
|
||||
const uul = turn(ul[0], ul[1], cx, cy, -a);
|
||||
const ulr = turn(lr[0], lr[1], cx, cy, -a);
|
||||
return {
|
||||
left: uul[0] / width,
|
||||
top: 1 - uul[1] / height,
|
||||
right: ulr[0] / width,
|
||||
bottom: 1 - ulr[1] / height,
|
||||
};
|
||||
}
|
||||
@@ -9,6 +9,23 @@ describe("Lightroom sidecar", () => {
|
||||
expect(xml).not.toContain("crs:Shadows2012");
|
||||
});
|
||||
|
||||
it("turns a straightened crop so Lightroom still shows the photograph's aspect", () => {
|
||||
const xml = lightroomXmp(
|
||||
JSON.stringify({
|
||||
crop: {
|
||||
geometry: {
|
||||
angle: -5.9,
|
||||
rect: { x0: 0.024609, y0: 0.078821, x1: 0.799609, y1: 0.853821 },
|
||||
aspect: [6000, 4000],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(xml).toContain('crs:CropAngle="-5.90"');
|
||||
expect(xml).not.toContain('crs:CropLeft="0.024609"');
|
||||
expect(xml).not.toContain('crs:CropTop="0.078821"');
|
||||
});
|
||||
|
||||
it("writes a soft crop in the same crs fields Lightroom and Photo Mechanic read", () => {
|
||||
const xml = lightroomXmp(JSON.stringify({ crop: { geometry: { angle: -1.91, rect: { x0: 0, y0: 0.126385, x1: 0.861387, y1: 0.926887 } } } }));
|
||||
expect(xml).toContain('crs:HasCrop="True"');
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { DevelopState, EditCommand } from "@photoreport/contracts";
|
||||
import { cropFromXmp } from "@photoreport/metadata";
|
||||
import { localPhotos } from "../offline/local.js";
|
||||
import { desktopInvoke, isDesktop } from "../platform.js";
|
||||
import { fromLightroomEdges, photoFrame, toLightroomEdges, type PhotoFrame } from "./lightroomCrop.js";
|
||||
|
||||
/** Soft crop written as crs:Crop* (same numbers SoftCropGuide / Photo Mechanic draw). */
|
||||
/** Soft crop in the app: the levelled rectangle. The file stores Lightroom's turned corners. */
|
||||
export interface SoftCrop {
|
||||
left: number;
|
||||
top: number;
|
||||
@@ -201,7 +204,7 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str
|
||||
}
|
||||
|
||||
/** Only the sliders that are actually set. Missing ones stay out of the sidecar, so Lightroom is not given a preset. */
|
||||
export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIptc): string | null {
|
||||
export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIptc, frame?: PhotoFrame | null): string | null {
|
||||
let doc: Record<string, unknown>;
|
||||
try {
|
||||
const parsed = JSON.parse(settings) as unknown;
|
||||
@@ -243,12 +246,14 @@ export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIpt
|
||||
if (sharpen !== undefined) attrs.push(`crs:Sharpness="${crsNumber(sharpen, 0)}"`);
|
||||
if (nr !== undefined) attrs.push(`crs:ColorNoiseReduction="${crsNumber(nr, 0)}"`);
|
||||
if (crop) {
|
||||
const size = frameOf(doc) ?? frame ?? null;
|
||||
const edges = size ? toLightroomEdges(crop, crop.angle, size.width, size.height) : crop;
|
||||
attrs.push(
|
||||
`crs:HasCrop="True"`,
|
||||
`crs:CropLeft="${crop.left.toFixed(6)}"`,
|
||||
`crs:CropTop="${crop.top.toFixed(6)}"`,
|
||||
`crs:CropRight="${crop.right.toFixed(6)}"`,
|
||||
`crs:CropBottom="${crop.bottom.toFixed(6)}"`,
|
||||
`crs:CropLeft="${edges.left.toFixed(6)}"`,
|
||||
`crs:CropTop="${edges.top.toFixed(6)}"`,
|
||||
`crs:CropRight="${edges.right.toFixed(6)}"`,
|
||||
`crs:CropBottom="${edges.bottom.toFixed(6)}"`,
|
||||
`crs:CropAngle="${crsNumber(crop.angle, 2)}"`,
|
||||
`crs:CropConstrainToUnitSquare="1"`,
|
||||
`crs:AlreadyApplied="False"`,
|
||||
@@ -278,7 +283,15 @@ export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIpt
|
||||
|
||||
function foldEdit(doc: Record<string, unknown>, command: EditCommand): void {
|
||||
if (command.command === "develop.set") Object.assign(doc, command.params.values);
|
||||
else if (command.command === "crop.set") doc.crop = { geometry: { rect: command.params.rect, angle: command.params.angle ?? 0 } };
|
||||
else if (command.command === "crop.set") {
|
||||
const geometry: { rect: typeof command.params.rect; angle: number; aspect?: [number, number] } = {
|
||||
rect: command.params.rect,
|
||||
angle: command.params.angle ?? 0,
|
||||
};
|
||||
const aspect = command.params.aspect;
|
||||
if (aspect && aspect[0] > 0 && aspect[1] > 0) geometry.aspect = [aspect[0], aspect[1]];
|
||||
doc.crop = { geometry };
|
||||
}
|
||||
else if (command.command === "develop.merge") Object.assign(doc, command.params.partial);
|
||||
else if (command.command === "develop.reset") {
|
||||
for (const key of Object.keys(doc)) delete doc[key];
|
||||
@@ -299,6 +312,56 @@ export function settingsFromDevelop(state: DevelopState): string {
|
||||
return JSON.stringify(doc);
|
||||
}
|
||||
|
||||
function frameOf(doc: Record<string, unknown>): PhotoFrame | null {
|
||||
const crop = doc.crop;
|
||||
if (!crop || typeof crop !== "object") return null;
|
||||
const geometry = (crop as { geometry?: unknown }).geometry;
|
||||
if (!geometry || typeof geometry !== "object") return null;
|
||||
const aspect = (geometry as { aspect?: unknown }).aspect;
|
||||
if (!Array.isArray(aspect) || aspect.length < 2) return null;
|
||||
const width = aspect[0];
|
||||
const height = aspect[1];
|
||||
if (typeof width !== "number" || typeof height !== "number") return null;
|
||||
if (!(width > 0) || !(height > 0)) return null;
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
function docOf(settings: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const parsed = JSON.parse(settings) as unknown;
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
return parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Pixel size for this file: the crop's own aspect, then a size learned from the library. */
|
||||
export function frameForPhoto(sha256: string, settings: string): PhotoFrame | null {
|
||||
const doc = docOf(settings);
|
||||
if (doc) {
|
||||
const fromCrop = frameOf(doc);
|
||||
if (fromCrop) return fromCrop;
|
||||
}
|
||||
const known = photoFrame(sha256);
|
||||
if (known) return known;
|
||||
const local = localPhotos.bySha(sha256);
|
||||
if (local && local.width && local.height && local.width > 0 && local.height > 0) {
|
||||
return { width: local.width, height: local.height };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A straighten with no pixel size would be written as a different aspect. Hold the file until the size is known. */
|
||||
export function cropWaitsForFrame(settings: string, frame: PhotoFrame | null): boolean {
|
||||
const doc = docOf(settings);
|
||||
if (!doc) return false;
|
||||
const crop = cropOf(doc);
|
||||
if (!crop || Math.abs(crop.angle) < 0.05) return false;
|
||||
if (frameOf(doc) || frame) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function cropOf(doc: Record<string, unknown>): SoftCrop | null {
|
||||
const crop = doc.crop;
|
||||
if (!crop || typeof crop !== "object") return null;
|
||||
@@ -438,7 +501,13 @@ function invokeWithTimeout(command: string, args: Record<string, unknown>): Prom
|
||||
async function flushPhotoFile(sha256: string): Promise<void> {
|
||||
const row = rememberedNow.get(sha256) ?? loadRemembered()[sha256];
|
||||
if (!row) return;
|
||||
const xml = lightroomXmp(row.settings, { flag: row.flag, rating: row.rating, colorLabel: row.colorLabel, sent: row.sent }, iptcOf(row.iptc));
|
||||
const frame = frameForPhoto(sha256, row.settings);
|
||||
// Without the pixel size a straighten is written as another aspect. Wait, and retry.
|
||||
if (cropWaitsForFrame(row.settings, frame)) {
|
||||
flushFailed.add(sha256);
|
||||
return;
|
||||
}
|
||||
const xml = lightroomXmp(row.settings, { flag: row.flag, rating: row.rating, colorLabel: row.colorLabel, sent: row.sent }, iptcOf(row.iptc), frame);
|
||||
if (!xml) return;
|
||||
// Write the file first. Soft-crop bookkeeping must not block or abort the Lightroom packet.
|
||||
try {
|
||||
@@ -453,7 +522,13 @@ async function flushPhotoFile(sha256: string): Promise<void> {
|
||||
try {
|
||||
const { noteOwnSoftCropWrite } = await import("./softCropWatch.js");
|
||||
const writtenFlag = row.sent || row.flag === "PICK" ? "PICK" : row.flag === "REJECT" ? "REJECT" : row.flag === "NONE" ? "NONE" : undefined;
|
||||
noteOwnSoftCropWrite(sha256, softCropFromSettings(row.settings), writtenFlag);
|
||||
const raw = cropFromXmp(xml);
|
||||
let noted = softCropFromSettings(row.settings);
|
||||
if (raw && frame && Math.abs(raw.angle) >= 0.05) {
|
||||
const back = fromLightroomEdges(raw, raw.angle, frame.width, frame.height);
|
||||
noted = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: raw.angle };
|
||||
}
|
||||
noteOwnSoftCropWrite(sha256, noted, writtenFlag);
|
||||
} catch {
|
||||
// Watcher is optional; the file already has the marks.
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { cropFromXmp, type SoftCrop, xmpPacketFromJpeg } from "@photoreport/metadata";
|
||||
import { desktopInvoke, isDesktop } from "../platform.js";
|
||||
import { fromLightroomEdges, photoFrame } from "./lightroomCrop.js";
|
||||
|
||||
const cache = new Map<string, SoftCrop | null>();
|
||||
const inflight = new Map<string, Promise<SoftCrop | null>>();
|
||||
@@ -39,7 +40,16 @@ export async function softCropFor(sha256: string): Promise<SoftCrop | null> {
|
||||
const work = (async () => {
|
||||
try {
|
||||
const xmp = await localXmpText(sha256);
|
||||
const crop = xmp ? cropFromXmp(xmp) : null;
|
||||
const raw = xmp ? cropFromXmp(xmp) : null;
|
||||
if (!raw || Math.abs(raw.angle) < 0.05) {
|
||||
cache.set(sha256, raw);
|
||||
return raw;
|
||||
}
|
||||
const frame = photoFrame(sha256);
|
||||
// The file stores turned corners. Without the photo size they are not the crop to draw.
|
||||
if (!frame) return raw;
|
||||
const back = fromLightroomEdges(raw, raw.angle, frame.width, frame.height);
|
||||
const crop = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: raw.angle };
|
||||
cache.set(sha256, crop);
|
||||
return crop;
|
||||
} catch {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { colorClassFromXmp, cropFromXmp, libraryMarksFromXmp, type SoftCrop, typ
|
||||
import type { ColorLabel, PhotoFlag } from "@photoreport/contracts";
|
||||
import { desktopInvoke, isDesktop } from "../platform.js";
|
||||
import { offlineQueue } from "../offline/queue.js";
|
||||
import { fromLightroomEdges, photoFrame } from "./lightroomCrop.js";
|
||||
import { forgetSoftCrop, localXmpText } from "./softCrop.js";
|
||||
|
||||
/**
|
||||
@@ -159,7 +160,20 @@ export async function reconcileSoftCrops(
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const crop = cropFromXmp(xmp);
|
||||
const rawCrop = cropFromXmp(xmp);
|
||||
// A straighten is stored as turned corners. Without the photo size those corners are not the crop we show.
|
||||
if (rawCrop && Math.abs(rawCrop.angle) >= 0.05 && !photoFrame(row.sha256)) {
|
||||
next.push(row);
|
||||
continue;
|
||||
}
|
||||
let crop = rawCrop;
|
||||
if (rawCrop && Math.abs(rawCrop.angle) >= 0.05) {
|
||||
const frame = photoFrame(row.sha256);
|
||||
if (frame) {
|
||||
const back = fromLightroomEdges(rawCrop, rawCrop.angle, frame.width, frame.height);
|
||||
crop = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: rawCrop.angle };
|
||||
}
|
||||
}
|
||||
const color = colorClassFromXmp(xmp);
|
||||
const marks = libraryMarksFromXmp(xmp);
|
||||
let colorApplied = color ? row.color : (row.color ?? "");
|
||||
|
||||
@@ -42,6 +42,8 @@ export const t = {
|
||||
label: "sem ligação",
|
||||
waiting: (n: number) => (n === 1 ? "1 alteração à espera de ligação" : `${n} alterações à espera de ligação`),
|
||||
waitingHelp: "Feito sem ligação ao servidor: fica guardado neste computador e é enviado sozinho quando a ligação voltar.",
|
||||
pending: (n: number) => (n === 1 ? "1 alteração por enviar" : `${n} alterações por enviar`),
|
||||
pendingHelp: "A ligação está feita. Estas alterações seguem para o servidor.",
|
||||
queuedDelivery: "Sem ligação: o envio fica à espera e sai sozinho quando a ligação voltar.",
|
||||
editingOffline: "Sem ligação: as edições ficam guardadas neste computador e são enviadas quando a ligação voltar.",
|
||||
},
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { SoftCrop } from "@photoreport/metadata";
|
||||
import type { ColorLabel, PhotoSummary } from "@photoreport/contracts";
|
||||
import { memo, useEffect, useRef, useState } from "react";
|
||||
import { fileShaForPhoto } from "../desktop/fileMarks.js";
|
||||
import { rememberPhotoFrame } from "../desktop/lightroomCrop.js";
|
||||
import { softCropFor } from "../desktop/softCrop.js";
|
||||
import { watchSoftCropPhoto } from "../desktop/softCropWatch.js";
|
||||
import { t } from "../i18n.js";
|
||||
@@ -41,19 +43,23 @@ const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, o
|
||||
const [softCrop, setSoftCrop] = useState<SoftCrop | null>(null);
|
||||
useEffect(() => setImgFailed(false), [shown]);
|
||||
useEffect(() => {
|
||||
if (!isDesktop() || !photo.sha256) {
|
||||
const sha = fileShaForPhoto(photo.id, photo.sha256);
|
||||
if (!isDesktop() || !sha) {
|
||||
setSoftCrop(null);
|
||||
return;
|
||||
}
|
||||
if (orgId) watchSoftCropPhoto(orgId, photo.id, photo.sha256);
|
||||
if (orgId) {
|
||||
rememberPhotoFrame(sha, photo.width, photo.height);
|
||||
watchSoftCropPhoto(orgId, photo.id, sha);
|
||||
}
|
||||
let alive = true;
|
||||
void softCropFor(photo.sha256).then((crop) => {
|
||||
void softCropFor(sha).then((crop) => {
|
||||
if (alive) setSoftCrop(crop);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [orgId, photo.id, photo.sha256]);
|
||||
}, [orgId, photo.id, photo.sha256, photo.width, photo.height]);
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
|
||||
@@ -6,10 +6,24 @@ import { io } from "socket.io-client";
|
||||
export type LiveState = "connecting" | "live" | "offline";
|
||||
|
||||
const liveListeners = new Set<() => void>();
|
||||
let liveSockets = 0;
|
||||
|
||||
/** At least one library socket is connected. Several screens each open their own. */
|
||||
export function isSocketLive(): boolean {
|
||||
return liveSockets > 0;
|
||||
}
|
||||
|
||||
function noteSocket(up: boolean): void {
|
||||
if (up) liveSockets += 1;
|
||||
else liveSockets = Math.max(0, liveSockets - 1);
|
||||
if (!up) return;
|
||||
for (const fn of [...liveListeners]) fn();
|
||||
}
|
||||
|
||||
/** The library socket connected. Waiting edits go out on this, not on a timer. */
|
||||
export function onSocketLive(fn: () => void): () => void {
|
||||
liveListeners.add(fn);
|
||||
if (liveSockets > 0) fn();
|
||||
return () => liveListeners.delete(fn);
|
||||
}
|
||||
|
||||
@@ -33,17 +47,33 @@ export function useLibraryLive(api: ApiClient, onMessage: (message: LibraryMessa
|
||||
);
|
||||
},
|
||||
});
|
||||
let connected = false;
|
||||
const mark = (up: boolean) => {
|
||||
if (up === connected) return;
|
||||
connected = up;
|
||||
noteSocket(up);
|
||||
};
|
||||
socket.on("connect", () => {
|
||||
setState("live");
|
||||
for (const fn of liveListeners) fn();
|
||||
mark(true);
|
||||
});
|
||||
socket.on("disconnect", () => {
|
||||
setState("offline");
|
||||
mark(false);
|
||||
});
|
||||
socket.on("connect_error", () => {
|
||||
setState("offline");
|
||||
mark(false);
|
||||
});
|
||||
socket.on("disconnect", () => setState("offline"));
|
||||
socket.on("connect_error", () => setState("offline"));
|
||||
socket.on(LIBRARY_CHANNEL, (message: LibraryMessage) => handler.current(message));
|
||||
socket.on("desk", (command: DeskCommand) => {
|
||||
window.dispatchEvent(new CustomEvent("photoreport-desk", { detail: command }));
|
||||
});
|
||||
return () => {
|
||||
socket.off("connect");
|
||||
socket.off("disconnect");
|
||||
socket.off("connect_error");
|
||||
mark(false);
|
||||
socket.close();
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
@@ -86,6 +86,29 @@ describe("offline queue", () => {
|
||||
expect(q.size).toBe(0);
|
||||
});
|
||||
|
||||
it("sends a pick queued after the photo is already on the server", async () => {
|
||||
const q = new OfflineQueue("o1", store);
|
||||
q.uploaded("abc", "server-1");
|
||||
q.enqueueEdit(localId("abc"), { command: "develop.set", params: { values: { "light.exposure": 0.4 } } });
|
||||
q.add({ kind: "patch", ids: [localId("abc")], patch: { flag: "PICK" } });
|
||||
const sent: string[][] = [];
|
||||
const edits: string[] = [];
|
||||
const api = {
|
||||
updatePhotos: vi.fn(async (_org: string, ids: string[]) => {
|
||||
sent.push(ids);
|
||||
return { updated: ids.length };
|
||||
}),
|
||||
postEdits: vi.fn(async (photoId: string) => {
|
||||
edits.push(photoId);
|
||||
return { developSeq: 1, ops: [] };
|
||||
}),
|
||||
} as unknown as ApiClient;
|
||||
await q.flush(api);
|
||||
expect(sent).toEqual([["server-1"]]);
|
||||
expect(edits).toEqual(["server-1"]);
|
||||
expect(q.size).toBe(0);
|
||||
});
|
||||
|
||||
it("drops what the server refuses for good", async () => {
|
||||
const q = new OfflineQueue("o1", store);
|
||||
q.add({ kind: "patch", ids: ["gone"], patch: { flag: "PICK" } });
|
||||
|
||||
@@ -202,34 +202,51 @@ export class OfflineQueue {
|
||||
|
||||
/** Develop edits made offline on photos no longer open (or uploaded since). Repeated ops are ignored by the server. */
|
||||
private async flushOutboxes(api: ApiClient): Promise<void> {
|
||||
let changed = false;
|
||||
const notify = () => {
|
||||
if (!changed) return;
|
||||
changed = false;
|
||||
for (const fn of this.listeners) fn();
|
||||
};
|
||||
for (const key of this.outboxKeys()) {
|
||||
const photoId = key.slice(OUTBOX.length);
|
||||
let photoId = key.slice(OUTBOX.length);
|
||||
if (isLocalId(photoId)) {
|
||||
// Edited in Revelar before (and after) the upload: those edits follow the photo.
|
||||
// Edited before the upload finished: those edits follow the photo, then go out in this same pass.
|
||||
const id = this.serverId(photoId);
|
||||
if (id) this.uploaded(photoId.slice(LOCAL.length), id);
|
||||
continue;
|
||||
if (!id) continue;
|
||||
this.uploaded(photoId.slice(LOCAL.length), id);
|
||||
photoId = id;
|
||||
changed = true;
|
||||
}
|
||||
const storeKey = `${OUTBOX}${photoId}`;
|
||||
let ops: { opId: string; command: unknown }[];
|
||||
try {
|
||||
ops = JSON.parse(this.store.get(key) ?? "[]") as { opId: string; command: unknown }[];
|
||||
ops = JSON.parse(this.store.get(storeKey) ?? "[]") as { opId: string; command: unknown }[];
|
||||
} catch {
|
||||
this.store.remove(key);
|
||||
this.store.remove(storeKey);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if (!ops.length) {
|
||||
this.store.remove(key);
|
||||
this.store.remove(storeKey);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await api.postEdits(photoId, { clientId: "offline-queue", ops } as unknown as Parameters<ApiClient["postEdits"]>[1]);
|
||||
} catch (err) {
|
||||
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) return;
|
||||
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) {
|
||||
notify();
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Sent (or refused for good). An editor still open on the photo keeps its own copy and resends harmlessly.
|
||||
if (this.store.get(key) === JSON.stringify(ops)) this.store.remove(key);
|
||||
if (this.store.get(storeKey) === JSON.stringify(ops)) {
|
||||
this.store.remove(storeKey);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (const fn of this.listeners) fn();
|
||||
notify();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { PhotoPatch } from "@photoreport/contracts";
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
import { onSocketLive } from "../library/realtime.js";
|
||||
import { isSocketLive, onSocketLive } from "../library/realtime.js";
|
||||
import { localPhotos } from "./local.js";
|
||||
import { isLocalId, isNetworkError, offlineQueue, type OfflineQueue } from "./queue.js";
|
||||
|
||||
@@ -9,23 +9,44 @@ import { isLocalId, isNetworkError, offlineQueue, type OfflineQueue } from "./qu
|
||||
* Sends what was kept while the socket was down, the moment it is live again. A change made while the socket is
|
||||
* already live goes out in `patchPhotos` itself. The socket is the clock: down, keep it; live, send it.
|
||||
*/
|
||||
const SEND_DELAY_MS = 40;
|
||||
const SEND_AGAIN_MS = 1500;
|
||||
const SEND_TRIES = 5;
|
||||
|
||||
export function useOfflineSync(api: ApiClient, orgId: string): void {
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
const queue = offlineQueue(orgId);
|
||||
return onSocketLive(() => {
|
||||
let tries = 0;
|
||||
const send = () => {
|
||||
let tries = 0;
|
||||
let timer = 0;
|
||||
const send = () => {
|
||||
if (!isSocketLive()) return;
|
||||
window.clearTimeout(timer);
|
||||
timer = window.setTimeout(() => {
|
||||
void queue.flush(api).then(() => {
|
||||
// Still waiting (the link dropped mid-send): try again while this connection stays up.
|
||||
if (queue.size > 0 && tries < 5) {
|
||||
// Still waiting (the link dropped mid-send, or a photo was still uploading): try again.
|
||||
if (queue.size > 0 && isSocketLive() && tries < SEND_TRIES) {
|
||||
tries += 1;
|
||||
window.setTimeout(send, 1500);
|
||||
window.setTimeout(send, SEND_AGAIN_MS);
|
||||
}
|
||||
if (queue.size === 0) tries = 0;
|
||||
});
|
||||
};
|
||||
}, SEND_DELAY_MS);
|
||||
};
|
||||
// A pick made while the socket is already up never sees another "connect". Send those too.
|
||||
const stopLive = onSocketLive(() => {
|
||||
tries = 0;
|
||||
send();
|
||||
});
|
||||
const stopQueue = queue.subscribe(() => {
|
||||
tries = 0;
|
||||
send();
|
||||
});
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
stopLive();
|
||||
stopQueue();
|
||||
};
|
||||
}, [api, orgId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ import { ALL_PHOTOS, applyPatch, isMac, type LibraryFilter, matchesFilter, patch
|
||||
import { t } from "../i18n.js";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { forgetSoftCrop, softCropFor } from "../desktop/softCrop.js";
|
||||
import { fileShaForPhoto } from "../desktop/fileMarks.js";
|
||||
import { rememberPhotoFrame } from "../desktop/lightroomCrop.js";
|
||||
import { onSoftCropApplied, watchSoftCropPhoto } from "../desktop/softCropWatch.js";
|
||||
import { writeLightroomSidecar } from "../desktop/lightroomSidecar.js";
|
||||
import { isDesktop, localOriginalToView, prefs } from "../platform.js";
|
||||
@@ -235,25 +237,29 @@ export function DevelopPage() {
|
||||
|
||||
// Embed the develop crop into the JPEG as crs:Crop* (AlreadyApplied=False), the same Soft Crop Photo Mechanic reads.
|
||||
useEffect(() => {
|
||||
if (!isDesktop() || !session?.loaded || session.hasPending || session.seq < 1 || !current?.sha256) return;
|
||||
const sha = current.sha256;
|
||||
const sha = current?.id ? fileShaForPhoto(current.id, current.sha256) : null;
|
||||
if (!isDesktop() || !session?.loaded || session.hasPending || session.seq < 1 || !sha) return;
|
||||
const settings = session.settings;
|
||||
const timer = setTimeout(() => {
|
||||
forgetSoftCrop(sha);
|
||||
void writeLightroomSidecar(sha, settings);
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, [session, version, current?.sha256]);
|
||||
}, [session, version, current?.id, current?.sha256]);
|
||||
|
||||
// Watch the local file while this photo is open: Lightroom / Photo Mechanic crop changes become develop crops.
|
||||
useEffect(() => {
|
||||
if (!isDesktop() || !orgId || !current?.id || !current.sha256) return;
|
||||
watchSoftCropPhoto(orgId, current.id, current.sha256);
|
||||
}, [orgId, current?.id, current?.sha256]);
|
||||
if (!isDesktop() || !orgId || !current?.id) return;
|
||||
const sha = fileShaForPhoto(current.id, current.sha256);
|
||||
if (!sha) return;
|
||||
rememberPhotoFrame(sha, current.width, current.height);
|
||||
watchSoftCropPhoto(orgId, current.id, sha);
|
||||
}, [orgId, current?.id, current?.sha256, current?.width, current?.height]);
|
||||
|
||||
// A file that already has a Lightroom soft crop and no develop crop yet: start from that rectangle.
|
||||
useEffect(() => {
|
||||
if (!isDesktop() || !session?.loaded || !current?.sha256 || session.hasPending || session.seq > 0) return;
|
||||
const sha = current?.id ? fileShaForPhoto(current.id, current.sha256) : null;
|
||||
if (!isDesktop() || !session?.loaded || !sha || session.hasPending || session.seq > 0) return;
|
||||
const currentCrop = cropOf(session.settings);
|
||||
const full =
|
||||
currentCrop.rect.x0 <= 0.001 &&
|
||||
@@ -263,7 +269,7 @@ export function DevelopPage() {
|
||||
Math.abs(currentCrop.angle) < 0.05;
|
||||
if (!full) return;
|
||||
let alive = true;
|
||||
void softCropFor(current.sha256).then((soft) => {
|
||||
void softCropFor(sha).then((soft) => {
|
||||
if (!alive || !soft || !session) return;
|
||||
session.edit(
|
||||
{
|
||||
@@ -280,7 +286,7 @@ export function DevelopPage() {
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [session, version, current?.sha256]);
|
||||
}, [session, version, current?.id, current?.sha256]);
|
||||
|
||||
// Soft crop applied by the file watcher while this session is open: paint it immediately.
|
||||
useEffect(() => {
|
||||
|
||||
@@ -902,8 +902,8 @@ export function LibraryPage() {
|
||||
)}
|
||||
<span className="ml-auto flex items-center gap-3 font-mono text-[11px] text-faint">
|
||||
{waitingChanges > 0 && (
|
||||
<span className="text-star" title={t.offline.waitingHelp}>
|
||||
{t.offline.waiting(waitingChanges)}
|
||||
<span className="text-star" title={live === "live" ? t.offline.pendingHelp : t.offline.waitingHelp}>
|
||||
{live === "live" ? t.offline.pending(waitingChanges) : t.offline.waiting(waitingChanges)}
|
||||
</span>
|
||||
)}
|
||||
<span>
|
||||
|
||||
+21
-5
@@ -396,8 +396,9 @@ A match does not stop when the venue's internet does. The desktop app keeps work
|
||||
photo in the event of its capture time (the same rule as the server), with id `local:<sha256>`. It can be culled,
|
||||
named and edited before it is uploaded; the server's copy replaces it when the upload is done, keeping what was done.
|
||||
- **Changes wait, in order** (`offline/queue.ts`, localStorage): culling, players, IPTC and "send to" made without a
|
||||
network are kept and sent when the server answers (every 10 s and on `online`); changes to a photo not uploaded yet
|
||||
wait for it. Develop edits use the per-photo outbox (`develop/session.ts`) and follow the photo to its server id.
|
||||
network are kept and sent when the socket is up, including a change made while it was already up. Changes to a
|
||||
photo not uploaded yet wait for it. Develop edits use the per-photo outbox (`develop/session.ts`) and follow the
|
||||
photo to its server id.
|
||||
- **Uploads wait instead of failing**: the queue pauses on a network error and resumes when the connection is back.
|
||||
- The autopilot runs on the server when the photo arrives, and never over a person's edit (made offline first).
|
||||
|
||||
@@ -496,9 +497,24 @@ server may store on the photo.
|
||||
|
||||
**Cull marks from disk into the library (XMP → library).** On local FTP arrival, hand import, and server
|
||||
ingest, PhotoReport reads the same XMP fields back into the library (pick / reject / stars / colour). Soft
|
||||
crop becomes a develop `crop.set`. The desktop watcher re-reads work-folder originals while the app is open,
|
||||
so a pick or crop painted in Lightroom / Photo Mechanic lands without another import. The 2048 px FTP preview
|
||||
is never the source of marks — the original JPEG is.
|
||||
crop becomes a develop `crop.set`. The desktop watcher re-reads work-folder originals while the app is open
|
||||
(every few seconds, for photos on screen and photos that arrived on this computer), so a pick, a star, a colour
|
||||
or a crop painted in Lightroom / Photo Mechanic lands without another import and is sent to the server. The
|
||||
2048 px FTP preview is never the source of marks — the original JPEG is, found by the hash recorded at upload
|
||||
(`pr.localmap`), not by the preview hash the server may store.
|
||||
|
||||
What comes back from the file: the crop, the pick or reject, the stars and the colour. Exposure, white balance
|
||||
and the other develop sliders are written out for Lightroom, and are not read back. Lightroom has to write the
|
||||
change into the file (automatically write changes into XMP, or save metadata to the file). A change that stays
|
||||
only in the Lightroom catalog is invisible.
|
||||
|
||||
A straightened crop is stored as the corners Lightroom turns back around the crop centre. Writing the levelled
|
||||
rectangle plus the angle makes Lightroom show another proportion (Custom). The levelled result is always the
|
||||
photograph's own aspect. The autopilot never chooses another one (`docs/photo-editing-rules.md`).
|
||||
|
||||
A photo that was already delivered is sent again to that same destination about a minute after the edit
|
||||
settles, under the same file name, replacing the previous file. A destination that takes the untouched
|
||||
original is not sent again: it has no edit to carry.
|
||||
|
||||
**Cull marks on delivery.** The same pick / reject / stars / colour are written into the delivered JPEG
|
||||
(plus digiKam `PickLabel` and IPTC Urgency for Photo Mechanic). When the desktop app is open it watches local
|
||||
|
||||
@@ -44,6 +44,9 @@ Following the AP and NPPA codes:
|
||||
- **Shape:** the autopilot keeps the photograph's own aspect (non-negotiable). The crop may move anywhere across
|
||||
the frame, including a tighter window, but it is not turned into another format. A square, a 4:5, a 16:9, or a
|
||||
portrait crop of a landscape frame is not an autopilot crop. An editor, by hand, may still choose another aspect.
|
||||
A file written for Lightroom stores a straightened crop as the corners Lightroom turns back around the crop
|
||||
centre, so the crop tool still shows this aspect. Writing the levelled rectangle together with the angle makes
|
||||
Lightroom call it Custom.
|
||||
- **Lead room (sport):** leave space in the direction the player looks or runs; put their back nearer the opposite
|
||||
edge. Dead space behind the facing direction is wrong. Without a reliable facing signal (face on the body, or
|
||||
the ball in play), keep the subject centred as before. Reportage and open team frames do not force lead room.
|
||||
|
||||
Reference in new issue
Block a user