import type { Edits, PhotoRecord } from '../types'; import { normalizeEdits } from './edits'; /** * Lightroom-compatible XMP sidecars. * * The crs: attributes are the shared vocabulary, so a sidecar written here * carries the grade into Lightroom and one written by Lightroom opens here. * Lightroom has no slot for everything Luminary can do (film curves, HSL, * local layers, denoise), so the full edit is also written to a private * `lum:Settings` attribute as base64 JSON. Import prefers that attribute when * it is present and falls back to reading the crs: fields otherwise, which * keeps round trips exact without making the file useless elsewhere. */ const LUM_NS = 'https://luminary.app/xmp/1.0'; /** crs field, direction: our edits use the same -100…100 scale. */ const CRS_FIELDS: [string, (edits: Edits) => number][] = [ ['Exposure2012', (e) => e.exposure], ['Contrast2012', (e) => e.contrast], ['Highlights2012', (e) => e.highlights], ['Shadows2012', (e) => e.shadows], ['Whites2012', (e) => e.whites], ['Blacks2012', (e) => e.blacks], ['Texture', (e) => e.texture], ['Clarity2012', (e) => e.clarity], ['Dehaze', (e) => e.dehaze], ['Vibrance', (e) => e.vibrance], ['Saturation', (e) => e.saturation], ['ParametricHighlights', (e) => e.parametric.highlights], ['ParametricLights', (e) => e.parametric.lights], ['ParametricDarks', (e) => e.parametric.darks], ['ParametricBlacks', (e) => e.parametric.blacks], ['PostCropVignetteAmount', (e) => e.vignette.amount], ['GrainAmount', (e) => e.grain.amount], ]; const CRS_TO_EDIT: Record void> = { Exposure2012: (e, v) => (e.exposure = v), Contrast2012: (e, v) => (e.contrast = v), Highlights2012: (e, v) => (e.highlights = v), Shadows2012: (e, v) => (e.shadows = v), Whites2012: (e, v) => (e.whites = v), Blacks2012: (e, v) => (e.blacks = v), Texture: (e, v) => (e.texture = v), Clarity2012: (e, v) => (e.clarity = v), Dehaze: (e, v) => (e.dehaze = v), Vibrance: (e, v) => (e.vibrance = v), Saturation: (e, v) => (e.saturation = v), ParametricHighlights: (e, v) => (e.parametric.highlights = v), ParametricLights: (e, v) => (e.parametric.lights = v), ParametricDarks: (e, v) => (e.parametric.darks = v), ParametricBlacks: (e, v) => (e.parametric.blacks = v), PostCropVignetteAmount: (e, v) => (e.vignette.amount = v), GrainAmount: (e, v) => (e.grain.amount = v), ConvertToGrayscale: (e, v) => (e.bw = v >= 0.5 || v === 1), }; export interface XmpImport { edits: Edits; /** How the settings were read: exact Luminary payload or crs fallback. */ source: 'luminary' | 'lightroom'; /** crs fields the sidecar set, for the toast. */ applied: string[]; } function escapeXml(value: string) { return value .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function unescapeXml(value: string) { return value .replace(/"/g, '"') .replace(/'/g, "'") .replace(/</g, '<') .replace(/>/g, '>') .replace(/&/g, '&'); } function base64Encode(text: string) { const bytes = new TextEncoder().encode(text); let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); return btoa(binary); } function base64Decode(value: string) { const binary = atob(value); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); return new TextDecoder().decode(bytes); } function num(value: number) { return Number.isFinite(value) ? String(Math.round(value * 1000) / 1000) : '0'; } /** Sidecar name for a photo: "DSC0123.ARW" → "DSC0123.xmp". */ export function xmpFileName(name: string) { return `${name.replace(/\.[^.]+$/, '') || 'photo'}.xmp`; } export function editsToXmp(edits: Edits, photo?: Pick): string { const normalized = normalizeEdits(edits); const attrs = CRS_FIELDS.map( ([name, read]) => `crs:${name}="${num(read(normalized))}"`, ); attrs.push(`crs:ConvertToGrayscale="${normalized.bw ? 'True' : 'False'}"`); if (normalized.kelvin != null) attrs.push(`crs:Temperature="${Math.round(normalized.kelvin)}"`); attrs.push(`lum:Settings="${escapeXml(base64Encode(JSON.stringify(normalized)))}"`); const label = photo ? escapeXml(photo.name) : 'Luminary edit'; return [ '', '', ' ', ` `, ` ${label}`, ' ', ' ', '', '', ].join('\n'); } function attributes(xml: string) { const out = new Map(); const pattern = /([A-Za-z][\w:.-]*)\s*=\s*"([^"]*)"/g; let match: RegExpExecArray | null; while ((match = pattern.exec(xml))) { // Later duplicates lose: rdf:about="" repeats on every nested node. if (!out.has(match[1])) out.set(match[1], unescapeXml(match[2])); } return out; } /** * Reads settings from a sidecar. `base` supplies every field the file does not * mention, so importing a Lightroom crop-free sidecar keeps the photo's mask * layers, crop and lens profile instead of resetting them. */ export function xmpToEdits(xml: string, base: Edits): XmpImport { if (!/; return { edits: normalizeEdits({ ...base, ...parsed }), source: 'luminary', applied: ['Luminary settings'], }; } catch { // A damaged private payload still leaves the crs: fields to read. } } const next = normalizeEdits(base); const applied: string[] = []; for (const [name, apply] of Object.entries(CRS_TO_EDIT)) { const raw = attrs.get(`crs:${name}`); if (raw === undefined) continue; const value = name === 'ConvertToGrayscale' ? raw === 'True' || raw === 'true' || raw === '1' ? 1 : 0 : Number(raw); if (!Number.isFinite(value)) continue; apply(next, value); applied.push(name); } const temperature = attrs.get('crs:Temperature'); const tint = attrs.get('crs:Tint'); if (temperature !== undefined) { const kelvin = Number(temperature); // Lightroom's Temperature is absolute Kelvin; the absolute control here is // defined against a 5500 K daylight reference, so the value transfers // directly and the panel shows the same number. if (Number.isFinite(kelvin) && kelvin >= 1500 && kelvin <= 15000) { next.kelvin = kelvin; applied.push('Temperature'); } } if (tint !== undefined) { const value = Number(tint); if (Number.isFinite(value)) { next.tint = Math.max(-100, Math.min(100, value)); applied.push('Tint'); } } if (!applied.length) throw new Error('No develop settings found in that sidecar'); return { edits: normalizeEdits(next), source: 'lightroom', applied }; } /** Opens the OS picker and returns the sidecar text, or null when cancelled. */ export function readXmpFile(): Promise { return new Promise((resolve, reject) => { const input = document.createElement('input'); input.type = 'file'; input.accept = '.xmp,application/rdf+xml,text/xml,application/xml'; input.onchange = () => { const file = input.files?.[0]; if (!file) { resolve(null); return; } file.text().then(resolve, reject); }; input.click(); }); } /** * Sidecars named after the file next to the original, the way Lightroom writes * them, plus the download helper used by the library action. */ export function downloadXmp(photo: PhotoRecord) { const blob = new Blob([editsToXmp(photo.edits, photo)], { type: 'application/rdf+xml' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = xmpFileName(photo.name); document.body.appendChild(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(url), 4000); }