From f6596b7145eea1af5f9eb2e334f32791fae2f360 Mon Sep 17 00:00:00 2001 From: Ralph Largo Date: Thu, 3 Dec 2026 04:01:37 +0800 Subject: [PATCH 1/6] docs: amend constitution to v1.0.1 (allow same-folder staging file for atomic writes) Resolve the conflict between Principle I (temp files in the OS temp directory) and Principle IV (atomic rename into place) by permitting a single hidden, owner-only staging file in the destination folder, with cleanup on failure, cancel, normal exit, and next launch. --- .specify/memory/constitution.md | 52 ++++++++++++++++++++------------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/.specify/memory/constitution.md b/.specify/memory/constitution.md index 8c7d46f..1cdb708 100644 --- a/.specify/memory/constitution.md +++ b/.specify/memory/constitution.md @@ -1,26 +1,30 @@ @@ -46,6 +50,13 @@ built with Rust and Tauri, installable on macOS, Ubuntu, and Windows. no remote content loaded into the webview. - Temporary files MUST be created in the OS temp directory with restrictive permissions and MUST be removed when a conversion finishes, fails, or is cancelled. +- **Exception: final-stage staging file.** To allow the atomic write required by + Principle IV, the single file holding a conversion's finished output MAY be created in + the destination folder instead. It MUST be hidden (a dot-prefixed name unique to the app), + readable and writable only by the current user, and deleted if the conversion fails or is + cancelled. Staging files left behind by a crash or forced quit MUST be deleted when the + app exits normally and at the next launch. All other intermediate data MUST stay in the + OS temp directory. Rationale: People convert private photos, contracts, and recordings. Keeping everything local is the core product promise and removes a whole class of security risks. @@ -83,7 +94,8 @@ growing. A uniform interface keeps each new format cheap to add and isolated fro - Source files MUST NEVER be modified, moved, or deleted by a conversion. - Output MUST be written to a temporary file and atomically renamed into place only on - success; a failed or cancelled conversion MUST NOT leave partial output behind. + success; a failed or cancelled conversion MUST NOT leave partial output behind. The + staging file follows the Principle I exception. - Existing files MUST NOT be overwritten silently. The default is a non-colliding name (e.g., `photo (1).png`); overwriting requires an explicit user choice. - Every failure MUST produce an actionable, human-readable error (what failed, which @@ -196,4 +208,4 @@ cross-platform risk. - **Review cadence**: Revisit the constitution when a principle is repeatedly waived or when platform targets change. -**Version**: 1.0.0 | **Ratified**: 2026-12-03 | **Last Amended**: 2026-12-03 +**Version**: 1.0.1 | **Ratified**: 2026-12-03 | **Last Amended**: 2026-12-03 From 06f8c176939d7a4ec553222f6a13d4a60864b2c7 Mon Sep 17 00:00:00 2001 From: Ralph Largo Date: Thu, 3 Dec 2026 04:01:37 +0800 Subject: [PATCH 2/6] docs: add image conversion MVP spec, plan, and tasks Specify the first feature: 9 input and 7 output image/PDF formats (57 conversion pairs), with batch conversion, cancellation, metadata preservation, and crash-safe output. Includes research decisions, data model, IPC and core API contracts, quickstart validation guide, and 91 tasks organized by user story, updated with /speckit-analyze fixes. --- .../checklists/requirements.md | 38 ++ .../contracts/core-api.md | 88 +++ .../001-image-conversion-mvp/contracts/ipc.md | 142 +++++ specs/001-image-conversion-mvp/data-model.md | 159 ++++++ specs/001-image-conversion-mvp/plan.md | 179 ++++++ specs/001-image-conversion-mvp/quickstart.md | 78 +++ specs/001-image-conversion-mvp/research.md | 255 +++++++++ specs/001-image-conversion-mvp/spec.md | 351 ++++++++++++ specs/001-image-conversion-mvp/tasks.md | 514 ++++++++++++++++++ 9 files changed, 1804 insertions(+) create mode 100644 specs/001-image-conversion-mvp/checklists/requirements.md create mode 100644 specs/001-image-conversion-mvp/contracts/core-api.md create mode 100644 specs/001-image-conversion-mvp/contracts/ipc.md create mode 100644 specs/001-image-conversion-mvp/data-model.md create mode 100644 specs/001-image-conversion-mvp/plan.md create mode 100644 specs/001-image-conversion-mvp/quickstart.md create mode 100644 specs/001-image-conversion-mvp/research.md create mode 100644 specs/001-image-conversion-mvp/spec.md create mode 100644 specs/001-image-conversion-mvp/tasks.md diff --git a/specs/001-image-conversion-mvp/checklists/requirements.md b/specs/001-image-conversion-mvp/checklists/requirements.md new file mode 100644 index 0000000..7fef9d4 --- /dev/null +++ b/specs/001-image-conversion-mvp/checklists/requirements.md @@ -0,0 +1,38 @@ +# Specification Quality Checklist: Image Conversion MVP + +**Purpose**: Validate specification completeness and quality before proceeding to planning +**Created**: 2026-12-03 +**Feature**: [spec.md](../spec.md) + +## Content Quality + +- [x] No implementation details (languages, frameworks, APIs) +- [x] Focused on user value and business needs +- [x] Written for non-technical stakeholders +- [x] All mandatory sections completed + +## Requirement Completeness + +- [x] No [NEEDS CLARIFICATION] markers remain +- [x] Requirements are testable and unambiguous +- [x] Success criteria are measurable +- [x] Success criteria are technology-agnostic (no implementation details) +- [x] All acceptance scenarios are defined +- [x] Edge cases are identified +- [x] Scope is clearly bounded +- [x] Dependencies and assumptions identified + +## Feature Readiness + +- [x] All functional requirements have clear acceptance criteria +- [x] User scenarios cover primary flows +- [x] Feature meets measurable outcomes defined in Success Criteria +- [x] No implementation details leak into specification + +## Notes + +- Clarifications resolved 2026-12-03: Q1 any input → any output (57 pairs; the 20 listed are + priority pairs), Q2 keep all metadata including GPS (FR-015), Q3 SVG output traces into + vector shapes (FR-016). +- All items pass; spec is ready for `/speckit-clarify` or `/speckit-plan`. +- Items marked incomplete require spec updates before `/speckit-clarify` or `/speckit-plan` diff --git a/specs/001-image-conversion-mvp/contracts/core-api.md b/specs/001-image-conversion-mvp/contracts/core-api.md new file mode 100644 index 0000000..2a97c5b --- /dev/null +++ b/specs/001-image-conversion-mvp/contracts/core-api.md @@ -0,0 +1,88 @@ +# Contract: `largsform-core` public Rust API + +The conversion library is independent of Tauri (Constitution III). This is its public surface. +Everything else is private to the crate. The signatures are normative; the bodies are written +during implementation. + +```rust +// ---- formats ---- +pub enum Format { Jpeg, Png, Webp, Avif, Heic, Tiff, Gif, Svg, Pdf, Ico } +impl Format { + pub fn is_input(self) -> bool; + pub fn is_output(self) -> bool; + pub fn extension(self) -> &'static str; // "jpg", "png", ... +} + +/// Content-based detection (reads at most 4 KiB). FR-002. +pub fn detect_format(path: &Path) -> Result; +/// Header-only inspection for the file list (no full decode). +pub fn inspect(path: &Path) -> Result; + +// ---- registry / capabilities ---- +pub struct Registry { /* decoders × encoders */ } +impl Registry { + pub fn new() -> Self; // builds all 57 pairs + pub fn targets_for(&self, input: Format) -> Vec; + pub fn converter(&self, input: Format, output: Format) -> Option<&dyn Converter>; +} +pub struct Capability { pub output: Format, pub options: Vec, pub notices: Vec } + +// ---- converter trait (Constitution III) ---- +pub trait Converter: Send + Sync { + fn input(&self) -> Format; + fn output(&self) -> Format; + /// Decode + normalize + encode one source into staged (not yet persisted) outputs. + fn convert(&self, src: &Path, opts: &ConversionOptions, ctx: &mut ConvertCtx) + -> Result, ConversionError>; +} + +// Internal building blocks (pub(crate)); new formats plug in here. +pub(crate) trait Decoder: Send + Sync { + fn format(&self) -> Format; + fn decode(&self, src: &Path, opts: &ConversionOptions, ctx: &mut ConvertCtx) + -> Result, ConversionError>; +} +pub(crate) trait Encoder: Send + Sync { + fn format(&self) -> Format; + fn encode(&self, images: Vec, opts: &ConversionOptions, ctx: &mut ConvertCtx, + sink: &mut dyn OutputSink) -> Result<(), ConversionError>; +} + +/// Progress reporting and cancellation passed through every stage. +pub struct ConvertCtx { /* cancel: CancelToken, progress: Box, notices */ } +impl ConvertCtx { + pub fn check_cancelled(&self) -> Result<(), ConversionError>; // Err(Cancelled) + pub fn progress(&mut self, fraction: f32); + pub fn notice(&mut self, n: NoticeKind); +} + +// ---- output safety (Constitution IV) ---- +/// A temp file in the destination folder that has not been committed yet. Dropping it deletes it. +pub struct StagedOutput { /* tempfile + desired base name + page */ } +impl StagedOutput { + /// Atomic, no-clobber persist; appends " (n)" on collision. FR-018/FR-020. + pub fn commit(self, reserved: &mut NameReservations) -> Result; +} + +// ---- jobs ---- +pub struct JobRunner { /* registry, semaphore(available_parallelism) */ } +impl JobRunner { + pub fn run(&self, job: JobSpec, cancel: CancelToken, + events: impl Fn(JobEvent) + Send + Sync + 'static) -> JobSummary; +} +#[derive(Clone)] pub struct CancelToken(/* Arc */); +``` + +## Behavioral guarantees (tested in `crates/core/tests/`) + +| Guarantee | Test file | +|-----------|-----------| +| The source file's bytes and mtime are unchanged after any conversion | `output_safety.rs` | +| No file remains in the destination folder after a failure or cancel | `output_safety.rs` | +| An existing file is never overwritten; the `(n)` suffix sequence is correct | `naming.rs` | +| Every one of the 57 pairs converts its reference sample into a valid output | `conversions.rs` (generated matrix) | +| Corrupt or truncated samples return `Err(Corrupt)` and never panic | `corrupt.rs` (+ `cargo fuzz` target for detection) | +| EXIF (including GPS) is kept for JPG/PNG/WebP(/AVIF) output, and orientation is reset to 1 | `metadata.rs` | +| Output dimensions match the source, except for scale/DPI/ICO options | `conversions.rs` | +| `detect_format` ignores the extension | `detect.rs` | +| SVG input never reads `http(s):` or `file:` hrefs | `svg_security.rs` | diff --git a/specs/001-image-conversion-mvp/contracts/ipc.md b/specs/001-image-conversion-mvp/contracts/ipc.md new file mode 100644 index 0000000..ee9bf05 --- /dev/null +++ b/specs/001-image-conversion-mvp/contracts/ipc.md @@ -0,0 +1,142 @@ +# Contract: UI ↔ Core IPC (Tauri commands and channels) + +The only interface between the Svelte UI and Rust. Tauri commands are thin adapters over +`largsform-core` (Constitution III). All payloads are JSON (serde `camelCase`). Types match +[data-model.md](../data-model.md). + +Permissions: the frontend may call **only** the commands below, plus `dialog:allow-open` and the +scoped `opener` permissions (research R17). There is no `fs` or `http` plugin. + +## Commands + +### `add_files` + +Inspects paths from the file dialog or drag-and-drop. It does not decode pixels. + +```ts +invoke("add_files", { paths: string[] }): Promise + +type AddFilesResult = { + added: SourceFile[]; // newly added, in input order + duplicates: string[]; // paths already in the list (ignored) + rejected: { path: string; error: ConversionError }[]; // Unsupported, SourceMissing, Corrupt header +}; +``` + +- Directories are expanded one level and non-files are ignored. +- Must return within 200 ms for 100 files (header-only reads). + +### `remove_files` + +```ts +invoke("remove_files", { ids: number[] }): Promise +``` + +### `get_targets` + +```ts +invoke("get_targets", { ids: number[] }): Promise + +type TargetsResult = { + targets: { + format: OutputFormat; // "jpg" | "png" | "webp" | "avif" | "pdf" | "ico" | "svg" + applicableTo: number[]; // source ids that can convert to it + skipped: number[]; // source ids already in this format + options: OptionKind[]; // union across applicable sources + notices: { kind: NoticeKind; sourceIds: number[] }[]; + }[]; +}; +``` + +The UI uses this to show the target picker, the options, and the "will be skipped" and +pre-conversion notices (US2-4, FR-016 warning, transparency notice). + +### `start_job` + +```ts +invoke("start_job", { + request: { + sourceIds: number[]; // order = PDF page order when pdfLayout = "combine" + target: OutputFormat; + options: { + quality?: number; // 1..100, default 90 + pdfDpi?: 72 | 150 | 300; // default 150 + svgScale?: 1 | 2 | 4; // default 1 + pdfLayout?: "combine" | "separate"; // default "combine" + outputDir?: string | null; // null = next to each source + }; + }, + onEvent: Channel, +}): Promise<{ jobId: number }> +``` + +Errors (rejected promise): `InvalidOptions`, `OutputNotWritable` (when `outputDir` is set and +can't be written to), `NothingToConvert`. + +### `cancel_job` / `cancel_item` + +```ts +invoke("cancel_job", { jobId: number }): Promise +invoke("cancel_item", { jobId: number, sourceId: number }): Promise +``` + +Returns immediately. The UI receives `itemStatus: "cancelled"` within 1 s (SC-007). + +### `open_output` / `reveal_output` + +```ts +invoke("open_output", { path: string }): Promise +invoke("reveal_output", { path: string }): Promise +``` + +Rejected unless `path` is an `OutputFile.path` produced in this session (an allow-list held in +Rust state). + +## Channel events: `JobEvent` + +```ts +type JobEvent = + | { type: "itemStarted"; sourceId: number } + | { type: "itemProgress"; sourceId: number; progress: number } // 0..1, ≤ 10/s per item + | { type: "itemFinished"; sourceId: number; + status: "done" | "failed" | "cancelled" | "skipped"; + outputs: OutputFile[]; error?: ConversionError; notices: NoticeKind[] } + | { type: "jobFinished"; jobId: number; + status: "completed" | "cancelled"; + summary: { succeeded: number; failed: number; skipped: number; cancelled: number }; + combinedOutput?: OutputFile }; +``` + +Ordering guarantees: +- `itemStarted` comes before any `itemProgress` for that item. +- Exactly one `itemFinished` is sent per item. +- `jobFinished` is always the last event for a job. + +## Shared types + +```ts +type OutputFormat = "jpg" | "png" | "webp" | "avif" | "pdf" | "ico" | "svg"; +type InputFormat = OutputFormat | "heic" | "tiff" | "gif"; // note: "ico" is never detected as input +type OptionKind = "quality" | "pdfDpi" | "svgScale" | "pdfLayout"; +type NoticeKind = "transparencyFlattened" | "stylizedTrace" | "metadataDropped" + | "firstFrameOnly" | "firstImageOnly" | "externalSvgResourcesSkipped"; + +type SourceFile = { + id: number; path: string; name: string; sizeBytes: number; format: InputFormat; + width?: number; height?: number; pageCount?: number; frameCount?: number; hasAlpha?: boolean; +}; +type OutputFile = { path: string; format: OutputFormat; sourceIds: number[]; page?: number }; +type ConversionError = { + kind: "unsupported" | "corrupt" | "tooLarge" | "protectedPdf" | "sourceMissing" + | "outputNotWritable" | "diskFull" | "cancelled" | "internal"; + message: string; // user-facing, plain language + detail?: string; // technical +}; +``` + +## Contract tests + +- Rust: `src-tauri/tests/ipc_contract.rs` serializes every type and compares it with JSON + snapshots in `contracts/fixtures/*.json`. +- TS: `src/lib/ipc.test.ts` type-checks the same snapshots against the TS types, so drift between + the two sides fails CI. diff --git a/specs/001-image-conversion-mvp/data-model.md b/specs/001-image-conversion-mvp/data-model.md new file mode 100644 index 0000000..27125ce --- /dev/null +++ b/specs/001-image-conversion-mvp/data-model.md @@ -0,0 +1,159 @@ +# Data Model: Image Conversion MVP + +**Feature**: [spec.md](./spec.md) | **Plan**: [plan.md](./plan.md) + +All state is in-memory for the lifetime of the app. Nothing is persisted between launches (spec +Assumptions). Rust types live in `crates/core`. Their serialized form, shared with the UI, is +defined in [contracts/ipc.md](./contracts/ipc.md). + +## Format + +Enumeration of every supported format and its role. + +| Variant | Input | Output | Lossy quality | Alpha | Carries EXIF/ICC | Multi-image | +|---------|-------|--------|---------------|-------|------------------|-------------| +| `Jpeg` | ✓ | ✓ | ✓ | ✗ (flatten on white) | ✓ / ✓ | ✗ | +| `Png` | ✓ | ✓ | ✗ | ✓ | ✓ / ✓ | ✗ | +| `Webp` | ✓ | ✓ | ✓ | ✓ | ✓ / ✓ | ✗ (animated → first frame) | +| `Avif` | ✓ | ✓ | ✓ | ✓ | ✓* / ✓ | ✗ | +| `Heic` | ✓ | ✗ | — | ✓ | ✓ / ✓ | primary image only | +| `Tiff` | ✓ | ✗ | — | ✓ | ✓ / ✓ | first page only | +| `Gif` | ✓ | ✗ | — | ✓ (1-bit) | ✗ | first frame only | +| `Svg` | ✓ | ✓ (traced) | — | ✓ | ✗ | ✗ | +| `Pdf` | ✓ | ✓ | (JPEG pages at 90) | ✓ (SMask) | date only | ✓ pages | +| `Ico` | ✗ | ✓ | — | ✓ | ✗ | ✓ sizes | + +\* Subject to research spike Q3. + +**Validation**: A format is assigned only by content sniffing (research R13). The file extension +is used only for naming outputs. + +## SourceFile + +A file the user added. + +| Field | Type | Notes | +|-------|------|-------| +| `id` | `SourceId` (u64) | Unique within the session | +| `path` | absolute path | Canonicalized and used for de-duplication (edge case: same file added twice) | +| `name` | string | File name for display | +| `size_bytes` | u64 | | +| `format` | `Format` | Detected from content | +| `dimensions` | `{width, height}?` | From the header only, without a full decode. Unknown for PDFs | +| `page_count` | u32? | PDF only | +| `frame_count` | u32? | GIF/WebP/TIFF/HEIC; > 1 triggers the "first frame/page only" notice | +| `has_alpha` | bool? | Drives the transparency → white notice for JPG | +| `is_photographic` | bool? | Computed lazily when SVG is the target (research R9) | +| `warnings` | `Warning[]` | e.g. `AnimatedFirstFrameOnly`, `MultiImageFirstOnly` | + +**Rules**: The path must exist and be readable when added. A format that cannot be detected +rejects the file (FR-004) and it does not enter the list. + +## Target / FormatCapability + +The registry's view of what is possible. + +| Field | Type | Notes | +|-------|------|-------| +| `input` | `Format` | | +| `output` | `Format` | `input != output` | +| `options` | `OptionKind[]` | Which options apply: `Quality` (JPG/WebP/AVIF out), `PdfDpi` (PDF in), `SvgScale` (SVG in), `PdfLayout` (PDF out) | +| `notices` | `NoticeKind[]` | e.g. `TransparencyFlattened` (alpha → JPG), `StylizedTrace` (photo → SVG), `MetadataDropped` (→ ICO/SVG) | + +57 entries are built by the registry. `targets_for(format)` returns all outputs except the +format itself (FR-003). + +## ConversionOptions + +| Field | Type | Default | Valid range | +|-------|------|---------|-------------| +| `quality` | u8 | 90 | 1–100 | +| `pdf_dpi` | enum | `Dpi150` | `Dpi72`, `Dpi150`, `Dpi300` | +| `svg_scale` | enum | `X1` | `X1`, `X2`, `X4` | +| `pdf_layout` | enum | `Combine` | `Combine`, `Separate` | +| `output_dir` | path? | `None` → each source's own folder | Must exist and be writable (checked at job start) | + +Options that do not apply to a pair are ignored. + +## ConversionJob + +One "Convert" action. + +| Field | Type | Notes | +|-------|------|-------| +| `id` | `JobId` (u64) | | +| `target` | `Format` | One target for the whole job (FR-022) | +| `options` | `ConversionOptions` | | +| `items` | `ConversionItem[]` | In the user's list order. For `Combine`, this order is the page order | +| `status` | `JobStatus` | See the state machine below | +| `summary` | `{succeeded, failed, skipped, cancelled}` | Filled in once the job is finished | +| `combined_output` | `OutputFile?` | Only for PDF output with `Combine` | + +**Skipped items**: Items whose format equals the target are marked `Skipped` before the job +starts, and the UI shows them beforehand (US2 scenario 4). + +## ConversionItem + +| Field | Type | Notes | +|-------|------|-------| +| `source` | `SourceId` | | +| `status` | `ItemStatus` | | +| `progress` | f32 0..1 | Per-stage weighted estimate | +| `outputs` | `OutputFile[]` | One file normally. One per page for PDF→image | +| `error` | `ConversionError?` | When `Failed` | +| `notices` | `NoticeKind[]` | Notices that applied, e.g. `ExternalSvgResourcesSkipped` | + +### Item state machine + +```text +Waiting ──start──▶ Converting ──ok──▶ Done + │ │ └──error──▶ Failed + │ └──cancel──▶ Cancelled (temp output deleted) + ├──cancel──▶ Cancelled + └──(format == target, at job creation)──▶ Skipped +``` + +In `Combine` mode each item goes `Converting → Done` once it is decoded and staged. The combined +PDF is written after the last item. If no item succeeded, no PDF is written and the job reports a +failure. + +### Job state machine + +```text +Pending ──run──▶ Running ──all items terminal──▶ Completed + └──cancel job──▶ Cancelling ──in-flight items end──▶ Cancelled +``` + +`Completed` holds even when some items failed. The summary shows the counts (FR-023, FR-025). + +## OutputFile + +| Field | Type | Notes | +|-------|------|-------| +| `path` | absolute path | Final name after collision handling (`name (n).ext`) | +| `format` | `Format` | | +| `source` | `SourceId[]` | Several for a combined PDF | +| `page` | u32? | Set when exported from a PDF page (`-page-`) | + +**Naming rules (FR-018)**: +- Single output: `.`, where ext is `jpg`, `png`, `webp`, `avif`, `pdf`, `ico`, or `svg`. +- PDF page: `-page-.` (1-based, not zero-padded). +- Combined PDF: `.pdf`. +- On collision: ` (1).`, ` (2).`, … Names reserved by other outputs in the + same batch count as collisions too. + +## ConversionError + +| Field | Type | Notes | +|-------|------|-------| +| `kind` | enum | `Unsupported`, `Corrupt`, `TooLarge`, `ProtectedPdf`, `SourceMissing`, `OutputNotWritable`, `DiskFull`, `Cancelled`, `Internal` | +| `message` | string | Plain language: what failed and what the user can do (FR-026) | +| `detail` | string? | Technical detail, shown on request | + +## Decoded intermediate (internal, not exposed over IPC) + +`DecodedImage { pixels: DynamicImage, icc: Option>, exif: Option>, xmp: Option>, page: Option, dpi: Option<(f32, f32)> }` + +Decoders return `Vec`: one entry, or one per PDF page. The normalizer applies +orientation, patches EXIF orientation, and converts color when the target needs it. Encoders then +consume the result. See [contracts/core-api.md](./contracts/core-api.md). diff --git a/specs/001-image-conversion-mvp/plan.md b/specs/001-image-conversion-mvp/plan.md new file mode 100644 index 0000000..f8c8595 --- /dev/null +++ b/specs/001-image-conversion-mvp/plan.md @@ -0,0 +1,179 @@ +# Implementation Plan: Image Conversion MVP + +**Branch**: `feat/001-image-conversion-mvp` | **Date**: 2026-12-03 | **Spec**: [spec.md](./spec.md) + +**Input**: Feature specification from `/specs/001-image-conversion-mvp/spec.md` + +## Summary + +Build the first version of Largsform: a Tauri 2 desktop app that converts images and PDFs fully +offline on macOS, Ubuntu, and Windows. Nine input formats (HEIC, WebP, AVIF, JPG, PNG, TIFF, GIF, +SVG, PDF) convert to seven output formats (JPG, PNG, WebP, AVIF, PDF, ICO, SVG), giving 57 pairs. +Supporting features: batch conversion, progress, cancellation, metadata preservation, and +crash-safe output. + +Technical approach: a Tauri-independent Rust library (`largsform-core`) runs a +**decoder → normalizer → encoder** pipeline. Nine decoders and seven encoders combine into 57 +converters behind one `Converter` trait and registry. Outputs are written atomically with no +overwrite. A Svelte 5 UI talks to the core through a small set of Tauri commands and an event +channel. See [research.md](./research.md) for every technology decision. + +## Technical Context + +**Language/Version**: Rust stable (≥ 1.85, edition 2021); TypeScript 5.x (frontend) + +**Primary Dependencies**: +- App: Tauri 2.x, `tauri-plugin-dialog`, `tauri-plugin-opener`, Svelte 5, Vite +- Codecs: + - `image` 0.25 (jpeg, png, tiff, gif, webp, ico, avif-native/dav1d) + - `webp` (libwebp, lossy encode) + - `ravif` (AVIF encode) + - `heic` (pure-Rust HEIC; spike, with `libheif-rs` as fallback) + - `pdfium-render` + bundled PDFium library + - `pdf-writer` + - `resvg`/`usvg` + - `vtracer` +- Support: `img-parts` (EXIF/ICC/XMP write), `qcms` (color), `tempfile`, `tokio`, `thiserror`, + `serde` + +**Storage**: None. In-memory session state only. Files on disk are the user's inputs and outputs. + +**Testing**: +- `cargo test`: unit tests, a generated 57-pair fixture matrix, and safety/metadata/corrupt-input + tests +- `cargo fuzz` for format detection +- Vitest + Testing Library + `vitest-axe` +- WebdriverIO + `tauri-driver` E2E (Ubuntu/Windows) + +**Target Platform**: +- macOS 11+ (universal: arm64 + x86_64) +- Ubuntu 22.04+ x86_64 (webkit2gtk-4.1) +- Windows 10/11 x86_64 (WebView2) + +**Project Type**: Desktop application (Rust core library + Tauri shell + web UI) + +**Performance Goals** (Constitution VI, spec SC-002/003/007): +- Cold start < 2 s +- 12 MP single conversion: JPG/PNG/WebP/PDF/ICO output < 1 s; AVIF < 3 s; SVG < 10 s (photo) + and < 2 s (flat color); PDF input < 1 s per page at 150 DPI +- 100 photos < 60 s +- Cancellation shown < 1 s, with no new work started and no output from cancelled items + +**Constraints**: +- Fully offline, with zero network requests +- Idle memory < 150 MB +- Per-item allocation limit 2 GiB +- Installer < 100 MB (estimated 15–25 MB) +- WCAG 2.1 AA + +**Scale/Scope**: +- 10 formats (9 inputs, 7 outputs), 57 pairs +- 1 main screen (file list, target picker, options, summary) +- Batches of up to about 1,000 files + +## Constitution Check + +*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* + +| Principle | Gate | Pre-research | Post-design | Evidence | +|-----------|------|--------------|-------------|----------| +| I. Local-First Privacy & Security | No uploads or telemetry; content-based detection; no panics on bad input; least-privilege Tauri; temp cleanup (v1.0.1 staging-file exception) | ✅ | ✅ | R13 sniffer, R8 SVG href resolver, R17 (no `fs`/`http` plugins, strict CSP, opener allow-list), per-item `catch_unwind` + decoder fuzzing (R15, T022, T027), staging journal with exit and next-launch cleanup (R14, T019, T030), SC-008 network check. Residual risk of crashes in C libraries is recorded in R15 | +| II. Cross-Platform Parity | Every feature works on all 3 OSes; installers for all 3; neutral paths; platform code isolated | ✅ | ✅ | Pure-Rust codecs or vendored builds. PDFium binaries exist for all 3. CI matrix (R18). No OS codec APIs | +| III. Pluggable Converter Architecture | One `Converter` trait + registry; core independent of Tauri; external tools behind the trait | ✅ | ✅ | R1 pipeline, [core-api.md](./contracts/core-api.md). `src-tauri` commands are thin ([ipc.md](./contracts/ipc.md)). PDFium is behind the `Decoder` trait and its availability is checked at startup | +| IV. Never Destroy User Data | Sources untouched; atomic temp + rename; no silent overwrite; actionable errors | ✅ | ✅ | R14 `persist_noclobber` + `(n)` naming, `output_safety.rs`, `ConversionError.message`/`detail` | +| V. Pragmatic Testing | Unit tests for logic; ≥ 1 fixture test per pair; regression tests for bugs; UI tests for critical flows | ✅ | ✅ | 57-pair matrix (several samples for the 20 priority pairs), E2E for add → convert → error flows | +| VI. Performance & Responsiveness | Off the UI thread; progress + cancel; streaming where possible; bounded parallelism; budgets | ✅ | ✅ | R15 (spawn_blocking + semaphore + memory-aware limit, CancelToken, throttled progress). Cancel is available from US1, the first shippable increment. Per-format budgets are in SC-002 and checked by T039 and T084. Still images are decoded whole: streaming does not apply to them, and memory is bounded by `Limits` | +| VII. Accessibility (WCAG 2.1 AA) | Keyboard-only; picker alternative to drag-and-drop; screen-reader announcements; reduced motion and theme | ✅ | ✅ | R16 Svelte a11y compile checks + `vitest-axe`. A file dialog is always available. ARIA live region for job events. `prefers-reduced-motion`/`prefers-color-scheme` | +| VIII. Simplicity / YAGNI | Prefer pure Rust; justify binaries and new abstractions | ✅ | ✅ (one external binary, justified) | 16 decoders/encoders instead of 57 converters. No persistence, previews, plugin system, or updater. PDFium is the only bundled binary (Complexity Tracking) | +| Tech constraints: licensing | License review before adopting any bundled binary | ✅ | ✅ (action item) | PDFium BSD/Apache, libwebp BSD, dav1d BSD, rav1e BSD, vtracer MIT, resvg Apache/MIT. HEVC patent note and LGPL (fallback only) recorded in R5. **Owner sign-off required before the first public release** | + +**Gate result**: PASS. No unjustified violations. Re-checked after constitution v1.0.1 and the +`/speckit-analyze` fixes (C1, C2, I1, I2, I3, A1, G1). + +## Project Structure + +### Documentation (this feature) + +```text +specs/001-image-conversion-mvp/ +├── plan.md # This file +├── research.md # Phase 0: decisions R1–R18 +├── data-model.md # Phase 1: entities, state machines, naming rules +├── quickstart.md # Phase 1: build/run/validate guide +├── contracts/ +│ ├── ipc.md # Tauri commands + JobEvent channel (UI ↔ core) +│ └── core-api.md # largsform-core public Rust API + guarantees +├── checklists/ +│ └── requirements.md # Spec quality checklist +└── tasks.md # Phase 2 (/speckit-tasks, not created here) +``` + +### Source Code (repository root) + +```text +Cargo.toml # workspace: crates/core, src-tauri +package.json # pnpm: Svelte 5 + Vite + Tauri CLI +crates/core/ # largsform-core: no Tauri dependency +├── src/ +│ ├── lib.rs +│ ├── format.rs # Format enum + detect_format/inspect (R13) +│ ├── registry.rs # decoders × encoders → 57 converters, targets_for +│ ├── converter.rs # Converter trait, PipelineConverter, ConvertCtx, CancelToken +│ ├── decode/ # mod.rs, raster.rs (image crate), heic.rs, svg.rs, pdf.rs +│ ├── encode/ # mod.rs, jpeg_png.rs, webp.rs, avif.rs, pdf.rs, ico.rs, svg_trace.rs +│ ├── normalize.rs # orientation, alpha flatten, color → sRGB, bit depth (R12) +│ ├── metadata.rs # EXIF/ICC/XMP carry, orientation-tag patch (R11) +│ ├── output.rs # StagedOutput, persist_noclobber, (n) naming (R14) +│ ├── job.rs # JobRunner, semaphore, events, summary (R15) +│ └── error.rs # ConversionError kinds + user messages +├── tests/ +│ ├── fixtures/{samples,corrupt}/ +│ ├── conversions.rs # generated 57-pair matrix +│ ├── detect.rs naming.rs output_safety.rs metadata.rs corrupt.rs svg_security.rs +│ └── perf.rs # #[ignore] budget checks +└── fuzz/ # cargo-fuzz target: detect_format +src-tauri/ # Tauri shell (thin) +├── src/{main.rs, lib.rs, commands.rs, state.rs} +├── capabilities/default.json # dialog + scoped opener only +├── tauri.conf.json # CSP, bundle targets, resources (pdfium) +├── resources/pdfium/ # filled by scripts/fetch-pdfium.sh (not committed) +└── tests/ipc_contract.rs +src/ # Svelte 5 UI +├── App.svelte +├── lib/ +│ ├── ipc.ts # typed wrappers for contracts/ipc.md +│ ├── state.svelte.ts # file list, job state (runes) +│ └── components/ # DropZone, FileList, FileRow, TargetPicker, OptionsPanel, +│ # NoticeBanner, BatchSummary, LiveAnnouncer +└── **/*.test.ts # Vitest + Testing Library + axe +e2e/ # WebdriverIO specs: convert-single, batch-failure, cancel +scripts/fetch-pdfium.sh # pinned version + SHA-256 per platform +.github/workflows/ci.yml # macOS/Ubuntu/Windows matrix (R18) +``` + +**Structure Decision**: A Cargo workspace with the conversion engine in `crates/core`, kept apart +from the Tauri shell in `src-tauri` (Constitution III: core testable without the GUI). The Svelte +UI uses the standard Tauri layout at the repo root (`src/`). No separate CLI crate is built +(YAGNI): core integration tests exercise the engine directly. + +## Implementation phasing (input for `/speckit-tasks`) + +1. **Foundation**: Workspace, Tauri + Svelte scaffold, CI matrix, `format.rs` detection, + `output.rs` safety, `Converter`/registry skeleton, fixtures. Run the **R5 HEIC spike** and the + **R4 AVIF benchmark** early. +2. **US1 (P1)**: Raster decoders (JPG/PNG/WebP/AVIF/TIFF/GIF/HEIC), encoders + (JPG/PNG/WebP/AVIF), normalize + metadata, and a single-file UI flow with accessibility. +3. **US2 (P2)**: JobRunner batch, progress channel, cancel, summary, skipped/notice UI. +4. **US3 (P2)**: PDF decoder (PDFium) and PDF encoder (combine/separate, reorder UI, DPI option). +5. **US4 (P3)**: SVG decoder (resvg + safe resolver), ICO encoder, SVG tracing encoder + photo + warning. +6. **Polish**: Performance budget tests, network-silence check, installers for 3 OSes, + quickstart validation on each OS. + +## Complexity Tracking + +| Violation / Addition | Why Needed | Simpler Alternative Rejected Because | +|----------------------|------------|--------------------------------------| +| Bundled PDFium dynamic library (external binary, Principle VIII) | FR-010 needs a reliable rendering of real-world PDFs on all 3 OSes | `hayro` (pure Rust) describes itself as experimental. `mupdf` is AGPL. OS PDF APIs differ per platform (Principle II) | +| C codec libraries compiled from vendored source (libwebp, dav1d; libheif only as fallback) | Lossy WebP encoding (FR-008/SC-010) and AVIF decoding have no production-grade pure-Rust option | Lossless-only WebP fails SC-010. The pure-Rust AV1 decoder (`rav1d`) is an option to re-evaluate later | +| Possible AVIF encoder swap — *only if `ravif` misses the < 3 s SC-002 budget in T039* | AV1 encoding is much heavier than other codecs | `libavif` + SVT-AV1 would add a C/CMake build on 3 platforms; adopt only with measured numbers | diff --git a/specs/001-image-conversion-mvp/quickstart.md b/specs/001-image-conversion-mvp/quickstart.md new file mode 100644 index 0000000..9fcd0a3 --- /dev/null +++ b/specs/001-image-conversion-mvp/quickstart.md @@ -0,0 +1,78 @@ +# Quickstart & Validation: Image Conversion MVP + +How to build, run, and prove the feature works end to end. See [contracts/](./contracts/) and +[data-model.md](./data-model.md) for interface details. + +## Prerequisites + +| Tool | Version | +|------|---------| +| Rust | stable (≥ 1.85), `rustup component add clippy rustfmt` | +| Node.js | 22 LTS + pnpm 9 | +| Tauri prerequisites | per platform: Xcode CLT (macOS); `libwebkit2gtk-4.1-dev build-essential libssl-dev libayatana-appindicator3-dev librsvg2-dev` (Ubuntu 22.04+); MSVC Build Tools + WebView2 (Windows) | +| NASM / Meson | only if the dav1d build requires them on your platform (see the `avif-native` notes) | + +## Setup + +```bash +pnpm install +./scripts/fetch-pdfium.sh # downloads the pinned PDFium build and verifies its SHA-256 +``` + +## Run + +```bash +pnpm tauri dev # development app +pnpm tauri build # installers in src-tauri/target/release/bundle/ +``` + +## Automated validation + +```bash +cargo fmt --all --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace # unit + 57-pair fixture matrix + safety/metadata tests +cargo test -p largsform-core --release -- --ignored perf # performance budget checks (SC-002/003) +pnpm lint && pnpm check && pnpm test # ESLint, svelte-check/tsc, Vitest + axe +pnpm e2e # WebdriverIO + tauri-driver (Ubuntu/Windows) +``` + +Expected: all pass. The fixture matrix reports `57/57 pairs OK`. + +## Manual scenarios (run on macOS, Ubuntu, and Windows; SC-004) + +Sample files are in `crates/core/tests/fixtures/` (`samples/` holds valid files, `corrupt/` holds +broken ones). + +| # | Scenario | Steps | Expected | +|---|----------|-------|----------| +| 1 | Single HEIC → JPG (US1) | Drag `samples/iphone.heic` into the window, choose JPG, Convert | `iphone.jpg` appears next to the source, upright, with the same dimensions. The source is unchanged. Done in < 1 s | +| 2 | Keyboard only (FR-030) | Without the mouse: Tab to "Add files", pick a file, choose a target, Convert, open the output | Every step is reachable. Focus is always visible. The screen reader announces "Converted 1 file" | +| 3 | Metadata kept (FR-015) | Convert `samples/gps.jpg` → PNG, then inspect it with `exiftool` | Camera model, DateTimeOriginal and GPS are present, and Orientation = 1 | +| 4 | Transparency → JPG | `samples/alpha.png` → JPG | A notice is shown first. Transparent areas are white | +| 5 | Collision | Convert `photo.png` → JPG twice | `photo.jpg`, then `photo (1).jpg`. The first file is untouched | +| 6 | Batch + failure (US2) | Add 50 mixed samples + `corrupt/truncated.webp`, convert to PNG | 50 done, 1 failed with a readable reason. The summary shows 50/1/0 | +| 7 | Cancel (US2) | Start a batch of 100 large images, press Cancel | The UI shows cancelled within 1 s. There are no partial files and no `.largsform-*` leftovers | +| 8 | Images → one PDF (US3) | Add 3 images, reorder them, choose PDF (Combine) | One 3-page PDF in the new order, each page sized to its image | +| 9 | PDF → PNG (US3) | `samples/5-pages.pdf` → PNG at 300 DPI | `5-pages-page-1.png` … `-page-5.png`, at 300 DPI pixel size | +| 10 | Protected PDF | `samples/protected.pdf` → JPG | Fails with "Password-protected PDFs aren't supported yet". No output | +| 11 | PNG → ICO (US4) | `samples/logo-512.png` → ICO | One `.ico` containing the 16…256 sizes | +| 12 | PNG → SVG (US4) | `samples/logo-flat.png` → SVG, open it in a browser at 400% | Vector shapes, sharp when zoomed | +| 13 | Photo → SVG warning | `samples/photo.jpg` → SVG | A "stylized result / large file" notice is shown before converting | +| 14 | SVG with remote image | `samples/remote-href.svg` → PNG while monitoring the network | Renders without the remote image, shows a notice, and makes **zero** network requests (SC-008) | +| 15 | Wrong extension | `samples/png-named.jpg` → WebP | Detected as PNG and converts successfully | +| 16 | Offline | Disable networking and repeat scenario 1 | Works the same | + +## Performance spot-checks (release build, mid-range machine) + +| Check | Budget | +|-------|--------| +| Cold start to interactive window | < 2 s | +| Idle memory | < 150 MB | +| 12 MP photo → JPG / PNG / WebP / PDF / ICO (incl. HEIC → JPG) | < 1 s each | +| 12 MP JPG → AVIF | < 3 s | +| 12 MP photo → SVG / flat-color logo → SVG | < 10 s / < 2 s | +| PDF → image, per page at 150 DPI | < 1 s | +| 100 × 12 MP photos → JPG | < 60 s | +| Cancel → shown as cancelled, no output | < 1 s | +| Force-quit mid-conversion, relaunch | No `.largsform-*` files remain in the output folder | diff --git a/specs/001-image-conversion-mvp/research.md b/specs/001-image-conversion-mvp/research.md new file mode 100644 index 0000000..75843ca --- /dev/null +++ b/specs/001-image-conversion-mvp/research.md @@ -0,0 +1,255 @@ +# Research: Image Conversion MVP + +**Feature**: [spec.md](./spec.md) | **Plan**: [plan.md](./plan.md) | **Date**: 2026-12-03 + +Each entry records the decision, why it was chosen, and the alternatives considered. Items marked +**Spike** must be confirmed by an early task, against the fixture corpus, before dependent work +starts. Each spike names a fallback that has already been evaluated. + +--- + +## R1. Overall conversion architecture (57 pairs) + +- **Decision**: Use a two-stage pipeline: **Decoder** (input format → normalized images) then + **Encoder** (normalized images → output format). Each `(decoder, encoder)` pair is wrapped in a + `PipelineConverter` that implements the common `Converter` trait. The registry builds all + 9×7 − 6 = 57 pairs from the decoder and encoder lists. A pair-specific converter can override + the generic pipeline when needed (none are planned for the MVP). +- **Rationale**: Constitution III requires every conversion to sit behind one trait and be + discovered through a registry. Building 9 decoders and 7 encoders (16 units) is far cheaper + than 57 hand-written converters and keeps behavior consistent (orientation, metadata, color, + naming). +- **Alternatives considered**: One converter per pair (57 units of mostly duplicated code). Going + through an intermediate file format (loses metadata and alpha, and is slower). + +## R2. General raster codecs (JPG, PNG, TIFF, GIF, WebP decode, AVIF decode) + +- **Decision**: Use the `image` crate (0.25.x) with features `jpeg`, `png`, `tiff`, `gif`, + `webp`, `ico`, and `avif-native` (dav1d) for AVIF decoding. +- **Rationale**: This is the de facto standard, mostly pure-Rust codec set. Since 0.25.8 it + provides `ImageDecoder::orientation()`, `apply_orientation`, ICC and EXIF access, and allocation + `Limits` (needed for the "image too large" edge case). +- **Alternatives considered**: Calling each format's crate directly (more glue code). OS image + APIs such as ImageIO and WIC (behavior differs per platform, which breaks Constitution II). + +## R3. WebP encoding (lossy, quality-controlled) + +- **Decision**: Use the `webp` crate (libwebp compiled from vendored source through + `libwebp-sys`, BSD-3). +- **Rationale**: FR-008 needs lossy encoding with a quality setting. `image`'s WebP encoder is + lossless only. +- **Alternatives considered**: `image` lossless WebP (files often larger than the JPG source, + which fails SC-010). The `cwebp` sidecar binary (a separate process to manage, and Principle + VIII says to avoid it). + +## R4. AVIF encoding + +- **Decision**: Use `ravif` (rav1e, pure Rust, BSD-2) at encoder speed 8, quality mapped from the + 1–100 setting, with multi-threading. +- **Rationale**: Pure Rust, so no extra system libraries to ship. +- **Budget**: SC-002 sets AVIF output at < 3 s for 12 MP. Benchmark speeds 6/8/10 in T039 and + pick the slowest (best-quality) speed that meets the budget. If none does, evaluate the + `libavif` + SVT-AV1 bindings. +- **Alternatives considered**: `libavif` + libaom/SVT-AV1 (faster, but C and CMake builds on 3 + platforms). The `avifenc` sidecar (separate process, Principle VIII). + +## R5. HEIC/HEIF decoding — **Spike** + +- **Decision**: Start with a **pure-Rust HEIF/HEVC decoder** (`heic` crate by imazen: HEVC + I-slices, no C dependencies, passes the ITU-T HEVC conformance vectors). Put it behind the + `Decoder` trait so the backend can be swapped. +- **Spike acceptance**: Decode correctly 8-bit and 10-bit iPhone HEIC (including grid/tiled + primary images), HEIF from Android and Samsung phones, and extract EXIF and ICC. Results must + visually match the reference output (PSNR ≥ 40 dB against a libheif decode). Performance must be + under 1 s for 12 MP. +- **Fallback**: `libheif-rs` with the `embedded-libheif` feature (builds libheif statically + through CMake) plus a vendored libde265 build. Both are LGPL-3.0: link them dynamically, or + provide relinkable objects, and record this in the license review. +- **Rationale**: Constitution VIII prefers pure-Rust crates, and Constitution II needs identical + behavior on all three platforms without system packages. +- **Alternatives considered**: OS codecs (Windows needs a paid HEVC extension, so they fail + Constitution II). `heifer` and `ente-io/heic-decoder` (newer, less adoption; keep as secondary + candidates for the spike). +- **Legal note**: HEVC may be covered by third-party patents. Decoding only is the common practice + of open-source viewers. Record this in the license review (Constitution: Technology + Constraints). Owner sign-off is required before the first public release. + +## R6. PDF rendering (PDF → images) + +- **Decision**: Use `pdfium-render` bound at runtime to a **prebuilt PDFium dynamic library** + (bblanchon/pdfium-binaries, BSD-3/Apache-2.0). The library is pinned by release tag, verified by + SHA-256 in `scripts/fetch-pdfium.sh`, and shipped as a Tauri bundle resource on each platform. +- **Rationale**: PDFium is Chrome's renderer and handles real-world PDFs (forms, fonts, + transparency, broken files) far better than any pure-Rust option today. It adds about 5–6 MB + per platform, within the installer budget. +- **Alternatives considered**: `hayro` (pure Rust and promising, but self-described as + experimental; re-evaluate once it is stable, since it would remove the binary). `mupdf` (AGPL, + not acceptable). `pdfium-render` with the `static` feature (needs a custom PDFium build per + platform). +- **Complexity Tracking**: This is an external binary, so it is justified in the plan. + +## R7. PDF writing (images → PDF) + +- **Decision**: Use `pdf-writer` (from the Typst project, pure Rust, MIT/Apache). Each page is + sized to its image at 72 pt per inch, using the image's DPI metadata when present and 96 DPI + otherwise. Images are embedded as DCT (JPEG, quality 90) for opaque images, and as + Flate-compressed RGB plus an SMask for images with transparency. +- **Rationale**: Small, fast, and gives exact control over page size and image embedding. +- **Alternatives considered**: `printpdf` (larger API surface than needed). `lopdf` (lower level + for writing). Passing JPEG bytes through unchanged without re-encoding (lossless for JPG→PDF, + but needs separate orientation handling; deferred until after the MVP, per Principle VIII). + +## R8. SVG rendering (SVG → images) + +- **Decision**: Use `resvg`/`usvg`/`tiny-skia` (pure Rust). Use a custom `ImageHrefResolver` that + allows only `data:` URIs and refuses `http(s):` and `file:` references. Load system fonts with + `fontdb`. Render at the declared size × the chosen scale (1×, 2×, or 4×). When an SVG has no + declared size, use its viewBox size, or 512×512 when it has neither. +- **Rationale**: The reference Rust SVG renderer. The resolver enforces FR-012 and Constitution I + (no network or file access driven by untrusted SVG input), and reports skipped resources. + +## R9. Raster → SVG tracing + +- **Decision**: Use `vtracer` (pure Rust, MIT): color mode, spline curves, and automatic presets + (preset "photo" when the image has many unique colors, "poster" otherwise). Detection uses a + sampled unique-color count, with the threshold tuned on fixtures. +- **Rationale**: Delivers the Q3/FR-016 answer of real vector shapes in full color. +- **Photo warning**: An image counts as photographic when, after sampling, it has more than 4,096 + unique colors. The UI warns about this before conversion. +- **Alternatives considered**: `potrace` (black-and-white only, GPL). Wrapping the original pixels + in an SVG (rejected by Q3). + +## R10. ICO encoding + +- **Decision**: Use `image`'s `IcoEncoder::write_images` with PNG-compressed entries at + 16/32/48/64/128/256 pixels. Sizes larger than the source are skipped. Non-square images are + centered on a transparent square canvas. Downscaling uses Lanczos3. +- **Rationale**: Already a dependency, and multi-size ICO is supported. + +## R11. Metadata preservation (Q2: keep all, FR-015) + +- **Decision**: + 1. Read EXIF, ICC, and XMP from the decoder (`image` metadata APIs; HEIF metadata items through + the HEIC decoder). + 2. Apply orientation to the pixels, then set EXIF tag 0x0112 to 1 using a small in-house IFD0 + patcher that edits the existing EXIF block in place. No other EXIF tags are touched. + 3. Write the metadata with `img-parts` (pure Rust) after encoding, for JPG, PNG, and WebP + (EXIF + ICC + XMP). For AVIF use the encoder's EXIF support (verify in the R5/R4 spikes; + fallback: an ICC-only container). + 4. AVIF: FR-015 applies (AVIF can store EXIF). If `ravif` cannot write EXIF (spike Q3), add + an `Exif` item to the AVIF container after encoding (ISO-BMFF `iinf`/`iloc`/`iref cdsc` + edit in `metadata.rs`), and verify it with `exiftool` in tests. + 5. ICO, SVG: drop metadata (the formats cannot carry it). + 6. PDF: copy the date taken to the document info `CreationDate`; drop the rest. +- **Rationale**: Encoder-agnostic and testable: compare EXIF before and after. `image`'s + `set_exif_metadata` support varies by encoder, so post-write injection is more predictable. +- **Alternatives considered**: `little_exif` (full EXIF rewrite, more than needed). `exiftool` + sidecar (Perl, rejected). + +## R12. Color management (FR-014) + +- **Decision**: Targets that can embed ICC (JPG, PNG, WebP, AVIF) keep the source pixels + unchanged and embed the source ICC profile, which is lossless and needs no conversion. Targets + without ICC support (ICO, SVG tracing, PDF pages) are converted to sRGB with `qcms` (pure Rust, + from Firefox). High-bit-depth sources (16-bit PNG/TIFF, 10-bit HEIC) are dithered down to 8-bit + only when the target is 8-bit. HDR gain maps are ignored, and the SDR base image is used. +- **Rationale**: Gives the most faithful result while doing the least work. +- **Alternatives considered**: `lcms2` (C dependency, not needed for the profiles in scope). + Always converting to sRGB (loses Display P3 color on targets that support it). + +## R13. Format detection (FR-002) + +- **Decision**: A small in-house sniffer over the first 4 KB of a file: + - Magic bytes for JPEG, PNG, GIF, TIFF (II*/MM*), WebP (RIFF+WEBP), and PDF (`%PDF-`). + - An ISO-BMFF `ftyp` brand check: `heic`/`heix`/`mif1`/`msf1` → HEIC; `avif`/`avis` → AVIF. + - SVG: an optional BOM, an optional XML prolog or comments, then an `