diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..065e082f --- /dev/null +++ b/.editorconfig @@ -0,0 +1,39 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.{csproj,props,targets,slnx,xml,resx,xaml,json,yml,yaml,svg}] +indent_size = 2 + +[*.{js,css,html}] +indent_size = 2 + +[*.cs] +csharp_style_namespace_declarations = file_scoped:warning +csharp_using_directive_placement = outside_namespace +dotnet_sort_system_directives_first = true +csharp_prefer_braces = when_multiline:suggestion +csharp_style_var_for_built_in_types = true:silent +csharp_style_var_when_type_is_apparent = true:silent +csharp_style_expression_bodied_methods = when_on_single_line:silent +csharp_new_line_before_open_brace = all +dotnet_style_qualification_for_field = false:suggestion +dotnet_naming_rule.private_fields_underscore.symbols = private_fields +dotnet_naming_rule.private_fields_underscore.style = underscore_camel +dotnet_naming_rule.private_fields_underscore.severity = suggestion +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private +dotnet_naming_style.underscore_camel.required_prefix = _ +dotnet_naming_style.underscore_camel.capitalization = camel_case + +# Interop and codec code legitimately uses these patterns. +dotnet_diagnostic.CA1416.severity = warning +dotnet_diagnostic.CA2101.severity = none +dotnet_diagnostic.SYSLIB1054.severity = none +dotnet_diagnostic.CA1401.severity = none diff --git a/.gitignore b/.gitignore index d5a18dee..1732a815 100644 --- a/.gitignore +++ b/.gitignore @@ -427,3 +427,11 @@ FodyWeavers.xsd *.msix *.msm *.msp + +# Titano +tests/fixtures/external/ +/out/ +/publish/ +/artifacts/ +*.junit.xml +TestResults/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..908e146a --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,19 @@ +# Titano — working rules +Read docs/BRIEF.md when in doubt; it wins over these notes. +- Zero . Anything not in the .NET BCL / Microsoft shared frameworks / OS APIs is written here. +- No external processes at runtime (no ffmpeg, exiftool, powershell). Only OS dialogs listed in BRIEF §8.6. +- Titano.Core / Data / Protocol / Server target net10.0 and build on Linux; Windows-only code lives in *.Windows or the desktop apps. +- English identifiers, comments, commits (Conventional Commits). Prototype in docs/reference is Italian: port algorithms, not language. +- Every UI string is a resource (en source, it translation). Labels ≤ 3 words; explanations only in tooltips; every actionable control has a tooltip; no helper paragraphs. +- Destructive operations: dry-run plan first, hash verification, explicit user action. +- When the brief is silent: choose the simplest safe option, log it in docs/DECISIONS.md, continue. Ask only at phase gates or before irreversible choices. +- Definition of Done per phase: green on windows-latest + ubuntu-latest, tests green, no new warnings, DECISIONS + CHANGELOG updated, i18n check green, phase report with "how to try it". +- Build: dotnet build -c Release; tests: dotnet run --project tests/ -- --junit out.xml; tools: dotnet run --project src/Titano.Tools -- . +- Current phase and next steps: see docs/STATUS.md (update at every gate). + +## Repository specifics +- Visual target: docs/ui/DESIGN.md (tokens, controls) and docs/ui/mockups/*.html. Looks: mockup wins; behaviour: brief wins. +- Code conventions and module ownership: docs/ARCHITECTURE.md. +- Localization: keys `Area.Group.Name` in i18n/en/.resx, Italian in i18n/it/.it.resx. C# `Loc.L("Key")`, XAML `{l:Loc Key}`. +- Checks run in CI: `Titano.Tools package-guard`, `i18n check`, `xaml-lint`. +- Linux builds the Windows projects for compile checking (EnableWindowsTargeting); Windows-only tests carry [WindowsOnly]. diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 00000000..5b59ad91 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,40 @@ + + + $(MSBuildThisFileDirectory) + 0.1.0 + $(TitanoVersion) + $([System.Text.RegularExpressions.Regex]::Match($(TitanoVersion), '^\d+\.\d+\.\d+').Value).0 + $(AssemblyVersion) + $(TitanoVersion) + Titano + Titano + © Titano + en + + latest + enable + enable + true + true + latest + false + false + true + true + false + en;it;de;fr;es;pt-BR;pt-PT;nl;pl;cs;sk;hu;ro;sv;da;nb;fi;ru;uk;tr;el;bg;hr;sl;lt;lv;et;ja;zh-Hans;zh-Hant;ko;ar;he;hi;id;ms;vi;th + + + true + + false + true + true + false + embedded + + + + true + + diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 00000000..60f0cca3 --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,42 @@ + + + + + + + + + + i18n\%(Filename)%(Extension) + + + + + + $(RepoRoot)artifacts/icons/ + + + $(TitanoIconDir)$(TitanoIconVariant).ico + + + + + + + + + + + diff --git a/Titano.slnx b/Titano.slnx new file mode 100644 index 00000000..4ba03d78 --- /dev/null +++ b/Titano.slnx @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/branding/titano-mono.svg b/branding/titano-mono.svg new file mode 100644 index 00000000..58642c70 --- /dev/null +++ b/branding/titano-mono.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/branding/titano-server.svg b/branding/titano-server.svg new file mode 100644 index 00000000..7cd565b2 --- /dev/null +++ b/branding/titano-server.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/branding/titano-uploader.svg b/branding/titano-uploader.svg new file mode 100644 index 00000000..31fd2675 --- /dev/null +++ b/branding/titano-uploader.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/branding/titano.svg b/branding/titano.svg new file mode 100644 index 00000000..fb2f35ed --- /dev/null +++ b/branding/titano.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 00000000..351f5587 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,88 @@ +# Titano — Architecture and code conventions + +Companion to `docs/BRIEF.md` (scope, behaviour) and `docs/ui/DESIGN.md` (looks). This file says +*where code goes* and *how it is written*. + +## 1. Projects + +| Project | TFM | Purpose | +|---|---|---| +| `src/Titano.Core` | net10.0 | Engine shared by every program: metadata, codecs, imaging, analysis, motion, render, video containers, archive model, naming, import planning, localization runtime, brand mark | +| `src/Titano.Core.Windows` | net10.0-windows | WIC decoder, Media Foundation encoder, DXGI, device APIs, shell helpers (P/Invoke/COM only) | +| `src/Titano.Data` | net10.0 | `IDatabase`, SQLite binding (winsqlite3 on Windows, system libsqlite3 elsewhere for tests/dev), PostgreSQL wire client, migrations, repositories | +| `src/Titano.Protocol` | net10.0 | API DTOs, source-generated JSON contexts, upload/sync/event schemas | +| `src/Titano.Server` | net10.0 (Web SDK) | ASP.NET Core minimal API, auth, jobs, storage, admin web panel (embedded) | +| `src/Titano.Ui` | net10.0-windows (WPF) | Theme (DESIGN tokens), icons, custom controls, `Loc` markup extension, MVVM helpers | +| `src/Titano.App` | WPF exe `Titano.exe` | Desktop client | +| `src/Titano.Uploader` | WPF exe | Uploader | +| `src/Titano.Setup` | WPF exe | Installer/uninstaller | +| `src/Titano.Tools` | net10.0 exe | CLI: make-icon, i18n, xaml-lint, package-guard, selftest, diagnose, fixtures, changelog | +| `tests/Titano.Testing` | net10.0 | In-house test framework (`[Test]`, `[Theory]`+`[Case]`, `Assert`, `TestContext`) | +| `tests/Titano.*.Tests` | exe | One test program per area; `dotnet run --project tests/X -- --junit out.xml` | + +## 2. Namespaces in Titano.Core + +| Folder / namespace | Content | +|---|---| +| `Imaging` | `ImageBuffer` (planar float, linear light), `ImageFileFormat`, `IImageDecoderProvider`, `ImageDecoder`, colour/geometry helpers, `FrameWindow` | +| `Metadata` (+ `Metadata.Tiff`, `Metadata.Bmff`, …) | Signature sniffing, TIFF/IFD (`TiffReader`), Exif/GPS/XMP/MakerNotes, ISO-BMFF, RIFF, RAF, PNG chunks, `MetadataReader`, `ExifWriter` | +| `Codecs` (`Codecs.Jpeg`, `Codecs.Png`, `Codecs.Tiff`, `Codecs.Dng`, `Codecs.Gif`, `Codecs.Ico`) | Pure managed image codecs | +| `Video` | `Mp4Muxer`, box writer, Annex-B/OBU parsing, MP4 inspector, AVI-MJPEG writer, managed encoder provider, encoder contracts | +| `Analysis` | Luminance statistics, deflicker, regions, holy grail, white balance, colour temperature, light/deep analysis | +| `Motion` | FFT, phase correlation, pyramids, optical flow, motion blur, stabilisation, virtual camera, interpolation, stacking | +| `Math` | Splines (Fritsch–Carlson, Catmull-Rom, Bézier), robust local regression, statistics, solar position | +| `Render` | Render plan, pipeline, export presets | +| `Advisor` | Recommendation rules with localisable reasons, sequence presets | +| `Archive` | Archive layout, sidecars (`sequence.json`, `project.json`), scanner, rebuild, verify, duplicates, orphans, adopt | +| `Naming` | Folder/file templates and tokens | +| `Import` | Card/folder scan, session detection, import plan, hash-verified copy | +| `Model` | Domain entities (§5) shared by Data, Server and clients | +| `Localization`, `Diagnostics`, `IO`, `Hashing`, `Branding` | Infrastructure | + +## 3. Conventions + +- File-scoped namespaces, `sealed` by default, nullable on, warnings are errors. No `#pragma warning disable` + except narrowly around interop with a reason. +- No third-party packages, ever. If the BCL lacks it (CRC-32, Adler, JPEG, PNG decode…), write it. +- Parsers never throw on malformed input: they return partial results plus warnings. Every offset is + bounds-checked against the stream length; recursion and loops are capped. +- Never load a whole RAW to read metadata: windowed reads through `Stream` + `Seek`. +- Hot loops: `Span`, `System.Numerics.Vector`/`Vector256` where it measurably pays, no LINQ. + Parallelise per row/tile with `Parallel.For` only when work per item is large. +- Pixel math in linear light, `float`, Rec.709 primaries. Convert to sRGB/8-bit only at the edges. +- Every long operation takes a `CancellationToken` and reports progress through `IProgress`. +- Libraries use `ConfigureAwait(false)`. No `async void` except WPF event handlers. +- Logging through `Titano.Core.Diagnostics.Log` in Core; `ILogger` on the server. +- Public types and non-obvious members get a one-line `///` summary. Comments explain *why*, not *what*. +- Disk writes that must survive crashes use `AtomicFile` (temp → fsync → rename). +- IDs are UUIDv7 (`Guid.CreateVersion7()`); timestamps UTC; capture times are camera wall-clock with an + optional offset. + +## 4. Tests + +- Framework: `Titano.Testing`. Test classes are `public sealed`; constructor may take `TestContext` + (temp directories, cancellation, log). Use `[WindowsOnly]` for OS-specific tests and + `[RequiresEnvironment("TITANO_TEST_PG")]` for PostgreSQL integration tests. +- Put tests under `tests/Titano..Tests//Tests.cs`, mirroring the source folder. +- Fixtures are synthetic and generated in code wherever possible; tiny binary fixtures may go in + `tests/fixtures/` (< 50 KB each). Larger CC0 samples are fetched by `Titano.Tools fixtures` into + `tests/fixtures/external/` (git-ignored) and tests depending on them skip when absent. +- Fuzz tests: truncate and corrupt valid inputs at many offsets; assert no exception escapes. + +## 5. Localization + +- Keys: `Area.Group.Name`; area = file name. Areas: Common, Shell, Library, Editor, Import, Archive, + Jobs, Server, Settings, Tooltips, Errors, Advisor, Admin, Uploader, Setup. +- `en` is the source (`i18n/en/.resx`), `it` is mandatory (`i18n/it/.it.resx`). +- Labels ≤ 30 chars, tooltips/errors/advisor reasons ≤ 200 chars (one or two sentences). +- Plurals: `Key.one` / `Key.few` / `Key.many` / `Key.other`, resolved by `Loc.Plural("Key", n)`. + +## 6. Build and checks + +``` +dotnet build Titano.slnx -c Release +dotnet run --project tests/Titano.Core.Tests -c Release -- --junit out/core.xml +dotnet run --project src/Titano.Tools -- package-guard +dotnet run --project src/Titano.Tools -- i18n check +dotnet run --project src/Titano.Tools -- xaml-lint +``` diff --git a/docs/BRIEF.md b/docs/BRIEF.md new file mode 100644 index 00000000..6a5f2d75 --- /dev/null +++ b/docs/BRIEF.md @@ -0,0 +1,1346 @@ +# Titano — Build Brief for Claude Code + +> This document is the complete specification and standing instruction set for building the +> Titano time-lapse ecosystem from scratch. It is written to be read by Claude Code at the +> start of every session (via `CLAUDE.md`, see Appendix A) and to be the single source of +> truth for scope, architecture, constraints and delivery order. +> +> Working name: **Titano**. Three shipped programs — **Titano** (Windows desktop client), +> **Titano Server** (Linux/Docker and Windows), **Titano Uploader** (Windows) — sharing one +> engine. Target audience: photographers, astro/landscape shooters, construction and +> weather-cam operators, hobbyists worldwide. + +--- + +## 0. How to work on this project (operating rules for Claude Code) + +### 0.1 Kickoff message + +Paste this as the first message in Claude Code, from an empty repository that contains only +this file at `docs/BRIEF.md` and the prototype dump at `docs/reference/titano-prototype.md`: + +``` +Read docs/BRIEF.md completely before doing anything. It is the full specification for this +repository and it overrides your defaults. Then: +1. Create CLAUDE.md from Appendix A of the brief, and docs/DECISIONS.md, docs/CHANGELOG.md. +2. Execute Phase 0 exactly as described in §22, stopping at its phase gate. +At every phase gate, report: what was built, how to run it, test results on Windows and +Linux, open decisions. Do not ask questions before the gate unless a decision is +irreversible; otherwise decide, record it in docs/DECISIONS.md, and continue. +``` + +### 0.2 Standing rules + +1. **Zero third-party packages, everywhere.** No `` in any `.csproj`, + including tests, tools and build scripts. Anything that is not the .NET BCL, a Microsoft + shared framework that ships with the .NET SDK/runtime (`Microsoft.NETCore.App`, + `Microsoft.AspNetCore.App`, `Microsoft.WindowsDesktop.App`, the Windows SDK targeting + pack), or an operating-system API reached by P/Invoke or COM interop, is implemented + in-house. CI fails the build if a `PackageReference` appears (§19.2). The prototype in + `docs/reference/titano-prototype.md` proves this is workable: it decodes images with WIC, + encodes video with Media Foundation, parses EXIF/TIFF/XMP with its own parsers, and + writes its own MP4 container. +2. **No external processes.** No FFmpeg, no ExifTool, no ImageMagick, no PowerShell + scripts at runtime. The only OS executables/dialogs the product may invoke are listed in + §8.6 (format-volume dialog, shell "open with", browser launch for links). +3. **Cross-platform core, Windows-only presentation.** `Titano.Core`, `Titano.Data`, + `Titano.Protocol` and `Titano.Server` target `net10.0` and must build and pass tests on + Linux. Windows-only code lives in `*.Windows` projects or the desktop apps. +4. **English everywhere in the codebase**: identifiers, comments, commit messages, docs. + The prototype is written in Italian; port the algorithms, not the language. +5. **Every user-visible string is a resource.** No literal UI text in code or XAML. + English is the source language; Italian is the first translation; all other languages + follow in Phase 8 (§16). +6. **UI copy rules (mandatory):** labels ≤ 3 words when possible; no helper text or + paragraphs anywhere in the UI; explanations live only in tooltips (≤ 2 sentences); + every actionable control has a tooltip; empty states are one sentence plus one button; + errors are one sentence saying what happened plus one action. +7. **Decide, record, continue.** When the brief is silent, choose the option that is + simplest, safest for user data, and consistent with the constraints; write one line in + `docs/DECISIONS.md` (date, decision, alternative, reason). Ask the human only at phase + gates, or before any irreversible or data-destroying design choice. +8. **User data is sacred.** Never delete, move or format anything without (a) a verified + hash match of every copied file and (b) an explicit user action. Every destructive + operation is dry-run-able and shows its plan first. +9. **Definition of Done for every phase:** builds green on `windows-latest` and + `ubuntu-latest`; all tests green; no new warnings; `docs/DECISIONS.md` and + `docs/CHANGELOG.md` updated; a short "how to try it" note in the phase report; + localization completeness check passes for `en` and `it`. +10. **Commit style:** Conventional Commits (`feat(core): …`, `fix(server): …`), small + commits, one concern each. Never commit generated binaries, fixtures downloaded by + scripts, or secrets. +11. **Reference prototype:** `docs/reference/titano-prototype.md` is a Repomix dump of the + previous single-program prototype (C#/.NET 10, WinForms, zero packages). Its engine + (metadata parsing, deflicker, holy-grail transitions, optical flow, motion blur, + stabilization, virtual camera, time remap, stacking, Media Foundation encoding, MP4 + muxing, self-tests) was validated on real material. Port those algorithms faithfully + into the new structure, with English names and unit tests; do not copy its UI + (WinForms) or its file layout. Search it with grep; do not try to read it whole. + +--- + +## 1. Product vision + +Titano turns folders of photos (RAW, JPEG, HEIC…) into finished time-lapse videos and keeps +a lifetime archive of shoots organised, verified and searchable — on one PC or on a shared +server. + +- **Import** memory cards with per-card rules, session detection, renaming and hash + verification; import directly into a local archive or straight to a server. +- **Analyse** every sequence deeply (metadata + pixels) and let the advisor set frame + timing, motion blur, deflicker, transitions and export presets — with a reason for every + choice, visible in a tooltip. +- **Render** with the in-house engine and GPU encoders (H.264/HEVC/AV1 via Media + Foundation) to purpose-built presets, from 720p previews to 8K 10-bit archives. +- **Archive** hundreds of thousands of photos across years and cameras, on local or network + drives, with an index that can always be rebuilt from the files themselves. +- **Share** through Titano Server: central archive, users with logins, uploads from the + tiny Uploader, sync of projects, server-side jobs, render delegation to GPU-equipped + clients, and a web admin panel — deployable as a Docker container (Unraid template + included) or on Windows. + +### 1.1 Goals (measurable) + +- A first-time user imports a card, gets a recommended preset, and renders a 1080p preview + in under five interactions from launch. +- A library of 500,000 photos in 2,000 sequences: Library screen opens in < 1 s, scrolls at + 60 fps, filters respond in < 200 ms, full index rebuild from sidecars in < 10 min. +- Rendering quality equals or exceeds the prototype's measured results (§20.4 regression + thresholds), with hardware encoding used whenever a hardware MFT exists. +- Every feature reachable without reading any documentation; every control explained by + its tooltip; UI available in ≥ 30 languages with RTL support. +- Server: 10 concurrent clients uploading at line speed; resumable uploads; zero data loss + on crash (append-only ingest + manifest commit). + +### 1.2 Non-goals (v1) + +- Audio tracks (P2: mux an external AAC file), HDR/PQ output, colour-managed display. +- macOS/Linux desktop clients (server only), mobile apps, browser-based editing. +- Cloud object storage backends (S3 etc.), multi-server federation. +- General RAW *development* beyond what the render pipeline needs (no Lightroom clone). +- GPU compute for image processing (CPU SIMD only in v1; keep interfaces open). +- Real-time tethered capture, camera control. +- Plugin system. + +--- + +## 2. Hard constraints and allowed native surface + +### 2.1 Language and platform decision + +**C# on .NET 10 LTS** for every component. Reasons: one toolchain for a cross-platform +server and a first-class Windows desktop; WPF and ASP.NET Core ship with the SDK (no +packages); mature BCL for crypto, HTTP/2, WebSockets, JSON, compression and SIMD +(`System.Numerics.Vector`, `Vector256`); direct P/Invoke/COM interop to WIC, Media +Foundation and `winsqlite3.dll`; the validated engine is already C#. Alternatives were +rejected: Python (stdlib GUI is dated, no GPU encode, no PostgreSQL driver), C++ (UI and +server cost), Rust/Go (no standard GUI, no SQLite/PostgreSQL in std), Java (JavaFX is +external). + +Desktop UI: **WPF** with the built-in Fluent theme (`Application.ThemeMode`, available in +WPF since .NET 9, refined in .NET 10) for a Windows 11 look with dark/light/system modes and +system accent colour, plus in-house custom `FrameworkElement`s for charts, filmstrip, +curve editors and the virtualized photo grid. If the Fluent theme proves inadequate for any +control, restyle it with an in-house `ResourceDictionary` — never a package. Window chrome: +`WindowChrome` + `DwmSetWindowAttribute` (dark title bar, Mica/backdrop where available). + +### 2.2 Allowed native/OS surface (Windows) + +| Need | API (all OS components, no packages) | +|---|---| +| Image decoding incl. RAW/HEIC/WebP/AVIF when codecs installed | WIC (`IWICImagingFactory`… via COM interop) | +| Video encoding, hardware MFTs (NVENC/QSV/AMF) | Media Foundation (`MFStartup`, `MFTEnumEx`, `IMFTransform`, `ICodecAPI`) | +| Local database | `winsqlite3.dll` (ships with Windows 10 1709+ / Windows 11) via P/Invoke | +| Volume identity, device arrival | `GetVolumeInformationW`, `GetDriveTypeW`, `WM_DEVICECHANGE`, `SetupAPI` if needed | +| Format a card | `SHFormatDrive` (OS format dialog) | +| GPU name/VRAM for encoder capability display | DXGI (`CreateDXGIFactory1`, `IDXGIAdapter::GetDesc`) | +| Taskbar progress, toasts | `ITaskbarList3`; toasts via Windows SDK projection (`net10.0-windows10.0.19041.0` targeting pack) or in-house tray balloon | +| MTP cameras (P2) | Windows Portable Devices (COM) | +| Window chrome | `dwmapi.dll` | + +Linux (server): BCL only. No `libsqlite3`, no `libva`, no FFmpeg. PostgreSQL is reached +through the in-house wire-protocol client (§6.3). + +### 2.3 What this implies (and how the brief resolves it) + +- **RAW decoding** without libraw is tiered (§8.2): full in-house decode for DNG/TIFF/ + JPEG/PNG and a growing set of native RAW formats; embedded full-size JPEG previews as a + universal fallback (every major RAW format embeds one); on Windows, WIC with the free + Microsoft "Raw Image Extension" gives full decode of everything else. +- **Video encoding** on Linux has no OS encoder API; the server produces pure-managed + outputs (MJPEG-AVI, image sequences, GIF, APNG) itself and delegates MP4/H.264/HEVC/AV1 + jobs to **render nodes** — Titano clients that volunteer their GPU (§14.7). An in-house + intra-only H.264 encoder is a P2 universal fallback (§11.6). +- **Testing** uses an in-house runner (`Titano.Testing`, §20.1), not xUnit/NUnit. +- **HEIC/HEIF** cannot be decoded in-house (HEVC intra decoder is out of scope): Windows + clients decode via WIC (HEIF + HEVC extensions); the server stores originals and relies on + proxies produced by a Windows client or render node. + +--- + +## 3. Repository layout + +``` +titano/ (private GitHub repo) +├── CLAUDE.md operating rules (Appendix A) +├── Directory.Build.props version, LangVersion, nullable, warnings-as-errors, analyzers +├── Directory.Build.targets zero-package guard, resource generation hooks +├── Titano.slnx +├── global.json pins .NET 10 SDK +├── src/ +│ ├── Titano.Core/ net10.0 — engine: Metadata, Imaging, Codecs, Analysis, Motion, Video (container/muxers), Archive model, Naming, Localization runtime +│ ├── Titano.Core.Windows/ net10.0-windows — WIC decoder, Media Foundation encoder, DXGI, device APIs, winsqlite3 binding +│ ├── Titano.Data/ net10.0 — IDatabase abstraction, SQL dialects, migrations, repositories, Postgres wire client (Titano.Data.Postgres), SQLite driver surface (implemented by Core.Windows binding) +│ ├── Titano.Protocol/ net10.0 — API DTOs, JSON contexts (source-generated), chunked upload protocol, sync manifests, WebSocket event schema, version negotiation +│ ├── Titano.Server/ net10.0 — ASP.NET Core minimal API, auth, job engine, storage service, admin web UI (embedded static files), Docker entrypoint +│ ├── Titano.App/ net10.0-windows — WPF desktop client +│ ├── Titano.Uploader/ net10.0-windows — WPF uploader (tray-capable) +│ ├── Titano.Setup/ net10.0-windows — in-house installer/uninstaller (self-extracting, Add/Remove Programs, shortcuts, file associations) +│ └── Titano.Tools/ net10.0 — CLI: selftest, diagnose, make-icon, i18n export/check, fixtures fetch, changelog +├── tests/ +│ ├── Titano.Testing/ in-house test framework + runner (attributes, asserts, fixtures, JUnit XML) +│ ├── Titano.Core.Tests/ +│ ├── Titano.Data.Tests/ includes PostgreSQL integration tests (skipped without TITANO_TEST_PG) +│ ├── Titano.Server.Tests/ in-process Kestrel on a random port +│ ├── Titano.App.Tests/ view-model tests + XAML lint (tooltip/resource rules) + screenshot smoke (`--capture`) +│ └── fixtures/ tiny checked-in samples; larger CC0 RAW samples fetched by `Titano.Tools fixtures` +├── branding/ icon sources (SVG), generated ICO/PNG sets +├── i18n/ .resx sources (en) + translations, glossary, machine-translation notes +├── deploy/ +│ ├── docker/Dockerfile, docker-compose.yml, entrypoint +│ └── unraid/titano.xml +├── .github/workflows/ ci.yml, release.yml, docker.yml +└── docs/ BRIEF.md (this), DECISIONS.md, CHANGELOG.md, ARCHITECTURE.md (generated per phase), reference/titano-prototype.md +``` + +Project references: `App` → `Core`, `Core.Windows`, `Data`, `Protocol`. `Server` → `Core`, +`Data`, `Protocol`. `Uploader` → `Core` (hashing, metadata light), `Protocol`. `Core` and +`Data` never reference anything Windows-specific; CI builds them on Linux. + +--- + +## 4. Architecture + +### 4.1 Component diagram + +``` + ┌────────────────────────────────────────────────────────────────┐ + │ Titano (WPF client) │ + │ Library · Sequence editor · Import · Archive manager · Jobs │ + │ Local mode: SQLite + local/network archive │ + │ Server mode: REST/WS client, proxies cache, render node │ + └───────┬───────────────────────────────────────┬────────────────┘ + │ HTTPS REST + WebSocket │ Memory cards (USB/SD) + ▼ ▼ +┌───────────────────────────────────┐ ┌──────────────────────────┐ +│ Titano Server │ │ Titano Uploader (WPF) │ +│ Kestrel · API v1 · Auth · Jobs │◄───────────│ queue · watch folders │ +│ Storage service · Admin web panel │ HTTPS │ resumable chunk upload │ +│ Pure-managed encoders │ └──────────────────────────┘ +└──────┬──────────────────┬─────────┘ + │ │ + ▼ ▼ + PostgreSQL (Docker) Archive volume (/archive: originals, sidecars, proxies, renders) + or SQLite (Windows) +``` + +### 4.2 Shared engine + +`Titano.Core` is the same assembly on client and server: metadata parsing, image codecs, +analysis advisor, render pipeline, container writers. Only the *decoder/encoder providers* +differ per platform, behind two interfaces: + +```csharp +public interface IImageDecoderProvider { bool CanDecode(ImageFormatInfo f); DecodedImage Decode(DecodeRequest r); } +public interface IVideoEncoderProvider { IReadOnlyList Capabilities { get; } IVideoEncoderSession Open(EncodeSettings s); } +``` + +Registered providers, in priority order: client → `WicDecoderProvider`, then +`ManagedDecoderProvider`; server → `ManagedDecoderProvider` only. Encoders: client → +`MediaFoundationEncoderProvider` (hardware first, software H.264 fallback), then +`ManagedEncoderProvider` (MJPEG/AVI, sequences, GIF, APNG); server → managed only, plus +delegation to render nodes. + +### 4.3 Data flow: card → archive → render + +``` +Card ──scan(light metadata)──► Import plan (sessions, names) ──copy+hash──► originals/ + ──light analysis──► sequence.json sidecar + DB rows ──queue──► deep analysis job + ──► proxies + thumbs ──► advisor recommendations + suggested presets +User opens sequence ──► settings (project JSON) ──render──► exports/ + DB render row +``` + +Frames are streamed to the server by the client or uploader through chunked, resumable, +hash-verified uploads; the server commits the frame into the archive layout and updates the +sequence manifest atomically (write temp → fsync → rename). + +### 4.4 Modes of the client + +| Mode | Storage | Index | Who renders | +|---|---|---|---| +| Local | local or network drive archive | SQLite | this PC | +| Server-connected | server archive; local proxies/thumbs cache | server DB via API; local SQLite caches only | server (managed formats), render nodes (MP4), or this PC after downloading originals | +| Mixed | both; each sequence has an `origin` and a `sync state` | both | as above | + +--- + +## 5. Domain model + +Primary entities (identical concepts in SQLite and PostgreSQL; ids are UUIDv7 stored as +`TEXT`/`uuid`; timestamps UTC ISO-8601/`timestamptz`): + +- **Archive** — id, name, root path, layout templates, schema version, created, proxy policy. +- **Sequence** — id, archive id, title, folder (relative), camera make/model/serial, lens, + first/last capture, frame count, median interval, total bytes, status flags + (`analyzed_light`, `analyzed_deep`, `proxies_built`, `thumbs_built`, `rendered_count`, + `verified_at`), hero frame id, tags, rating, notes (short), settings JSON (project), + analysis report JSON (compact) + path to full report, origin (local/server), sync state, + version counters (`settings_version`, `frames_version`), owner user id (server). +- **Frame** — id, sequence id, index, relative path, file name, size, sha256, captured at + (with sub-second and source: EXIF/XMP/filesystem), exposure time, f-number, ISO, focal + length, exposure bias, white balance, orientation, width, height, format, embedded + preview info (offset/length), light stats (mean log-luminance, clip fractions) once + analysed, flags (missing, corrupt, duplicate, excluded). +- **Render** — id, sequence id, preset name, settings JSON, output relative path, codec, + width, height, fps, duration, bytes, created, produced by (client id / server / node). +- **Job** — id, kind (scan, rebuild, verify, light-analyse, deep-analyse, proxies, + thumbs, render, import, upload-commit, maintenance), target ids, state (queued, running, + paused, done, failed, cancelled), progress (done/total, fps, eta), log tail, created by, + node id, attempts, error. +- **MediaCard** (client) — id, volume serial, filesystem label, capacity, nickname, camera + identity (Make/Model/BodySerial from first file), profile JSON, first/last seen, import + history (job ids). +- **User** (server) — id, username, display name, password hash (PBKDF2), role (admin, + editor, uploader, viewer), permissions bitmask, quota bytes, used bytes, disabled, + must-change-password, created, last login. +- **Session/Token** (server) — token hash, user id, client name, created, expires, last + used, revoked. +- **RenderNode** (server) — id, user id, client name, capabilities JSON (codecs, hardware + encoder names, max resolution), last heartbeat, state. +- **Setting** — key/value (typed JSON), scope (app, archive, user). +- **Tag**, **SequenceTag** — normalised for filtering. +- **AuditLog** (server) — who did what to which sequence/user, when. + +Indexes: `frame(sequence_id, index)`, `frame(sha256)`, `frame(captured_at)`, +`sequence(archive_id, first_capture)`, `sequence(camera_model)`, tags, jobs by state. +Paging everywhere (keyset pagination on `(first_capture, id)`). + +--- + +## 6. Data layer + +### 6.1 `Titano.Data` abstraction + +```csharp +public interface IDatabase : IAsyncDisposable { + Dialect Dialect { get; } // Sqlite | Postgres + Task OpenAsync(CancellationToken ct); // connection from pool +} +public interface IDbSession : IAsyncDisposable { + Task ExecuteAsync(string sql, params DbParam[] p); + IAsyncEnumerable QueryAsync(string sql, params DbParam[] p); + Task BeginAsync(); + Task BulkInsertAsync(string table, IReadOnlyList columns, IAsyncEnumerable rows); // COPY on PG, multi-row INSERT on SQLite +} +``` + +Hand-written SQL in repositories (`SequenceRepository`, `FrameRepository`, …); no ORM. +Migrations: numbered `.sql` files per dialect in `Titano.Data/Migrations/{sqlite,postgres}/`, +applied at startup inside a transaction, recorded in `schema_migrations`. Dialect +differences (types, `RETURNING`, upserts) are confined to SQL files and a small `SqlDialect` +helper. + +### 6.2 SQLite (client, and Windows standalone server) + +- Binding: `Titano.Core.Windows/Sqlite/WinSqlite3.cs` P/Invoke to `winsqlite3.dll` + (`sqlite3_open_v2`, `prepare_v2`, `step`, `reset`, `finalize`, `bind_*`, `column_*`, + `exec`, `errmsg`, `last_insert_rowid`, `changes`, `busy_timeout`, `libversion`, + `extended_result_codes`). UTF-8 marshalling by hand. Check `sqlite3_libversion() ≥ 3.31` + at startup; probe `PRAGMA compile_options` and never depend on FTS/JSON extensions. +- Pragmas: `journal_mode=WAL`, `synchronous=NORMAL`, `foreign_keys=ON`, + `temp_store=MEMORY`, `cache_size=-65536`, `mmap_size=268435456`. +- Location: `%LOCALAPPDATA%\Titano\titano.db` (never Documents/OneDrive-synced folders — + SQLite in a synced folder corrupts). Portable mode: `portable.txt` next to the exe puts + everything under `.\data\`. +- Backups: `VACUUM INTO` nightly copy kept ×3; restore from Settings › Advanced. + +### 6.3 PostgreSQL client (`Titano.Data.Postgres`) — in-house wire protocol v3 + +- TCP + optional TLS via `SslStream` after `SSLRequest`; `sslmode` = disable | prefer | + require | verify-full. +- Startup (`user`, `database`, `application_name=titano-server`, `client_encoding=UTF8`, + `TimeZone=UTC`); authentication: SCRAM-SHA-256 (`Rfc2898DeriveBytes.Pbkdf2`, HMAC-SHA256, + channel binding not required), MD5, cleartext, trust. +- Simple query, extended query (Parse/Bind/Describe/Execute/Sync) with parameters in text + format except `bytea` (binary), prepared-statement cache per connection, transactions, + `COPY … FROM STDIN` for bulk inserts, `LISTEN/NOTIFY` (used for multi-instance job + wake-ups, optional), cancellation via `CancelRequest`. +- Type mapping: `text, varchar, int4, int8, float8, bool, bytea, timestamptz, uuid, jsonb, + numeric(as string)`; arrays not needed. +- Connection pool (min/max, health check `SELECT 1`, idle eviction), typed + `PostgresException` carrying SQLSTATE, retry on transient errors (57P01, 08xxx). +- Test suite runs against PostgreSQL 16 and 17 service containers in CI (§19). + +--- + +## 7. Archive format on disk + +The archive is the source of truth; the database is an index that can be rebuilt from it. + +``` +/ +├── .titano/ +│ ├── archive.json { id, name, schemaVersion, created, layoutTemplates, proxyPolicy } +│ ├── index-snapshot.bin optional accelerator for rebuild (all sidecars concatenated + hash); ignored if stale +│ └── locks/ lease files for concurrent writers (server + client on same share) +├── 2026/ +│ └── 2026-09-28 Canon EOS R5 - Harbour sunset/ folder = expanded FolderTemplate +│ ├── originals/ IMG_0001.CR2 … names = expanded FileTemplate +│ ├── proxies/ 0001.jpg … (JPEG, long edge per policy; optional, regenerable) +│ ├── exports/ 2026-09-28 Harbour sunset - 4K HEVC.mp4 … +│ └── .titano/ +│ ├── sequence.json sidecar manifest (below) +│ ├── analysis.json full deep-analysis report +│ ├── project.json render settings (the "project") +│ └── thumbs.pack packed thumbnails (one file per sequence, indexed; avoids 100k tiny files on SMB) +``` + +`sequence.json` (canonical, versioned, written atomically): +`{ id, title, camera, lens, frames: [{ i, file, size, sha256, capturedAt, exposure, fNumber, +iso, focal, bias, wb, orientation, w, h, format, previewOffset, previewLength, flags }], +tags, rating, notes, status, versions, createdBy, updatedAt }`. + +Rules: originals are immutable (never rewritten; edits are settings); every write of a +sidecar goes to a temp file, `fsync`, rename; the folder name is derived from templates at +import time and never auto-renamed afterwards (renaming is a user mass-operation that +updates sidecars and DB together). Network drives: UNC or mapped paths; long-path aware +(`\\?\` prefix); no `FileSystemWatcher` reliance — periodic polling by mtime/size plus manual +rescan; offline detection with graceful read-only state. + +### 7.1 Naming templates + +`FolderTemplate` default `{year}/{date} {camera}`; `FileTemplate` default +`{date}_{time}_{n:0000}`. Tokens (localised descriptions in resources): `year, month, day, +date, time, hm, session, sessionstart, camera, lens, iso, shutter, aperture, n, nsession, +name, ext, title`. `{token:format}` passes the format to the .NET formatter. Illegal +characters are replaced, never passed through; templates are validated live in the UI with a +preview of the first three names. + +--- + +## 8. Image pipeline + +### 8.1 Supported input formats + +| Family | Extensions | Metadata (in-house) | Pixels on Windows | Pixels on server (Linux) | +|---|---|---|---|---| +| JPEG | jpg jpeg jpe jfif | APP1 Exif/XMP, MPF | WIC or managed | managed (baseline + progressive) | +| PNG | png | eXIf, iTXt XMP | WIC or managed | managed | +| TIFF | tif tiff | IFDs | WIC or managed | managed (strips/tiles; none/PackBits/LZW/Deflate/JPEG) | +| DNG (smartphones: Apple ProRAW, Android, Samsung; DJI; Insta360; Leica; Pentax; Ricoh) | dng | IFDs, MakerNote | WIC (if Raw ext.) or managed full decode | managed full decode | +| Canon | cr2 cr3 | cr2: TIFF; cr3: ISO-BMFF `CMT1..4` | WIC (Raw ext.) → managed CR2 (P1) → embedded preview | managed CR2 (P1) → embedded full-size JPEG (CR3 track 1) | +| Nikon | nef nrw | TIFF | WIC → managed NEF (P1) → preview | managed NEF (P1) → preview | +| Sony | arw srf sr2 | TIFF | WIC → managed ARW (P1) → preview | idem | +| Fujifilm | raf | RAF header + TIFF | WIC → managed RAF uncompressed (P1) → preview | idem | +| Olympus/OM, Panasonic, Pentax, Samsung, Hasselblad, Phase One, Leica | orf rw2 raw pef srw 3fr fff iiq rwl | TIFF-like | WIC → managed (P1/P2) → preview | preview (P1: managed decoders as feasible) | +| GoPro | gpr (DNG+VC-5) + jpg sidecar | IFDs | preview/sidecar JPEG; VC-5 out of scope | sidecar JPEG | +| HEIF/HEIC/AVIF (iPhone, Samsung, DJI) | heic heif hif avif | ISO-BMFF `Exif` item | WIC (HEIF + HEVC/AV1 extensions) | metadata only; pixels via client-made proxies | +| WebP | webp | RIFF `EXIF` chunk | WIC (WebP ext.) | metadata only (P2: managed VP8L) | +| JPEG XL, JPEG XR, BMP, GIF (single frame) | jxl jxr bmp gif | minimal | WIC if a codec exists | not supported | + +Windows codec availability is enumerated at startup (`IWICImagingFactory:: +CreateComponentEnumerator`). Missing codecs are surfaced as a one-line notice with an +"Install" button opening the Microsoft Store page (Raw Image Extension, HEIF Image +Extension, HEVC Video Extensions, AV1 Video Extension, WebP Image Extension; verify product +IDs at implementation time). The format table in Settings › Formats shows, per format, +which tier will be used on this machine. + +### 8.2 Decode tiers (deterministic, logged per frame) + +1. **Native full decode** (in-house or WIC) at working resolution, 16-bit linear light. +2. **Embedded preview** (largest JPEG found: TIFF `JPEGInterchangeFormat`/SubIFD strips, + RAF preview, CR3 full-size JPEG track, MPF). Marked `PreviewOnly` on the frame; the + sequence shows a chip with the count and the advisor caps output resolution to the + preview size unless the user overrides. +3. **Unavailable** → frame flagged `Undecodable`; excluded from render; listed in the + sequence warnings. + +The in-house DNG pipeline (server and client): CFA/linear DNG, `Compression` 1/7 (lossless +JPEG SOF3)/8 (Deflate)/34892 (lossy JPEG), `LinearizationTable`, `BlackLevel` (+ repeat +dims, delta), `WhiteLevel`, `AsShotNeutral`/`AsShotWhiteXY`, `ColorMatrix1/2` + +`CameraCalibration`, `AnalogBalance`, Bradford adaptation to D65, demosaic **AHD** (default, +"perfect result" priority) with bilinear for Draft quality, highlight reconstruction (clip ++ desaturate), `ActiveArea`/`DefaultCrop*`, `Opcode` lists 1–3 (at least `GainMap`, +`WarpRectilinear`, `FixVignetteRadial`; unknown opcodes ignored with a warning), +`BaselineExposure`. Output: linear Rec.709/sRGB primaries float planes. + +### 8.3 Managed codecs (all in `Titano.Core/Codecs`, pure C#, SIMD where it pays) + +- `JpegDecoder` (baseline, progressive, restart intervals, 4:4:4/4:2:2/4:2:0/4:1:1/gray, + 12-bit optional, ICC ignored), `JpegEncoder` (baseline, quality 1–100, subsampling + choice, optimised Huffman tables optional, Exif/XMP APP1 embedding). +- `PngDecoder`/`PngEncoder` (all colour types, 8/16-bit, Adam7 decode, filters, zlib via + `System.IO.Compression.ZLibStream`). +- `TiffReader`/`TiffWriter` (as prototype: 16-bit TIFF, linear DNG writer with + `PhotometricInterpretation=34892`). +- `GifEncoder` (animated; median-cut palette + Floyd–Steinberg; frame differencing). +- `ApngEncoder`. +- `AviMjpegWriter` (RIFF AVI with `MJPG`, OpenDML index for > 2 GB). +- `Mp4Muxer` (port of prototype: streaming `ftyp`/`mdat`/`moov`, 90 kHz timescale, + variable durations, `avcC`/`hvcC`; add `av1C` + OBU handling in P1), `AnnexBParser`. +- `Bmff` reader (HEIF/CR3/AVIF boxes), `Riff` reader (WebP/AVI), `Raf` reader. + +### 8.4 Image buffers + +Port the prototype's `ImageBuffer`/`FrameBufferPool` (pooled float planes, linear light), +`FrameWindow` (sliding window, disk spill under a memory budget, read-ahead), and +`GeometryStage` (crop/aspect/affine with Catmull-Rom). Memory is governed by the window +size and budget, never by sequence length; the self-tests assert this. + +### 8.5 Thumbnails and proxies + +- Thumbnail: 320 px long edge JPEG q80, packed per sequence in `thumbs.pack` (header, + index table, entries), with an LRU in-memory cache and async loading for the UI. +- Proxy: JPEG at policy long edge (default 1920; options 1280/1920/2560/full), q92, Exif + orientation applied, capture time copied into Exif. Proxies are optional and regenerable; + they enable remote editing, server-side rendering of formats the server cannot decode, + and fast scrubbing. + +### 8.6 The only OS executables/dialogs the product may invoke + +`SHFormatDrive` (format card), `ShellExecute("open", url)` (links, Store pages), +`ShellExecute("explore", folder)` (reveal in Explorer). Nothing else. + +--- + +## 9. Metadata model and parsers (`Titano.Core/Metadata`) + +Port and extend the prototype's binary parsers: container detection by signature; JPEG +segment scan (APP1 Exif, APP1 XMP + extended XMP, APP2 MPF); TIFF/IFD walker with on-demand +window reads (never load a whole RAW to read tags), SubIFD selection of the main image, +`0x02BC` XMP; ISO-BMFF walker (`meta/iinf/iloc` Exif item, CR3 `CMT` boxes, `PRVW`/`THMB`, +track sample tables for the CR3 JPEG); RIFF; RAF; PNG chunks. MakerNote parsing only where +it adds value: Canon/Nikon/Sony/Fuji/Olympus/Panasonic body serial, shutter count, lens +name, exposure mode, image stabilisation flag, intervalometer hints, sRaw flags. + +Fields extracted per frame: DateTimeOriginal + SubSecTimeOriginal + OffsetTimeOriginal +(fallback: CreateDate, GPS time, file mtime — recorded with `TimestampSource`), ExposureTime, +FNumber, ISO, FocalLength (+35 mm equiv), ExposureBias, ExposureProgram, MeteringMode, +WhiteBalance mode + Kelvin if present, Flash, Orientation, dimensions, Make/Model/BodySerial, +Lens, GPS (lat/lon/alt), Artist/Copyright, Rating/Label from XMP, `Software`. All parsers +are fuzz-safe (no exception escapes; malformed input yields partial metadata + a warning). + +`ExifWriter` (prototype) is kept for proxies/exports: writes a minimal, valid Exif block. + +--- + +## 10. Analysis advisor + +Two passes; both deterministic, both explainable (every finding and every recommendation +carries a resource key + parameters that render as a localised reason in tooltips). + +### 10.1 Light analysis (at import/scan, metadata only, seconds per 10k frames) + +Cadence (median interval, jitter, gaps → session boundaries; `SessionGapMinutes` default +45, `MinimumSessionFrames` 8), total capture span, exposure series (EV = +log2(N²/t) − log2(ISO/100)), exposure step detection (ISO/shutter/aperture changes and +their EV amplitude), camera/lens identity, orientation consistency, resolution +consistency, timestamp sanity (clock resets, duplicates, non-monotonic), format tiers, +GPS → sunrise/sunset/civil twilight via an in-house solar-position calculation (NOAA +algorithm) → day/night/transition labelling. + +### 10.2 Deep analysis (background job after import; "speed is not an issue") + +Every frame decoded at analysis width (default half native, capped 2048): per-frame +trimmed log-luminance mean, histogram, clip fractions, per-channel means (WB drift), colour +temperature where applicable (McCamy with Planckian-locus validity check), sharpness +(Laplacian variance), noise estimate, phase-correlation shift vs previous frame (shake +magnitude, drift → panning), region mask (horizon by strongest row-luminance step, refined +per column; fallback by luminance), flicker spectrum (autocorrelation of luminance +residuals → deflicker window), exposure steps *as actually received* by the pixels, +star-field detection (small bright point density on night frames), cloud coverage estimate +(sky-region texture), scene-change detection (histogram distance), duplicate/black/white +frames, motion magnitude histogram (for motion-blur recommendation), suggested hero frame. +Results → `analysis.json` + compact summary in DB; charts in the Sequence editor. + +### 10.3 Recommendations (rules, each with reason and confidence) + +- Frame timing mode: Constant when jitter < tolerance; Adaptive when the intervalometer + paused deliberately; Interpolated when gaps are sparse and motion is smooth. +- Frame rate and time compression: choose 24/25/30/60 fps and duration targets from cadence + and motion magnitude; offer "fit to N seconds". +- Motion blur target shutter angle: from measured shutter angle (360×exposure/interval) and + motion magnitude; skip flow when exposure already exceeds the target. +- Deflicker window (4× flicker period), region deflicker when horizon confidence is high, + holy-grail transition length (half the typical distance between exposure steps), WB + smoothing, stabilization on/off (measured shake > 0.3 px) with crop cost, crop/aspect + suggestions from subject placement, output resolution cap from source/preview size and + codec level limits, quality profile. +- Auto-generated **sequence presets** ("Night sky — 4K 10-bit HEVC 24 fps, deflicker 41, + stabilise", "Holy grail sunset — 4K HEVC 30 fps, transitions 18", "Construction cam — + 1080p H.264 30 fps, adaptive timing", "Social vertical 1080×1920") = full project settings + + export preset; one click to apply; saveable as user presets. + +### 10.4 Auto vs manual + +Every deducible parameter shows an **Auto** indicator with the chosen value and a reason +tooltip; touching the control takes it manual; a small reset returns it to Auto. Per section +**Optimise** applies heavier decisions (module on/off) and reports what changed and why. Where +data is missing, the advisor says so and changes nothing. + +--- + +## 11. Rendering engine and export + +### 11.1 Render plan (port) + +The engine walks a list of output frames, each with a (possibly fractional) source position +and a duration; constant, adaptive, interpolated and remapped timings all produce this one +shape. Fractional positions synthesise frames from the motion field; motion blur scales +with `√(target² − real²)` shutter angle composition (prototype rule). + +### 11.2 Modules (port, keep the validated behaviour and its tests) + +Colour science (linear light, sRGB transfer), orientation detection (declared vs decoded +size), deflicker (weighted local linear regression with Tukey robustness blended by +surviving-window fraction), region deflicker (horizon/luminance masks), holy-grail exposure +step redistribution (only steps the pixels actually received), WB smoothing (channel +ratios), optical flow (pyramidal differential, median filtered), motion blur (gather +filter), stabilization (phase correlation, nine patches, similarity fit, texture gating, +smoothed path), virtual camera (Bézier eased pan/zoom keyframes, composed with +stabilization into one affine), non-linear time remap (Fritsch–Carlson monotone spline), +temporal stacking (median, progressive max with decay), geometry stage, codec level limits, +disk spill, cancellation semantics. + +### 11.3 Encoders and containers + +| Output | Client (Windows) | Server (Linux/Windows) | +|---|---|---| +| MP4 H.264 (Baseline/Main/High, 8-bit) | Media Foundation: hardware MFT (NVENC/QSV/AMF) else Microsoft software encoder | render node; P2 in-house intra-only encoder | +| MP4 HEVC Main / Main10 (10-bit, P010) | hardware MFT only | render node | +| MP4 AV1 | hardware MFT only (Windows 11 + AV1 encoder) | render node | +| AVI MJPEG | managed | managed | +| Image sequence JPEG / PNG / TIFF-16 / linear DNG | managed | managed | +| Animated GIF, APNG | managed | managed | + +Encoder session design as prototype: encoder MFT driven directly (not SinkWriter), NV12/P010 +conversion in-house, Annex-B → MP4 samples, streaming muxer; rate control (VBR/CBR/quality), +GOP, B-frames, profile/level via `ICodecAPI`. Capability discovery (`MFTEnumEx` hardware +flag, friendly names, DXGI adapter) is shown in Settings › Rendering and used to hide +unavailable codecs. + +### 11.4 Presets + +Presets bind resolution, aspect, codec, profile, bit depth, fps, bitrate (≈0.10 bpp/frame +H.264, 0.07 HEVC, 0.05 AV1; night-sky content is the most demanding), GOP and container. +Editing any value flips the name to "Custom"; matching values restore the preset name. + +Built-in presets: 8K UHD 10-bit HEVC archive · 4K UHD 10-bit HEVC archive · 4K UHD HEVC · +4K UHD H.264 compatible · DCI 4K HEVC 24 fps · Cinema 21:9 4K HEVC 24 fps · 4K 60 fps · +1440p H.264 · 1080p H.264 share · 1080p 60 · 1080×1920 vertical social · 1080×1350 4:5 · +1440×1440 square · 720p quick preview (GOP 1 s) · AV1 4K · MJPEG AVI intermediate · PNG +sequence · JPEG sequence · TIFF-16 sequence · GIF preview (480 px) · APNG. Resolutions: +720p/1080p/1440p/4K UHD/DCI 4K/5K/6K/8K/custom; aspects 16:9, 21:9, 4:3, 3:2, 1:1, 9:16, +4:5, source, custom; fps 23.976/24/25/29.97/30/48/50/59.94/60/120. + +### 11.5 Export UI behaviour + +Preview stays visible during encoding (optional live preview); single global progress bar +(frames, fps, elapsed, ETA) mirrored to the taskbar; cancel is always available and leaves +no partial files behind; output name from `{title} - {preset}` template; "Reveal in +Explorer" and "Render another preset" follow-ups; batch render of several presets in one +job; per-sequence render history. + +### 11.6 P2: in-house H.264 intra-only encoder + +Baseline profile, I-frames only, I_16x16/I_4x4 prediction, 4×4 integer transform, CAVLC, +fixed QP or simple rate control. Large files but universally playable; enables MP4 output +on a server without render nodes. Validate with the in-house MP4 inspector and a system +player smoke test on Windows CI. + +--- + +## 12. Titano desktop client — UI specification + +### 12.1 Shell + +``` +┌────┬─────────────────────────────────────────────────────────────────────────────┐ +│ ≡ │ ▮▮▮▮▮▮▮▮▮▮▮▮▮░░░░░░░ Building proxies · Harbour sunset · 1,240/3,600 · 12 fps · 3 min │ ⏹ │ ← global job bar, only while a job runs +│ ├─────────────────────────────────────────────────────────────────────────────┤ +│ ▤ │ │ +│Lib │ │ +│ ⬇ │ section content (edge to edge) │ +│Imp │ │ +│ ✎ │ commands of the section live INSIDE the section, in one row above the │ +│Seq │ content they act on; every command has a tooltip │ +│ ▣ │ │ +│Arch│ │ +│ ⚙ │ │ +│Jobs│ │ +│ ☁ │ │ +│Srv │ │ +│ │ │ +│ ⚙ │ │ +│Set │ │ +│ ⓘ ├─────────────────────────────────────────────────────────────────────────────┤ +│ │ 412 sequences · 618,204 photos · 9.4 TB · ☁ Connected to "Studio NAS" · 3 jobs │ ← status strip +└────┴─────────────────────────────────────────────────────────────────────────────┘ +``` + +- Left navigation rail (prototype pattern): full names, collapsible to icons (state saved), + badge counts (warnings, running jobs), hover tooltip with section description. +- Fluent theme, system/dark/light, system accent; density "comfortable"; 8 px grid; one + typeface (Segoe UI Variable, system fallback for CJK/Arabic/etc.). +- Window chrome custom (dark title bar), min size 1200×760; per-monitor DPI. +- Keyboard: standard shortcuts, listed in tooltips ("Render · Ctrl+R"). +- Notifications: unobtrusive toasts inside the window (bottom-right) for job completion, + card detected, server events; optional OS toast when minimised. +- Modals only for destructive confirmations and login. + +### 12.2 Library (home) + +``` +│ [🔍 Search title, camera, tag] [Year ▾] [Camera ▾] [Status ▾] [Tags ▾] [Sort ▾] [⊞][☰][▦] [⟳] │ +├──────────────────────────────────────────────────────────────────────────────────────────────┤ +│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ +│ │ hero thumb │ │ │ │ │ │ │ │ │ │ │ │ +│ │ │ │ │ │ │ │ │ │ │ │ │ │ +│ ├────────────┤ ├────────────┤ ├────────────┤ ├────────────┤ ├────────────┤ ├────────────┤ │ +│ │Harbour sun…│ │2026-09-27 │ │… │ │ │ │ │ │ │ │ +│ │3,600 · R5 │ │1,020 · GoPr│ │ │ │ │ │ │ │ │ │ +│ │✓ ▣ ▶2 ☁ │ │✓ ▣ · ☁ │ │ │ │ │ │ │ │ │ │ +│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │ +``` + +- Unit of the library = **sequence** (never a flat list of 600k photos). Views: grid + (default), list (sortable columns), timeline (year/month bands with density). +- Card: hero thumbnail, title (user title or `{date} {camera}`), count · camera · span, + status chips: `✓` analysed, `▣` proxies, `▶n` renders, `☁` synced/origin, `!` warnings. + Hover reveals quick actions: Open, Analyse, Render preset, Sync. +- Multi-select → mass actions bar (Analyse, Build proxies, Verify, Tag, Rate, Move, + Upload, Download, Delete, Export list as CSV). +- Filters are chips; saved views (e.g. "Night, 4K, not rendered"); search is instant + (indexed columns); everything virtualized (in-house `VirtualizingWrapPanel`). + +### 12.3 Sequence editor + +``` +│ ← Harbour sunset · 3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m [Analyse] [Optimise all] [Render ▾] │ +├──────────────────────────────────────────────────────────────────┬──────────────────────────────────┤ +│ ┌──────────────────────────────────────────────────────────────┐ │ Exposure │ +│ │ │ │ Deflicker [●] Auto 41 ⓘ │ +│ │ PREVIEW │ │ Strength ───●──── 0.8 │ +│ │ │ │ Regions [●] Auto horizon │ +│ │ [◧ compare] [⊹ vectors] [▭ regions] [▦ crop mask] [1:1] [⛶] │ │ Transitions [●] Auto 18 ⓘ │ +│ └──────────────────────────────────────────────────────────────┘ │ WB smoothing [●] Auto │ +│ ▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏ filmstrip + markers │ │ +│ [Frames] [Exposure] [Motion] [Camera] [Time] [Stack] [Export] │ [Optimise section] [Reset] │ +│ ┌──────────────────────────────────────────────────────────────┐ │ │ +│ │ measured (amber) vs target (accent) luminance chart, │ │ │ +│ │ exposure-step markers, region curves; click = seek preview │ │ │ +│ └──────────────────────────────────────────────────────────────┘ │ │ +``` + +- Preview always on top with tools: zoom/pan (1:1 shows raw pixels), wipe compare + original/corrected, motion-vector overlay, region boundary, crop mask ("what I lose" vs + "how it will look"), full-screen native-resolution window with collapsible shot data. +- Sections (tabs inside the editor; each with its measuring tool below the filmstrip and + its settings column on the right): **Frames** (virtualized table: index, time, exposure, + ISO, f, size, tier, flags; exclude/include; set hero; warnings list), **Exposure** + (deflicker, regions, holy-grail transitions, WB) with luminance/waveform charts, + **Motion** (blur, flow quality, stabilization) with shake path chart, **Camera** (crop, + aspect, virtual camera keyframes with a spline editor), **Time** (fps, timing mode, remap + curve, fit-to-duration, plan chart), **Stack** (median/max, trail length), **Export** + (preset, values, output name, batch list, render history, sponsor slot — Phase 9 only). +- Every deducible control shows Auto/manual state (§10.4); every control has a tooltip + with the reason and the effect of moving it the wrong way. +- While a job runs on this sequence, settings that would change the rules mid-render are + disabled; viewing tools stay live. + +### 12.4 Import (cards) + +``` +│ Devices │ Profile "EOS R5 · card A" (SD 128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431) [Edit ▾] [New] │ +│ ● SD 128 GB EOS R5 card A ▲ │ Destination (•) Archive ( ) Folder [D:\Shoots …] ( ) Server ☁ "Studio NAS" │ +│ ● microSD 64 GB GoPro 12 │ Scan [✓] Subfolders Sessions [✓] gap [45] min · min [8] frames [✓] Verify hashes │ +│ ○ E:\ no DCIM │ Names {year}/{date} {camera} / {date}_{time}_{n:0000} → 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2 │ +│ ○ Folder… │ On existing (•) Skip ( ) Rename ( ) Overwrite Convert (•) Copy ( ) TIFF-16 ( ) Linear DNG ( ) JPEG │ +│ │ After import (•) Keep card ( ) Delete imported ( ) Format card [✓] Eject [✓] Deep analysis │ +│ [✓] Import automatically when │ Plan 3 sessions · 4,812 photos · 96.2 GB · 12 min [Show plan] [ Import ▶ ] │ +│ a known card is inserted │ │ +``` + +- Devices list: removable volumes and any volume with `DCIM`; identity = volume serial + + label + capacity, camera identity from the first file; known cards show their nickname + and profile; unknown cards prompt for a nickname (one field). +- Plan before touching disk: sessions, folders to be created, first three file names, + duplicates already in the archive (by hash), disk space check. +- Copy with hash while streaming; verify by re-reading destination; only then delete or + format (OS dialog); eject via `IOCTL_STORAGE_EJECT_MEDIA` after `FSCTL_LOCK_VOLUME`. +- Destination "Server" streams frames through the client to the server (§14.4); the + server confirms each hash before the client counts it as imported. +- Auto-import on insertion (per card), with the OS toast "Card X detected — Import". + +### 12.5 Archive manager + +``` +│ [Archive: D:\TitanoArchive ▾] [Scan] [Rebuild index] [Verify] [Duplicates] [Orphans] [Adopt folder…] [Maintenance ▾] │ +├──────────────────────────────────────────────────────────────────────────────────────────────────────┤ +│ 618,204 photos · 412 sequences · 9.4 TB · 14 cameras · 2019–2026 │ +│ ▆▇█▅▂▁▃▆ photos per month (heatmap) ██████░░ storage by year ▉▉▉▍ by camera ▉▉▎ by format │ +│ Index health: ✓ sidecars 412/412 · ⚠ 3 sequences without proxies · ⚠ 1 unverified since 90 days │ +│ Recent maintenance: 2026-09-20 verify ✓ · 2026-09-01 vacuum ✓ │ +├──────────────────────────────────────────────────────────────────────────────────────────────────────┤ +│ Mass operations on filtered set (412): [Analyse] [Proxies] [Thumbnails] [Verify] [Move] [Retag] [Export CSV] [Delete] │ +``` + +Operations: **Scan** (incremental, mtime/size), **Rebuild index** (from sidecars; falls +back to full metadata scan; never deletes originals), **Verify** (hashes; bit-rot report), +**Duplicates** (by hash across sequences), **Orphans** (files not indexed / rows without +files, with fix actions), **Adopt folder** (index an existing tree in place or copy into +the layout), **Merge/split sequences**, **Move archive** (relink), **Maintenance** +(SQLite vacuum/backup/restore, cache cleanup, proxy purge/rebuild, thumbnail pack +compaction, log rotation). Statistics drawn with in-house chart elements. Every operation +is a Job (resumable, cancellable, logged). + +### 12.6 Jobs + +Queue + history table: kind, target, progress, fps, ETA, node, state; pause/resume/cancel/ +retry; log tail on expand; filters. Global job bar mirrors the active job. + +### 12.7 Server (client side) + +``` +│ Server [https://nas.local:8443 ……] [Connect] Status ● Connected · v1.3 · TLS fingerprint 9A:… (trusted 2026-09-01) │ +│ Signed in as alberto · Editor · 2.1 TB of 5 TB used [Sign out] │ +│ [✓] Offer this PC as render node (NVENC HEVC/H.264, AV1) [✓] Keep proxies of synced sequences offline │ +├───────────────────────────────────────────────────────────────────────────────────────────────────────┤ +│ Sequence Local Server State Action │ +│ Harbour sunset ✓ originals ✓ in sync — │ +│ Comet 2026-08-13 ✓ originals ✗ local only [Upload] │ +│ Construction cam wk 38 proxies ✓ remote [Download originals] [Open with proxies]│ +``` + +First connection shows the certificate fingerprint (trust-on-first-use); login modal; +per-sequence sync actions and states; conflict resolution only for settings JSON (keep +mine / take server / save both). + +### 12.8 Settings + +Sections (list on the left, controls on the right, no descriptions — tooltips only): +General (language, theme, startup, notifications), Archive (root, templates, proxy policy, +thumbnail size, network polling), Import (defaults, session rules, verify, post-actions), +Analysis (widths, thresholds, deep analysis auto-run), Rendering (quality profile, memory +budget, spill folder, parallelism, encoders detected, hardware preference), Formats (per +format tier on this PC, codec install links), Server (last servers, trusted fingerprints, +render node), Updates (check on start), Advanced (portable mode, logs, database backup/ +restore, reset). Import/export settings as JSON. + +### 12.9 About + +Version, build, licence/EULA link, third-party notice (none), diagnostics bundle button +(zips logs + environment report), update check. + +--- + +## 13. Card import — behaviour details + +- Detection: `WM_DEVICECHANGE` (`DBT_DEVICEARRIVAL`/`REMOVECOMPLETE`) + `DriveInfo` poll + fallback; card identity `{volumeSerial}-{label}-{capacity}`; camera identity from EXIF + Make/Model/BodySerial of the first image found. +- Card pool (`media_cards`): nickname, profile, history; profiles copyable; a card can + inherit a "camera profile" (rules shared by all cards of that camera). +- Session detection: gap > `SessionGapMinutes`; groups with < `MinimumSessionFrames` merge + into the previous session (test shots); each session becomes a sequence; the user can + merge/split in the plan. +- Duplicate handling: hash lookup against the archive index (skip/rename/overwrite); + "already imported" state remembered per card + file (path, size, mtime) for fast + re-inserts. +- Rename during import: templates (§7.1) with live preview; original name kept in the + sidecar. +- Post-actions: keep / delete imported files (only those verified) / format card (OS + dialog) / eject; run deep analysis automatically (default on, background, low priority). +- Failure handling: card removed mid-copy → partial files deleted, plan resumable on + re-insert; errors listed per file, never a modal per error. + +--- + +## 14. Titano Server + +### 14.1 Stack + +ASP.NET Core minimal API on Kestrel (`Microsoft.AspNetCore.App` shared framework, no +packages), `System.Text.Json` source-generated contexts from `Titano.Protocol`, WebSockets +for events, in-house structured file logging (`Microsoft.Extensions.Logging` abstractions +are part of the shared framework; the file provider is in-house), in-house rate limiting for +login and uploads, health endpoint, graceful shutdown (jobs checkpoint). + +### 14.2 Security + +- TLS: `auto` (self-signed cert generated at first start with `CertificateRequest`, stored + in `/data/tls`, fingerprint printed in logs and shown in admin), `pem` (cert + key + paths), `proxy` (HTTP behind a reverse proxy, `ForwardedHeaders` middleware, admin warns + if not local). +- Passwords: PBKDF2-SHA512, ≥ 210,000 iterations, 16-byte salt, versioned hash format; + minimum length 10; admin-created users get `mustChangePassword`. +- Tokens: 32 random bytes, stored as SHA-256, `Authorization: Bearer`; sliding expiry + (default 30 days), per-client name, revocation list; web admin uses an `HttpOnly; Secure; + SameSite=Strict` cookie session + double-submit CSRF token. +- Authorization: roles admin/editor/uploader/viewer + permission bits; sequence ownership; + admin-only management endpoints; path traversal impossible (ids → paths via DB only). +- Limits: max upload size, chunk size (default 8 MiB), per-user quota, request timeouts, + login rate limit (5/min/IP), audit log. + +### 14.3 API v1 (JSON; errors as `{ code, message, details }`; `X-Titano-Api: 1`) + +``` +POST /api/v1/auth/login {username,password,clientName} → {token,user,mustChangePassword} +POST /api/v1/auth/logout · POST /auth/password · GET /auth/me +GET /api/v1/server/info name, version, apiVersion, capabilities, tlsFingerprint, formats, limits +GET /health + +GET /api/v1/users · POST · GET/PATCH/DELETE /users/{id} · POST /users/{id}/reset-password (admin) + +GET /api/v1/sequences?year&camera&status&tag&q&cursor&limit +POST /api/v1/sequences create (title, camera hint) → id +GET /api/v1/sequences/{id} · PATCH (title, tags, rating, settings) · DELETE +GET /api/v1/sequences/{id}/manifest frames with hashes/sizes/versions (sync) +GET /api/v1/sequences/{id}/analysis · GET /stats · GET /renders +GET /api/v1/sequences/{id}/frames?cursor&limit +GET /api/v1/frames/{id}/original · /proxy · /thumb (streamed, Range supported) + +POST /api/v1/uploads {sequenceId|null, fileName, size, sha256, capturedAt?} → {uploadId, chunkSize, received[]} | 200 {alreadyExists} +PUT /api/v1/uploads/{id}/chunks/{n} body bytes (idempotent) → {received} +POST /api/v1/uploads/{id}/complete → frame id (server verifies sha256, commits into layout, updates manifest) +GET /api/v1/uploads/{id} resume state +DELETE /api/v1/uploads/{id} + +GET /api/v1/jobs?state · POST /jobs {kind, target, params} · GET /jobs/{id} · POST /jobs/{id}/cancel · /retry +WS /api/v1/events {type: jobProgress|jobState|sequenceChanged|cardEvent|nodeState, …} + +POST /api/v1/nodes/register · POST /nodes/{id}/heartbeat · POST /nodes/{id}/claim → job · POST /nodes/{id}/jobs/{jobId}/result (chunked upload of output) + +GET/PUT /api/v1/archive/settings · POST /archive/scan · /rebuild · /verify · GET /archive/stats · POST /archive/maintenance (admin) +GET /api/v1/i18n/{culture} strings for the web admin +``` + +### 14.4 Upload and ingest + +Client computes SHA-256 while reading; `POST /uploads` short-circuits if the hash exists; +chunks are written to `/data/uploads/{id}.part` with a received-bitmap; `complete` verifies +the hash, moves the file into `originals/` under the layout templates (temp → fsync → +rename), extracts metadata, appends to `sequence.json`, inserts the DB row, enqueues +thumbs/proxies/light analysis, emits `sequenceChanged`. Frames without a target sequence +are grouped by the same session rules (§13) into auto-created sequences. Card imports from +a connected client use exactly this path. + +### 14.5 Sync + +Manifest diff per sequence: originals are content-addressed (never conflict); settings and +tags carry version counters (last-writer-wins with an explicit conflict prompt in the +client when both changed); proxies/thumbs are regenerable and never synced upward; renders +are uploaded on request. "Edit with proxies, render where the originals are": a client can +open a remote sequence with proxies only and submit a render job to the server, which runs +it itself (managed formats) or hands it to a render node. + +### 14.6 Job engine + +Persistent queue in the DB; N worker threads (configurable, default = cores/2); job kinds +in §5; checkpoints every 5 s (progress + resumable cursor); crash-safe restart; priorities +(user-initiated > background analysis); cancellation cooperative; logs per job; retention +of history 90 days. + +### 14.7 Render nodes + +A Titano client with "Offer this PC as render node" registers its encoder capabilities +and polls/claims render jobs matching them, downloads what it needs (proxies or originals +per job settings), renders with its GPU, uploads the result as a render of the sequence. +Node state shown in admin › Jobs; the server falls back to managed formats when no node is +available and says so in the job log. + +### 14.8 Admin web panel (`/admin`, vanilla HTML/CSS/JS, ES modules, no build step, same API) + +``` +┌─────────────┬────────────────────────────────────────────────────────────────────────────┐ +│ Titano │ Dashboard │ +│ ● Dashboard │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ +│ Users │ │ 9.4 TB │ │ 412 seq │ │ 3 jobs │ │ 2 nodes │ │ +│ Archive │ │ of 16 TB │ │ 618k pho │ │ running │ │ online │ │ +│ Jobs │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ +│ Settings │ Storage by year ▁▂▃▅▇█ Uploads last 30 days ▂▁▃▆▇▅▂ │ +│ Logs │ Recent: alberto uploaded 1,020 frames · node "studio-pc" rendered 4K HEVC │ +│ About │ │ +└─────────────┴────────────────────────────────────────────────────────────────────────────┘ +``` + +Pages: Login · Dashboard · Users (table; create/edit/disable/reset/roles/quota) · Archive +(path, templates, proxy policy, scan/rebuild/verify, stats) · Jobs (queue/history/nodes, +cancel/retry) · Settings (server name, ports, TLS mode + fingerprint, discovery, limits, +language, retention) · Logs (tail, download) · About. Same UI rules: tooltips only, light/ +dark, localised via `/api/v1/i18n`, keyboard accessible. + +### 14.9 Configuration and Docker + +Environment variables (also readable from `/data/server.json`): +`TITANO_ADMIN_USER`, `TITANO_ADMIN_PASSWORD` (used only when no admin exists; forced change +at first login), `TITANO_ARCHIVE_PATH=/archive`, `TITANO_DATA_PATH=/data`, +`TITANO_DB=postgres|sqlite` (Linux: postgres only), `TITANO_DB_HOST`, `TITANO_DB_PORT=5432`, +`TITANO_DB_NAME`, `TITANO_DB_USER`, `TITANO_DB_PASSWORD`, `TITANO_DB_SSLMODE=prefer`, +`TITANO_HTTP_PORT=8080`, `TITANO_HTTPS_PORT=8443`, `TITANO_TLS_MODE=auto|pem|proxy`, +`TITANO_TLS_CERT`, `TITANO_TLS_KEY`, `TITANO_SERVER_NAME`, `TITANO_LANG=en`, +`TITANO_WORKERS`, `TITANO_DISCOVERY=true` (LAN UDP beacon), `PUID`, `PGID`, `TZ`. + +Dockerfile: multi-stage on `mcr.microsoft.com/dotnet/sdk:10.0` → `aspnet:10.0`, non-root +user via `PUID/PGID` entrypoint, volumes `/archive` and `/data`, `HEALTHCHECK` on +`/health`, `linux/amd64` + `linux/arm64`. `docker-compose.yml` with a PostgreSQL 17 service. +Windows: `Titano.Server.exe` runs as console or Windows Service (`sc create`), SQLite or +PostgreSQL. + +--- + +## 15. Titano Uploader + +Single small window (tray-capable), zero analysis: connect + sign in (token saved with +DPAPI), drop zone (files/folders/cards), queue with per-file state, pause/resume, bandwidth +limit, retry with backoff, resumable across restarts (queue persisted in a JSON file next to +the app data), hash verification, optional "delete source after server confirms" (off by +default, confirmation), watch folders (poll + `FileSystemWatcher` where reliable; upload +new files after they stop growing), run at startup, minimise to tray, per-session target +(auto-group / choose sequence / new sequence with title). P2: "make proxies here" toggle +for HEIC/RAW so the server can render without a node. + +``` +│ Titano Uploader ☁ https://nas.local:8443 · alberto · ● Connected [⚙] │ +│ ┌────────────────────────────────────────────────────────────────────────────────┐ │ +│ │ Drop photos, folders or a card here │ │ +│ └────────────────────────────────────────────────────────────────────────────────┘ │ +│ Target (•) Group into sessions automatically ( ) Sequence [Harbour sunset ▾] ( ) New │ +│ Queue 4,812 files · 96.2 GB · 38 MB/s · 41 min left [⏸] [⏹] Limit [50] MB/s │ +│ ▮▮▮▮▮▮▮▮▮▮▮▮▮▮░░░░░░░░░░░░░░░░ 2026-09-28_18-02-11_0413.CR2 │ +│ Watch folders D:\Cam\Roof (every 60 s) ● [+] │ +│ [✓] Delete source after verified upload [✓] Start with Windows │ +``` + +--- + +## 16. Localization + +- Source strings in `i18n/en/*.resx` (one file per area: `Shell`, `Library`, `Editor`, + `Import`, `Archive`, `Server`, `Settings`, `Tooltips`, `Errors`, `Advisor`, `Admin`). + Keys are stable identifiers (`Library.Filter.Year`), never English sentences. +- Runtime: `ResourceManager` + a `Loc` XAML markup extension and `L("key", args)` helper in + `Titano.Core/Localization`; culture switch at runtime without restart (rebinding via a + `LocalizationChanged` event); web admin receives `/api/v1/i18n/{culture}` generated from + the same resx by `Titano.Tools i18n export`. +- Plurals: an in-house minimal CLDR plural-rule table for the shipped languages + (`one/few/many/other`), keys with suffixes (`Photos.Count.one`, `.other`). +- Dates/numbers/units via `CultureInfo`; file sizes localised; RTL via `FlowDirection` + for `ar`, `he`, `fa`, `ur` (mirrored rail and icons where directional). +- Languages (Phase 8, all machine-translated by Claude Code with a glossary, marked as such + in About and open to community review via the public releases repo): `en` (source), `it`, + `de`, `fr`, `es`, `pt-BR`, `pt-PT`, `nl`, `pl`, `cs`, `sk`, `hu`, `ro`, `sv`, `da`, `nb`, + `fi`, `ru`, `uk`, `tr`, `el`, `bg`, `hr`, `sl`, `lt`, `lv`, `et`, `ja`, `zh-Hans`, + `zh-Hant`, `ko`, `ar`, `he`, `hi`, `id`, `ms`, `vi`, `th`. Add more if effort allows. +- `Titano.Tools i18n check` fails CI when a key is missing in `en` or `it`, when a + placeholder count differs between languages, or when a string exceeds the layout budget + (tooltips ≤ 200 chars, labels ≤ 30 chars unless flagged). +- UI is written to survive +40 % text expansion (German, Finnish): no fixed-width labels. + +--- + +## 17. Branding and icon + +- Mark: a **time-lapse aperture-clock** — a circle of 12 short arc segments increasing in + opacity clockwise (the sequence of frames) around a solid sun disc slightly off-centre, + reading as camera aperture, clock and sun path at once; single accent colour on a rounded + square (dark) tile; no text. Works at 16 px (segments merge into a ring; the disc + remains). +- Generated programmatically (`Titano.Tools make-icon`): in-house PNG encoder + ICO + container (16/20/24/32/48/64/128/256), SVG source kept in `branding/`; variants: Server + (mark + three horizontal bars badge), Uploader (mark + up-arrow badge). Also favicon + for the admin panel and a 1024 px PNG for listings. Prototype `IconGenerator` shows + the ICO writer approach. +- App name in title bar only; no splash screen; first-run screen is the empty Library + with one sentence and two buttons (Import a card · Open an archive). + +--- + +## 18. Installer, distribution and updates + +- Builds: `dotnet publish -c Release -r win-x64 --self-contained -p:PublishSingleFile=true + -p:PublishReadyToRun=true` for App, Uploader, Setup; server as framework-dependent + Docker image and a self-contained Windows zip/installer. (No trimming: WPF does not + support it.) +- `Titano.Setup` (in-house, WPF, ~one screen): choose components (Titano, Uploader, + Server for Windows), folder, shortcuts, file associations (`.titano` project bundles), + installs to `%LOCALAPPDATA%\Programs\Titano` per user (no admin) or `Program Files` + (elevated), registers Add/Remove Programs entry with uninstaller, silent mode + (`/S /DIR=`), upgrade in place, keeps user data. Payload appended to the setup exe as a + compressed archive (in-house format on `DeflateStream`) with a manifest and per-file + hashes. If the human later permits a build-time tool, Inno Setup/MSIX are acceptable + alternatives; default is in-house. +- Code signing hook in the release workflow (`signtool` from the Windows SDK) using + secrets when present; unsigned builds are still produced. +- Updates: on start (opt-out) the client calls the GitHub Releases API of the **public + releases repository** (§19.4) and shows a one-line notice with "Download" (P1: download + installer, verify SHA-256 from `SHA256SUMS`, run it). +- Distribution: installers and `SHA256SUMS` on the public releases repo; Docker images on + GHCR (public package); Unraid template in the public repo. + +--- + +## 19. CI/CD, Docker, Unraid + +### 19.1 `ci.yml` (push, PR) + +Matrix `windows-latest` / `ubuntu-latest`: `dotnet --info`, restore (no packages → fast), +build with warnings as errors, run `Titano.Testing` for all test projects (JUnit XML +uploaded and annotated), `dotnet format --verify-no-changes`, `Titano.Tools i18n check`, +XAML lint (App.Tests), zero-package guard, Docker build (no push) on ubuntu; PostgreSQL 16 +and 17 service containers for `Titano.Data.Tests`; CC0 RAW fixtures fetched by +`Titano.Tools fixtures` and cached (`actions/cache`). + +### 19.2 Zero-package guard + +`Directory.Build.targets` target `AssertNoPackageReferences` fails the build if any +`PackageReference` exists; CI also greps `**/*.csproj` and `**/*.props` and checks that +`obj/project.assets.json` lists no packages. Only `actions/*` and `docker/*` GitHub +Actions are used in workflows. + +### 19.3 `release.yml` (tag `v*`) + +Version from the tag → `Directory.Build.props`; publish self-contained binaries; build +`Titano-Setup-.exe`, `Titano-Uploader-Setup-.exe`, `Titano-Server-win-x64-.zip`; +sign if secrets present; generate `SHA256SUMS` and the changelog (`Titano.Tools changelog` +from Conventional Commits); build and push multi-arch Docker image to +`ghcr.io//titano-server:` and `:latest`; create the GitHub Release **in the +public releases repository** with `gh release create` (the `gh` CLI is preinstalled on +runners) using a fine-grained PAT stored as `RELEASES_TOKEN`; copy `deploy/unraid/ +titano.xml` and EULA there. + +### 19.4 Public releases repository + +Because release assets of a private repository are not publicly downloadable, a second, +public repository (`titano-releases`) holds only: README (what it is, screenshots, +requirements), EULA/LICENSE, release assets, `SHA256SUMS`, Unraid template, `i18n/` +translations for community review, and issues. The private repo publishes into it; nothing +is developed there. The GHCR package is set to public visibility. + +### 19.5 `docker.yml` + +Nightly build of `main` to `ghcr.io//titano-server:nightly`; `deploy/docker/ +docker-compose.yml` for users (server + PostgreSQL + volumes). + +### 19.6 Unraid template (`deploy/unraid/titano.xml`) + +Community Applications XML: repository `ghcr.io//titano-server:latest`, WebUI +`http://[IP]:[PORT:8080]/admin`, ports 8080/8443, paths `/archive` → `/mnt/user/Timelapse`, +`/data` → `/mnt/user/appdata/titano`, variables from §14.9 (admin user/password, DB +host/port/name/user/password, TLS mode, PUID/PGID, TZ), icon URL from the public repo, +support/project links, description ≤ 2 sentences. Document (in the public README) how to +add the template repository URL in Unraid and to pair with the official PostgreSQL +template. + +--- + +## 20. Testing and quality + +### 20.1 `Titano.Testing` (in-house) + +Attributes `[Test]`, `[Theory]` + `[Case(...)]`, `[Skip(reason)]`, `[Timeout(ms)]`, +`[Category]`; assertions with expressive messages (`Assert.Equal`, `Approximately`, +`Throws`, `SequenceEqual`, `Monotonic`, `Within(px)`); fixtures (temp dirs, synthetic +sequences, in-process server, database per test); parallel execution; filters by name/ +category; console output + JUnit XML; exit codes; `dotnet run --project tests/X -- --junit +out.xml --filter core`. + +### 20.2 Test layers + +- Unit: parsers (fuzz corpus: truncated/garbage files must not throw), codecs (round-trip + PSNR thresholds), analysis rules (synthetic sequences with known answers — port the + prototype's 63-check self-test as tests), naming templates, SQL repositories (SQLite + in-memory), PostgreSQL wire client (against service container), protocol (chunk resume, + hash mismatch, idempotency), advisor recommendations (golden JSON). +- Integration: import a synthetic card folder → archive layout + sidecars + DB; rebuild + index from sidecars equals original DB; verify detects a flipped byte; server ingest via + API; sync round trip; render node claim/complete; job resume after simulated crash. +- Windows: WIC decode of fixtures, Media Foundation encode smoke (software H.264) + + in-house MP4 inspector + `MediaPlayer` playback check; `--capture` screenshots of every + screen for visual regression (pixel-diff tolerance) and for the phase report. +- Fixtures: tiny synthetic files checked in; CC0 RAW samples (one per major format, from a + public CC0 sample set) fetched by `Titano.Tools fixtures` into `tests/fixtures/external` + (git-ignored, CI-cached). + +### 20.3 Static rules + +Warnings as errors; nullable enabled; `dotnet format`; XAML lint: every `Button`, +`ToggleButton`, `Slider`, `ComboBox`, `CheckBox`, `MenuItem` has a `ToolTip`; no literal +`Content="…"`/`Text="…"` outside resources; no `PackageReference`; no Windows APIs in +`Titano.Core`/`Titano.Data`/`Titano.Protocol`/`Titano.Server` (checked by building them on +Linux); public API of `Titano.Protocol` versioned. + +### 20.4 Quality gates carried over from the prototype (regression thresholds) + +Deflicker: flicker reduction ≥ 60 % on the synthetic ramp sequence with the ramp preserved +within 0.05 EV; region deflicker: landscape residual ≤ 25 % of the global-curve residual; +phase correlation: sub-pixel error ≤ 0.10 px; stabilization on a textureless frame: shake +≤ 0.1 px (texture gating); holy grail: no step > 0.3 EV in the target curve; time remap +monotonic; star-trail luminance non-decreasing on ≥ 99 % of steps; memory: peak RSS +independent of sequence length for a fixed window; cancellation: no partial output, no +unobserved exceptions, spill file removed. + +--- + +## 21. Monetization — absolute final step (Phase 9; do not start before every gate passed) + +- In-house ad delivery, no SDK, no tracking by default: the client fetches a signed + campaign manifest (JSON: id, image URL, link, weight, languages, countries, start/end, + minimum version) from `https://.github.io/titano-releases/ads/manifest.json` + (or a URL set by the human), caches creatives, renders them natively in one slot — the + Export section while a render runs (prototype rationale: the only moment an ad takes + nothing from anyone) — and optionally a small footer slot in Library. Clicks open the + browser. Manifest signature: ECDSA P-256 with an embedded public key. +- Consent: first-run one-line choice for anonymous impression counting (off by default); + when on, a daily aggregated ping (version, language, country from OS locale, counts) — + no identifiers. Privacy policy link in About and EULA. +- Ad-free: "Titano Pro" licence key (ECDSA-signed, offline validation, tied to a display + name and edition, no phone-home) entered in Settings › Licence; a server licence makes + all its connected clients ad-free (team scenario). Fallback content when the manifest + is empty: internal tips about the program. +- Everything above is a toggle in Settings for the human's own builds; the feature ships + disabled by default until the human flips a build property `TitanoAdsEnabled=true`. + +--- + +## 22. Phased delivery plan + +Each phase ends with the Definition of Done (§0.2 rule 9) and a phase report. Phases may be +split into sub-phases; order inside a phase is Claude Code's choice. + +### Phase 0 — Bootstrap (repo, rules, shells) +Solution, `Directory.Build.*`, `global.json`, `CLAUDE.md`, `DECISIONS.md`, `CHANGELOG.md`; +`Titano.Testing`; zero-package guard; `ci.yml`; i18n infrastructure with `en` + `it`; +WPF shell (rail, theme, job bar, status strip, settings skeleton, tooltip lint); server +skeleton (Kestrel, `/health`, `/server/info`, login page, admin shell); Dockerfile builds; +branding mark + ICO generator. +*Gate:* both apps start, server container answers `/health`, CI green on both OSes. + +### Phase 1 — Metadata and imaging core +Parsers (§9), managed codecs (§8.3), WIC provider, decode tiers, thumbnails/proxies, +`ImageBuffer`/`FrameWindow` port, fixtures tool, fuzz tests, DNG full pipeline. +*Gate:* every fixture decodes at the expected tier on Windows and Linux; PSNR/round-trip +tests green; `Titano.Tools diagnose ` reports per-file tier and metadata. + +### Phase 2 — Data layer and archive +SQLite binding, PostgreSQL wire client, migrations, repositories, archive layout, sidecars, +scanner, rebuild, verify, duplicates, orphans, adopt folder, naming templates. +*Gate:* import synthetic 100k-frame archive; rebuild equals original; verify detects +corruption; PG tests green against 16 and 17. + +### Phase 3 — Client Library and Archive manager +Virtualized grid/list/timeline, filters, saved views, mass operations, jobs screen, stats +charts, maintenance, settings screens, `--capture` screenshots. +*Gate:* 500k-photo synthetic library meets §1.1 timings. + +### Phase 4 — Card import +Device detection, card pool and profiles, plan preview, sessions, hash-verified copy, +post-actions (delete/format/eject), auto-import, direct-to-server destination stub. +*Gate:* end-to-end import from a simulated card folder; destructive actions gated by +verification; screenshots. + +### Phase 5 — Analysis advisor +Light + deep analysis, reports, charts, recommendations with reasons, auto presets, +Auto/manual controls, Optimise. +*Gate:* golden recommendations for synthetic sequences; every recommendation has a +localised reason; deep analysis of 10k frames completes unattended. + +### Phase 6 — Engine, encoding and Sequence editor +6a modules port with regression thresholds (§20.4); 6b Media Foundation encoder, MP4 muxer +(H.264/HEVC/AV1), managed encoders (AVI/GIF/APNG/sequences), presets; 6c preview tools, +section charts, spline editor, export UI, batch render. +*Gate:* self-test suite green; renders play in Windows Media Player and the in-house +inspector validates containers; hardware MFT used when present (logged). + +### Phase 7 — Server, sync, uploader +Full API, auth, uploads/ingest, sync, jobs, render nodes, admin panel, Docker + compose, +client server mode, Uploader app, LAN discovery. +*Gate:* two clients + uploader against a Docker server: upload, sync, render via node and +via server; crash-restart resumes jobs; audit log complete. + +### Phase 8 — Worldwide release readiness +All languages (§16), RTL pass, installer, `release.yml`, public releases repo bootstrap +(README, EULA draft, template), Unraid template, update check, diagnostics bundle, +accessibility pass, performance pass, docs. +*Gate:* tagged pre-release published end-to-end from CI; install/uninstall/upgrade tested; +Unraid template validated. + +### Phase 9 — Monetization (§21) +*Gate:* human explicitly approves start; feature behind build property; privacy text done. + +--- + +## 23. Assumptions and open decisions (for the human; do not block on these) + +1. Product name **Titano** kept from the prototype — rename before Phase 0 if desired + (repo-wide rename later is costly). +2. Linux server MP4 output relies on render nodes (and P2 intra-only encoder). If an + FFmpeg subprocess were ever allowed as an *optional, opt-in* backend, it would be a + single `IVideoEncoderProvider`; not planned unless the human approves. +3. HEIC pixels are only decodable on Windows (WIC); server-side rendering of HEIC-only + sequences requires proxies from a client/node. +4. Native RAW decoders beyond DNG are phased (CR2, NEF, ARW, PEF, ORF, RW2, RAF + uncompressed first); until then those formats render from full-size embedded previews + on the server and via WIC + Raw Image Extension on Windows. +5. Windows 10 21H2+/Windows 11, x64 only (ARM64 later); `winsqlite3.dll` presence assumed. +6. Tests use the in-house runner to keep the zero-package rule absolute; xUnit would be + acceptable only if the human relaxes the rule for test projects. +7. Installer is in-house; Inno Setup/MSIX acceptable if the human allows build-time tools. +8. Ads and licence keys are designed but disabled by build property until Phase 9. + +--- + +## Appendix A — `CLAUDE.md` content (create verbatim in Phase 0, keep updated) + +```markdown +# Titano — working rules +Read docs/BRIEF.md when in doubt; it wins over these notes. +- Zero . Anything not in the .NET BCL / Microsoft shared frameworks / OS APIs is written here. +- No external processes at runtime (no ffmpeg, exiftool, powershell). Only OS dialogs listed in BRIEF §8.6. +- Titano.Core / Data / Protocol / Server target net10.0 and build on Linux; Windows-only code lives in *.Windows or the desktop apps. +- English identifiers, comments, commits (Conventional Commits). Prototype in docs/reference is Italian: port algorithms, not language. +- Every UI string is a resource (en source, it translation). Labels ≤ 3 words; explanations only in tooltips; every actionable control has a tooltip; no helper paragraphs. +- Destructive operations: dry-run plan first, hash verification, explicit user action. +- When the brief is silent: choose the simplest safe option, log it in docs/DECISIONS.md, continue. Ask only at phase gates or before irreversible choices. +- Definition of Done per phase: green on windows-latest + ubuntu-latest, tests green, no new warnings, DECISIONS + CHANGELOG updated, i18n check green, phase report with "how to try it". +- Build: dotnet build -c Release; tests: dotnet run --project tests/ -- --junit out.xml; tools: dotnet run --project src/Titano.Tools -- . +- Current phase and next steps: see docs/STATUS.md (update at every gate). +``` + +## Appendix B — Prototype module map (grep targets in `docs/reference/titano-prototype.md`) + +| Prototype (Italian) | New home | Notes | +|---|---|---| +| `Metadata/TiffDirectory, TiffPrimitives, MetadataReader, XmpScanner, FrameMetadata` | `Core/Metadata` | extend with BMFF/RIFF/RAF walkers, MakerNotes | +| `Imaging/WicInterop, ImageDecoder` | `Core.Windows/Wic` | keep pull-based scaling chain | +| `Imaging/ImageBuffer, ColorSpace, GeometryStage, RasterWriter, OrientationDetector` | `Core/Imaging` | RasterWriter → `Codecs/TiffWriter`, `LinearDngWriter` | +| `Analysis/*` (LuminanceAnalyzer, DeflickerEngine, RegionSegmenter, HolyGrailEngine, ExposureProcessor, ColorScience) | `Core/Analysis` | keep validated behaviour + tests | +| `Motion/*` (Fourier, PhaseCorrelator, GrayPyramid, OpticalFlowEngine, MotionField, MotionBlurRenderer, Stabilizer, VirtualCamera, TemporalStacker, FrameInterpolator) | `Core/Motion` | | +| `Core/Spline, LocalRegression, TimelapseSequence, FrameRecord` | `Core/Math`, `Core/Sequences` | | +| `Pipeline/RenderPlan, RenderPipeline, FrameWindow, AutoDirector, AutoOptimizer, SequenceWarnings` | `Core/Render`, `Core/Advisor` | AutoDirector/Optimizer → advisor rules with reasons | +| `Pipeline/MediaImporter, PathTemplate` | `Core/Import`, `Core/Naming` | tokens translated to English | +| `Video/MediaFoundationInterop, VideoEncoderSession, Nv12Converter, CodecLimits` | `Core.Windows/MediaFoundation` | add P010, AV1, capability enumeration | +| `Video/Mp4Muxer, BoxWriter, AnnexBParser, ExportPresets, ExportSettings` | `Core/Video`, `Core/Export` | add `av1C`, new presets | +| `Diagnostics/SelfTest, SyntheticSequence, SequenceDiagnostics, Mp4Inspector, Mp4Playback, AdvancedModuleTests, ExifWriter, IconGenerator, CrashGuard` | `tests/*`, `Titano.Tools`, `Core/Diagnostics` | 63 checks → tests | +| `UI/*` (WinForms) | not ported | reuse only the interaction ideas (rail, preview tools, Auto indicator, presets) | +| `UI/SponsorPanel` | Phase 9 only | | + +## Appendix C — Glossary + +Sequence (a shoot: one folder of frames = one project) · Frame (one photo) · Hero frame +(thumbnail of the sequence) · Light/Deep analysis · Advisor (rule engine producing +recommendations with reasons) · Tier (how a frame's pixels are obtained) · Proxy (JPEG +stand-in) · Sidecar (`sequence.json` manifest) · Render (an exported video) · Preset +(bundle of export values) · Sequence preset (project settings + export preset produced by +the advisor) · Render node (client lending its GPU to the server) · Job (any long +operation, resumable) · Card profile (import rules for a memory card). diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md new file mode 100644 index 00000000..88a030af --- /dev/null +++ b/docs/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +All notable changes. Format: Keep a Changelog; versions follow SemVer; commits follow Conventional Commits. + +## [Unreleased] + +### Added +- Repository foundation: solution, build rules (warnings as errors, zero-package guard), .NET 10 SDK pin. +- `Titano.Testing`: in-house test framework and runner with JUnit XML output. +- Localization runtime (`Loc`, CLDR plural rules, 38 shipped languages) and `i18n check/export`. +- Brand mark geometry, SDF rasteriser, PNG encoder, ICO writer and `make-icon`. +- Core contracts: image buffers and decoder providers, video encoder providers, domain model, atomic file writes. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md new file mode 100644 index 00000000..4b79c26f --- /dev/null +++ b/docs/DECISIONS.md @@ -0,0 +1,16 @@ +# Decisions + +One line per decision: date · decision · alternative · reason. + +| Date | Decision | Alternative | Reason | +|---|---|---|---| +| 2026-10-02 | The prototype dump `docs/reference/titano-prototype.md` was not supplied; algorithms are implemented from the brief's descriptions and the cited literature, with the §20.4 thresholds as acceptance tests. | Wait for the dump | Not available in the repository or uploads; the brief fully specifies behaviour and gates. | +| 2026-10-02 | Custom WPF theme dictionaries (`Titano.Ui/Themes`) implementing DESIGN.md tokens instead of `Application.ThemeMode` Fluent. | Fluent theme + overrides | DESIGN.md fixes exact colours/sizes; Fluent is still flagged experimental (WPF0001) and would need restyling of most controls anyway (§2.1 permits in-house dictionaries). | +| 2026-10-02 | Added shared WPF library `src/Titano.Ui` (theme, icons, controls, `Loc` markup extension) used by App, Uploader and Setup. | Duplicate resources per app | One visual system for three programs. | +| 2026-10-02 | Added `tests/Titano.Core.Windows.Tests` for WIC / Media Foundation / DXGI tests. | Put them in App.Tests | Keeps engine interop tests independent of the WPF app. | +| 2026-10-02 | Localization areas extended with `Common`, `Jobs`, `Uploader`, `Setup`. | Fold into `Shell` | Smaller, owned files; same key scheme. | +| 2026-10-02 | Resources live in `i18n//[.].resx`, embedded into `Titano.Core` (satellite assemblies), base name `Titano.Core.i18n.`. Keys marked `invariant` need no translation. | Raw XML loader | Uses `ResourceManager` as the brief requires; satellites bundle into single-file publishes. | +| 2026-10-02 | Program icons (ICO) are generated at build time into `artifacts/icons` by `Titano.Tools make-icon`, invoked from `Directory.Build.targets`. | Commit generated ICO files | Brief forbids committing generated binaries and raster sources. | +| 2026-10-02 | In-house CRC-32 (`Titano.Core.Hashing.Crc32`). | System.IO.Hashing | That assembly is a NuGet package, not part of the shared framework. | +| 2026-10-02 | Windows projects target `net10.0-windows` (platform version 7.0) without a Windows SDK projection TFM; Windows 10 APIs are reached by P/Invoke/COM. | `net10.0-windows10.0.19041.0` | Avoids the CsWinRT projection; toasts use the in-window toast host plus tray balloon. | +| 2026-10-02 | Test projects use an explicit `TestMain` entry point. | Top-level statements | Avoids the `Program` type clash with the server's top-level program. | diff --git a/docs/STATUS.md b/docs/STATUS.md new file mode 100644 index 00000000..992f99a0 --- /dev/null +++ b/docs/STATUS.md @@ -0,0 +1,5 @@ +# Status + +Current phase: **Phase 0 — Bootstrap** (in progress). + +See docs/BRIEF.md §22 for the phase plan. diff --git a/docs/ui/DESIGN.md b/docs/ui/DESIGN.md new file mode 100644 index 00000000..6bcfbea5 --- /dev/null +++ b/docs/ui/DESIGN.md @@ -0,0 +1,119 @@ +# Titano — Design reference for Claude Code + +Companion to `docs/BRIEF.md` §12 (UI spec). Suggested repo placement: +`docs/ui/DESIGN.md` (this file), `docs/ui/mockups/*.html` (open in any browser; +each file is one screen at its natural size, links between screens work), `branding/` +(icon sources). The mockups are the visual target; where a mockup and the brief disagree +on behaviour, the brief wins; where they disagree on looks, the mockup wins. + +## 1. Tokens → WPF resource dictionary (`Titano.App/Themes/Dark.xaml`, `Light.xaml`) + +| Key (SolidColorBrush) | Dark | Light | Use | +|---|---|---|---| +| `Brush.Bg` | #1F1F23 | #F3F3F3 | window background | +| `Brush.Chrome` | #1A1A1E | #FFFFFF | title bar, rail, status bar, web sidebar | +| `Brush.Surface` | #26262C | #FFFFFF | panels, toolbars, dialogs | +| `Brush.Card` | #2F3038 | #FFFFFF | cards, inputs, buttons, hovered rows | +| `Brush.Stroke` | #3E404A | #E5E5E5 | 1 px borders and dividers | +| `Brush.Text` | #F2F3F5 | #1A1A1A | primary text | +| `Brush.TextMuted` | #A9AEB9 | #616161 | secondary text, labels | +| `Brush.TextFaint` | #7B818E | #9E9E9E | hints, column headers, disabled | +| `Brush.Accent` | #4CC2FF | #0067C0 | primary button, active rail edge, links, Auto | +| `Brush.OnAccent` | #0B1B24 | #FFFFFF | text on accent | +| `Brush.AccentSelected` | rgba(76,194,255,.25) | #E8F1FA | selection glow / selected nav | +| `Brush.Sun` | #F5A524 | #E08A1E | manual slider track, uploader accent, icon sun | +| `Brush.Success` | #35C48F | #0F7B4F | analysed, in sync, done | +| `Brush.Warning` | #E8B339 | #9A6700 | warnings, destructive outline | +| `Brush.Error` | #F0625D | #C42B1C | errors, failed | +| `Brush.Region` | #5AD1C8 | #1A9E95 | sky/landscape region masks only | + +Dark is the client default; Light follows the OS setting; the web admin is Light-only. +Never use colour alone to carry state: pair it with a glyph (● ○ ◐ ▲ ✕ ▶) or a word. + +## 2. Type (Segoe UI Variable, fallback Segoe UI; `FontSize` keys) + +`Text.PageTitle` 18/600 · `Text.Title` 16/600 · `Text.Section` 14/600 · `Text.Body` 13/400 +· `Text.Secondary` 12/400 muted · `Text.Chip` 11/400. Line heights 24/22/20/18/16/14. +Numbers in tables use tabular figures (`Typography.NumeralAlignment="Tabular"`). +Layout must survive +40 % text width (de, fi): no fixed-width labels, `MinWidth` only. + +## 3. Spacing, radii, sizes + +Spacing scale 4 · 8 · 12 · 16 · 20 (`Thickness` keys `Space.1`…`Space.5`). +Radii: 6 controls · 8 cards/panels · 12 pills · 12 modal dialogs. +Controls 32 px tall, 44 px minimum width, 12 px horizontal padding; compact row buttons 26–28 px. +Rail 128 px (collapses to 48 px icons); title bar 34; job bar 40; toolbar 56; status bar 30; +table rows 36–40 (52 in the web admin); side panels 320 px; settings section list 200 px. +Label column left of controls: 116 px in panels, 180 px in Settings. + +## 4. Controls and states (see `Components.html`) + +- **Button**: Card fill, Stroke border. Hover +6 % lightness, pressed −6 %, focus = 2 px + Accent ring outside. **Primary** (Accent fill, OnAccent text, 600) — one per screen. + **Destructive** = Warning outline, transparent fill, never a primary. **Subtle** = no border + until hover. **Toggled** = Accent text + Accent border. **Disabled** = 40 % opacity and the + tooltip says why. Icon-only buttons carry `AutomationProperties.Name` and a tooltip. +- **Inputs**: Card fill, Stroke border, Accent border on focus, Error border when invalid with + the message in the tooltip (never a line of text under the field). Enter commits, Esc reverts. +- **Slider — Auto/manual** (brief §10.4): Auto state = Accent track, dimmed thumb, an `Auto · 41` + pill at the right whose tooltip gives the advisor's reason; touching it turns the track Sun + (manual), shows the value, and a `⟲` reset button returns to Auto. Not applicable = greyed + value "n/a" with the reason in its tooltip. +- **Status glyphs**: `●` green Analysed · `○` faint Not analysed · `●` Proxies · `▶ n` rendered + · `●` accent Synced/Remote · `◐` amber Analysing · `▲ n` warnings · `✕ n` errors. +- **Chips**: 24 px pills, Card fill, Stroke border; selected/recommended = Accent border and text. +- **Progress**: 6 px bar, Accent fill, text to the right; indeterminate = sliding highlight. +- **Tooltip**: light on dark (#F2F3F5 on dark, #1A1A1A text), 12 px, one line: action + cost + + shortcut ("Read every frame again · about 6 min · Ctrl+Shift+A"); 400 ms delay; ≤ 200 chars. + Every interactive element has one. There is no other explanatory text in the UI. +- **Dialog**: Surface fill, Stroke border, radius 12, 24 px shadow, two buttons maximum, safe + action left and default, destructive on the right with typed confirmation for formatting. +- **Toast**: bottom-right, 420 px, Card fill with a 3 px Accent left edge, one action button, + 8 s, hover pauses. Used for card insertion, render done, server messages. +- **Job bar**: 40 px strip under the title bar in every client screen: current job, progress, + time left, pause; hidden when idle only in the editor (it shows "Ready" elsewhere). +- **Rail item**: 36 px; active = Card fill + 3 px Accent left edge; badge = Accent pill with + the count of things needing attention. +- **Cards** (Library): 236 px wide, thumbnail 16:9, count badge top-right, checkbox top-left on + hover/selection, selected = Accent border + `AccentSelected` glow; hover scrubs the thumbnail. +- **Tables**: header 11 px faint, sortable; rows Card fill on hover; numbers right-aligned, + tabular; virtualised beyond 200 rows; row actions are 26 px buttons revealed on the row. + +## 5. Icons + +16 px, 1.5 px strokes, round caps and joins, `currentColor`, drawn as `PathGeometry` / +`DrawingImage` resources in `Titano.App/Icons/Icons.xaml` (source SVGs in `branding/ui-icons/` +if generated by a tool). No icon fonts, no emoji in shipped UI (the mockups use a few glyphs +only as placeholders: replace ⟳ ▾ ✕ ■ ❚❚ ≡ with drawn icons). Directional icons mirror in RTL. + +## 6. App icon (`branding/`) + +`titano.svg` is the master: 256 plate radius 56 #1A1A1E, ring r 92, 12 ticks of 12° with 18° +gaps, stroke 20 round caps, opacity 0.14 → 1.0 clockwise from 12 o'clock, sun disc at +(152,104) r 30 #F5A524. Variants: `titano-server.svg` (rack badge), `titano-uploader.svg` +(up-arrow badge), `titano-mono.svg` (white, no plate, for the tray). PNG renders at +16/32/48/64/128/256 are reference output; `Titano.Tools make-icon` must regenerate ICO/PNG +from the SVG geometry (no raster assets checked in as sources). Badges only at ≥ 48 px. + +## 7. Screen-by-screen notes (mockup → brief section) + +| Mockup | Brief | Notes | +|---|---|---| +| `Main.html` | §12.2 Library | grid/list, year·camera·status filters, selection panel | +| `Editor.html` | §12.3 Sequence editor | Exposure tab, wipe compare, curves, advisor Auto pills | +| `Export.html` | §12.3 / §11.4 | preset cards with size/time estimate, Output panel, batch | +| `Import.html` | §12.4 / §13 | card profile, sessions, plan, verification, after-import actions | +| `Archive.html` | §12.5 | tree, mass operations, stats, verify/rebuild, maintenance | +| `Jobs.html` | §12.6 | filters, queue order, expandable log, retry/open/folder | +| `Server.html` | §12.7 / §14 | connection with TOFU fingerprint, account and quota, render node, sync table, conflicts | +| `Settings.html` | §12.8 | section list, Rendering section, encoder table, self-test | +| `Welcome.html` | §12.1 | first run: local archive / adopt folder / connect; consent line; card toast | +| `Admin.html` | §14.7 | dashboard | +| `AdminUsers.html` | §14.7 | users table, roles, quotas, temporary password, render-node right | +| `Uploader.html` | §15 | single window, watch folder, queue, tray | +| `Components.html` | §12.1 | the control kit above, with hex values and state rules | +| `Icon.html` | §17 | construction, sizes, variants, wordmark | + +Missing on purpose (build from the brief and this kit): About, Login dialog, the other editor +tabs (Frames, Motion, Camera, Time, Stack), Import "Show plan", Archive rebuild dialog, the +admin Archive/Jobs/Settings/Logs pages. Reuse the shell and the kit; do not invent new colours. diff --git a/docs/ui/mockups/Admin.html b/docs/ui/mockups/Admin.html new file mode 100644 index 00000000..fe0ac6f5 --- /dev/null +++ b/docs/ui/mockups/Admin.html @@ -0,0 +1,118 @@ + + + + +Titano Server — Admin dashboard + + + +
+ +
+
+ Dashboard + up 12 d 4 h · PostgreSQL 17 · TLS auto · discovery on + + + + +
+
+
+
+ Storage + 9.4 TBof 16 TB +
+ 6.6 TB free · exports 210 GB · proxies 610 GB +
+
+ Archive + 412sequences + 618,204 photos · 14 cameras · last scan 07:12 + 3 sequences without proxies +
+
+ Jobs + 3running + 12 queued · 41 done today · 0 failed + workers 4 of 4 busy +
+
+ Render nodes + 2online + studio-pc · NVENC HEVC/H.264/AV1 · busy + laptop-alb · QSV HEVC/H.264 · idle +
+
+
+
+ Storage by year + +
+
+
Uploads · last 30 daysframes per day · 96,410 total · peak 12,400
+ +
+
+
+
+
Recent activityAll logs
+
+ 09:41alberto uploaded 1,020 frames to Construction cam · week 38 + 09:12studio-pc rendered Milan skyline dusk · 4K HEVC · 2 min 41 s + 08:55uploader roof-cam signed in from 192.168.1.44 + 08:30admin set export retention to 180 days + 07:12scheduled scan finished · 412 sequences · 0 changes + 06:00database backup · /data/backups/2026-09-30.sql.gz · 190 MB + 23:04admin created user giulia · Editor · quota 2 TB +
+
+
+ +
+ KindTargetNodeProgressState + RenderHarbour sunset → 4K 10-bit HEVCstudio-pc
62 %
running + Deep analysisConstruction cam · week 38server
28 %
running + ProxiesComet over the ridgeserver
91 %
running + VerifyArchive · 2024server
—
queued + RenderAurora, Tromsø → 1080p share H.264laptop-alb
—
queued +
+
+
+
+
+
+ + diff --git a/docs/ui/mockups/AdminUsers.html b/docs/ui/mockups/AdminUsers.html new file mode 100644 index 00000000..faffd14d --- /dev/null +++ b/docs/ui/mockups/AdminUsers.html @@ -0,0 +1,76 @@ + + + + +Titano Server — Users + + + +
+ +
+
+ Users + 6 accounts · 5 active · roles: admin, editor, uploader, viewer + + + + +
+
+
+
UserRoleQuotaLast seenUploads 30 dStatus
+
AadminAdministrator · created at first startAdmin—now · 192.168.1.100● Active
+
AalbertoAlberto · render node studio-pcEditor
2.1 of 5 TB
10:15 · client 1.3.014,208● Active
+
GgiuliaGiulia · must change passwordEditor
0.1 of 2 TB
09:20 · client 1.3.0640● Active
+
Rroof-camUploader on the roof PC · watch folderUploader
0.6 of 1 TB
08:55 · uploader 1.3.081,320● Active
+
MmarcoMarco · clientViewer—2026-09-140● Active
+
SsimoneSimone · disabled 2026-08-30Editor
0.4 of 2 TB
2026-08-290○ Disabled
+ +
Passwords: PBKDF2-SHA512, 12 characters minimum · tokens expire after 30 days idleSign-in log
+
+ +
+
+
+ + diff --git a/docs/ui/mockups/Archive.html b/docs/ui/mockups/Archive.html new file mode 100644 index 00000000..8837fc49 --- /dev/null +++ b/docs/ui/mockups/Archive.html @@ -0,0 +1,142 @@ + + + + +Titano — Archive manager + + + +
+
+ + Titano — Archive + + —▢✕ +
+
+ +
+
+
+ Verify · 6.7 of 9.4 TB · 410 MB/s · 1 h 52 min left · 0 errors + +
+
+
+ + + + + + + + + + + Last scan 2026-09-29 07:12 · 14 min +
+
+
618,204photos
+
412sequences · 1,309 loose photos
+
9.4 TBoriginals · 610 GB proxies · 1.8 GB thumbnails
+
14cameras · 9 formats
+
2019 – 2026316 rendered · 84 never rendered · 12 not analysed
+
+
+
+
Photos per month021k
+ +
+
+ Storage by year + +
+
+ By camera + +
+
+ By format + +
+
+
+
+ Index health +
Sidecars 412 / 412 · database matches the disk
+
3 sequences without proxies
+
1 sequence not verified in 90 days
+
Database 214 MB · thumbnail pack 1.8 GB · 0 orphans · 0 duplicates
+
Network root reachable · SMB · 118 MB/s read
+
+
+
Recent maintenance
+
+ 2026-09-29Verify · running71 % + 2026-09-20Verify · 9.4 TB0 errors + 2026-09-01Vacuum · 231 → 214 MBdone + 2026-08-14Rebuild index · 412 sidecarsdone + 2026-08-02Backup · D:\Backups\titano-2026-08-02.dbdone +
+
+
+
+ Filtered set + + + + + + + + + + + +
+
+
+ 412 sequences618,204 photos9.4 TBConnected to "Studio NAS"1 job +
+
+
+
+ + diff --git a/docs/ui/mockups/Components.html b/docs/ui/mockups/Components.html new file mode 100644 index 00000000..7dfa392c --- /dev/null +++ b/docs/ui/mockups/Components.html @@ -0,0 +1,193 @@ + + + + +Titano — UI kit + + + +
+
+ COLOURS · CLIENT (DARK, DEFAULT) +
+
Bg #1F1F23
+
Chrome #1A1A1E
+
Surface #26262C
+
Card #2F3038
+
Stroke #3E404A
+
Text #F2F3F5
+
Muted #A9AEB9
+
Faint #7B818E
+
Accent #4CC2FF
+
On accent #0B1B24
+
Sun #F5A524
+
Success #35C48F
+
Warning #E8B339
+
Error #F0625D
+
+ Region teal #5AD1C8 only for sky/landscape masks · one accent per screen · never colour alone: pair with a shape or a word +
+
+ COLOURS · LIGHT THEME & WEB ADMIN +
+
Bg #F3F3F3
+
Card #FFFFFF
+
Stroke #E5E5E5
+
Text #1A1A1A
+
Muted #616161
+
Accent #0067C0
+
+ Selected nav #E8F1FA · sun #E08A1E · success #0F7B4F · warning #9A6700 · error #C42B1C +
+
+ TYPE · SPACING · RADII + Page title 18 / 600 + Sequence title 16 / 600 + Section 14 / 600 + Body and controls 13 / 400 + Secondary 12 / 400 muted + Chips and axis labels 11 / 400 +
+ + 4 · 8 · 12 · 16 · 20 px + + 6 control · 8 card · 12 pill +
+
+
+ BUTTONS · 32 PX · MIN WIDTH 44 +
+ + + +
+
+ + + + +
+
+ + +
+ Hover +6 % lightness · pressed −6 % · focus ring 2 px accent outside · every button has a tooltip +
+
+ INPUTS · SELECTION + +
+ + + +
+ +
+ + + + + +
+ Labels left of the control, 116 px column · placeholder never replaces a label · Enter commits, Esc reverts +
+
+ SLIDERS · AUTO / MANUAL +
+
+ +
+
+
0.80
+ +
+
Colour temperaturen/a
+ Accent track = Auto · sun track = manual · greyed with reason = not applicable · values edit on double-click +
+
+ STATUS · PROGRESS · TOOLTIP +
+ ● Analysed○ Not analysed● Proxies▶ 2 rendered● Synced● Remote◐ Analysing▲ 1 warning✕ 2 errors +
+
+ sunset ✕ + holy grail ✕ + Recommended +
+
Determinate 6 px · text to the right, never inside
+
Indeterminate: sliding highlight
+
+ +
Read every frame again and refresh the analysis · about 6 min · Ctrl+Shift+A
+
+ Tooltip: one line, action + cost + shortcut · shows after 400 ms · light on dark +
+
+ DIALOG · DESTRUCTIVE CONFIRM +
+ Format EOS R5 · card A? + 4,812 photos were copied and verified. Formatting removes everything on the card. + +
+ + +
+
+ Two buttons max · safe action left and default · destructive never primary · Esc = safe +
+
+ TOAST · JOB BAR · RAIL +
+ + EOS R5 · card A inserted4,812 photos · 96.2 GB · 3 sessions + + +
+
+
+ Building proxies · 1,240 / 3,600 · 3 min left + +
+
+
+ Library + Import + Jobs2 +
+ Rail 128 px, collapses to 48 px icons · active = card fill + 3 px accent edge · badge = count needing attention · toast bottom-right, 8 s, hover pauses +
+
+
+ EMPTY STATE · SEQUENCE CARD · TABLE ROW +
+
+ + No sequences yet +
+ + + +
+
+
+
+
3,600
+
Harbour sunsetCanon EOS R5 · 2 h 00 m
● Analysed● Proxies▶ 2
+
+ Selected card: accent border + glow · thumbnail is the first analysed keyframe, hover scrubs +
+
+
SequenceCameraFramesState
+
Harbour sunsetCanon EOS R53,600● ok
+
Comet over the ridgeGoPro HERO81,005▲ 1
+
Aurora, TromsøNikon Z 81,860● sync
+ Rows 36 px · hover = card fill · numbers right-aligned in real tables · sortable headers · virtualised past 200 rows +
+
+
+
+ + diff --git a/docs/ui/mockups/Editor.html b/docs/ui/mockups/Editor.html new file mode 100644 index 00000000..3e013a8f --- /dev/null +++ b/docs/ui/mockups/Editor.html @@ -0,0 +1,114 @@ + + + + +Titano — Sequence editor + + + +
+
+ + Titano — Harbour sunset + + —▢✕ +
+
+ +
+
+ ← + Harbour sunset + 3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings + + + + +
+
+
+
+
+
+
+
original | corrected
+
+ + + + + + +
+
0413 / 3,600 · 18:02:11 · 1/8 s · f/8 · ISO 400 · 24 mm
+
+
+
▼▼▼▼
+
+
+
+
+
+ + + + + + + +
+
+
— measured luminance— target curve- - sky region▼ exposure steps as receivedflicker −67 % · max step 0.21 EV
+ +
+
+ +
+
+
+
+ + diff --git a/docs/ui/mockups/Export.html b/docs/ui/mockups/Export.html new file mode 100644 index 00000000..16814484 --- /dev/null +++ b/docs/ui/mockups/Export.html @@ -0,0 +1,102 @@ + + + + +Titano — Sequence editor · Export + + + +
+
+ + Titano — Harbour sunset + + —▢✕ +
+
+ +
+
+ ← + Harbour sunset + 3,600 frames · 24 fps · 2 min 30 s · 3840×2160 source 8192×5464 + + + + +
+
+
+
+
+
+ + + +
+
0413 / 3,600 · 00:17.2 of 02:30 · output 3840×2160
+
+
+
+
+
+ + + + + + + +
+
+ + + + + + + + +
+
+ +
+
+
+
+ + diff --git a/docs/ui/mockups/Icon.html b/docs/ui/mockups/Icon.html new file mode 100644 index 00000000..b45593f5 --- /dev/null +++ b/docs/ui/mockups/Icon.html @@ -0,0 +1,80 @@ + + + + +Titano — Icon + + + +
+ + + + + + + + + + + + + + + + + + + + + + plate 256 · radius 56 · ring r 92 · stroke 20 · sun (152,104) r 30 + + 12 ticks of 12°, 18° gaps, round caps — a clock face and an intervalometer at once. + Opacity 0.14 → 1.0 clockwise from 12 o'clock: time accumulating, exposure ramping. + The sun sits off-centre, north-east, the way it does in every sunset shot. + Two colours only: accent #4CC2FF on plate #1A1A1E, sun #F5A524. No gradients, no text. + Generated by `Titano.Tools make-icon` into ICO (16–256), PNG, and the WPF DrawingImage. + + + ON DARK + + + + + + 12864483216 + + + ON LIGHT + + + + + + + VARIANTS + + + + Titano ServerTitano UploaderTray · monochrome · no plate + + WORDMARK · Segoe UI Variable Display Semibold, tracking −1 %, cap height aligned to the ring + + Titano + + Titano Server + + Titano Uploader + + Clear space around the mark: one tick length (40/256) on every side. Never rotate, recolour or add a drop shadow. + Badges only at 48 px and above; below that the Server and Uploader use the plain mark and their window title. + Installer, Store listing, GitHub social preview and the Unraid template icon all use the 256 px PNG. + + +
+ + diff --git a/docs/ui/mockups/Import.html b/docs/ui/mockups/Import.html new file mode 100644 index 00000000..3f1f14da --- /dev/null +++ b/docs/ui/mockups/Import.html @@ -0,0 +1,154 @@ + + + + +Titano — Import + + + +
+
+ + Titano — Import + + —▢✕ +
+
+ +
+
+
+ Ready · 0 jobs queued +
+
+ +
+
+ EOS R5 · card A + SD 128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431 · last import 2026-09-21 + + + +
+
+ Destination +
+ + + + + + Studio NAS +
+ Scan +
+ + + gap min + min frames + +
+ Names +
+
+ + / + + +
+ → 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2 +
+ On existing +
+ + + +
+ Convert +
+ + + + +
+ After import +
+ + + + + + +
+
+
+
+ Plan + 3 sessions · 4,812 photos · 96.2 GB · about 12 min + + 0 duplicates + 2.1 TB free after import +
+
+ SessionFrames · intervalSizeCameraSequence + 2026-09-28 · 18:02 → 20:043,600 · 2 s72.4 GBEOS R5new · 2026-09-28 Canon EOS R5 + 2026-09-27 · 05:41 → 06:571,140 · 4 s22.6 GBEOS R5new · 2026-09-27 Canon EOS R5 + 2026-09-26 · 21:10 → 23:3472 · 120 s1.2 GBEOS R5loose photos +
+ +
+ + + +
+
+
+
+
+ 412 sequences618,204 photos9.4 TBConnected to "Studio NAS"0 jobs +
+
+
+
+ + diff --git a/docs/ui/mockups/Jobs.html b/docs/ui/mockups/Jobs.html new file mode 100644 index 00000000..9a391d65 --- /dev/null +++ b/docs/ui/mockups/Jobs.html @@ -0,0 +1,80 @@ + + + + +Titano — Jobs + + + +
+
+ + Titano — Jobs + + —▢✕ +
+
+ +
+
+
+ Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left + +
+
+ + + + + + + + + + Workers 4 / 4 · GPU NVENC busy + + +
+
+
KindTargetProgressSpeedLeftWhereState
+
RenderHarbour sunset → 4K 10-bit HEVC · 24 fps
62 %
11.3 fps2 minthis PC · NVENCrunning
+
+
10:14:02 window 41 · deflicker −67 % · 3 exposure steps redistributed over 18 frames
+
10:14:03 stabilisation on · mean shake 0.42 px · crop 1.8 %
+
10:14:03 encoder NVENC HEVC Main10 · 3840×2160 · 120 Mb/s · 24 fps · GOP 48
+
10:15:41 frame 2232 / 3600 · 11.3 fps · spill 0 · memory 6.1 GB of 8 GB budget
+
+
Deep analysisConstruction cam · week 38
28 %
41 fps6 minthis PCrunning
+
UploadComet over the ridge → Studio NAS
46 %
38 MB/s4 minnetworkrunning
+
ProxiesComet over the ridge
91 %
118 fps8 sthis PCrunning
+
RenderAurora, Tromsø → 1080p share H.264
—
—after 1this PCqueued
+
VerifyArchive · 2024
—
—after 2this PCqueued
+
VerifyStar trails, Colle del Nivolet
100 %
—09:58this PCfailed · 2
+
RenderMilan skyline dusk → 4K HEVC
100 %
14.8 fps09:12studio-pcdone · 2:41
+
ImportEOS R5 · card A → Archive · 4,812 photos
100 %
410 MB/s08:41this PCdone · 11:52
+
Thumbnails2026-09-27 Sony ILCE-7M4
100 %
2,300 fps08:42this PCdone · 0:01
+ +
History keeps 90 days · 1,412 jobsFailed jobs retry automatically 3× with backoff, then wait for youRendering settings
+
+
+ 412 sequences618,204 photos9.4 TBConnected to "Studio NAS"4 jobs +
+
+
+
+ + diff --git a/docs/ui/mockups/Main.html b/docs/ui/mockups/Main.html new file mode 100644 index 00000000..ba11bd8a --- /dev/null +++ b/docs/ui/mockups/Main.html @@ -0,0 +1,101 @@ + + + + +Titano — Library + + + +
+
+ + Titano + + —▢✕ +
+
+ +
+
+
+ Building proxies · Harbour sunset · 1,240 / 3,600 · 12 fps · 3 min left + +
+
+ + + + + + + + + + + + +
+
+
+
+
Harbour sunset3,600 · Canon EOS R5 · 2 h 00 m
● Analysed● Proxies▶ 2● Synced
+
+
+
+
Comet over the ridge1,005 · GoPro HERO8 · 5 h 34 m
● Analysed● Proxies▲ 1
+
+
+
+
2026-09-27 Sony ILCE-7M42,140 · Sony A7 IV · 1 h 11 m
● Analysed○ Proxies
+
+
+
+
Aurora, Tromsø1,860 · Nikon Z 8 · 4 h 08 m
● Analysed● Proxies● Synced
+
+
+
+
Construction cam · week 388,920 · Brinno · 7 d
◐ Analysing● Remote
+
+
+
+
Milan skyline dusk2,400 · iPhone 16 Pro · 1 h 20 m
● Analysed● Proxies▶ 1
+
+
+
+
Clouds over the Langhe1,320 · Canon EOS R5 · 44 m
○ Analysed○ Proxies
+
+
+
+
Star trails, Colle del Nivolet640 · Sony A7 IV · 5 h 20 m
● Analysed● Proxies▶ 3
+
+
+
+
Fog lifting, Asti980 · DJI Osmo Action 5 · 1 h 38 m
● Analysed○ Proxies
+
+
+
+
Holy grail · Monviso1,720 · Nikon Z 8 · 3 h 02 m
● Analysed● Proxies▶ 1● Synced
+
+
+
+ 412 sequences618,204 photos9.4 TBConnected to "Studio NAS"3 jobs +
+
+
+
+ + diff --git a/docs/ui/mockups/Server.html b/docs/ui/mockups/Server.html new file mode 100644 index 00000000..f865587e --- /dev/null +++ b/docs/ui/mockups/Server.html @@ -0,0 +1,112 @@ + + + + +Titano — Server + + + +
+
+ + Titano — Server + + —▢✕ +
+
+ +
+
+
+ Upload · Comet over the ridge · 46 % · 38 MB/s · 4 min left + +
+
+
+
+
+ + + + +
+
+ Status + Connected + ·Studio NAS · v1.3.0 · 14 ms + ·TLS 9A:3C:71:E0:… trusted 2026-09-01 + +
+
+ Account + A + alberto·Editor· +
2.1 TB of 5 TB + + + +
+
+ + NVENC HEVC · H.264 · AV1 + + + +
+
+
+
Render nodeBusy
+ Rendering Harbour sunset → 4K 10-bit HEVC for the server · 62 % · 11.3 fps +
+
Today3 jobs · 41 min GPU timeQueue1 waiting on the serverAvailabilitywhen idle for 2 min · never on battery
+ +
Node settings
+
+
+
+
+ Sequences + + + + + + + + +
+
SequenceThis PCServerState
+
Holy grail · Monvisooriginals · proxiesoriginals · proxies▲ settings differ
+
Harbour sunsetoriginals · proxiesoriginals · proxies● in sync
rendering on this PC as a node
+
Comet over the ridgeoriginals · proxies46 % received● uploading
+
Clouds over the Langheoriginals—local only
+
Construction cam · week 38proxiesoriginals · proxies● remote
+
Aurora, Tromsøoriginals · proxiesoriginals · proxies● in sync
+
Star trails, Colle del Nivoletoriginals · proxiesoriginals · proxies · 3 exports● in sync
+
Milan skyline dusk—originals · proxies · 1 export● remote
+ +
Last sync 10:15 · manifest diff 0.4 sServer archive 9.4 TB · 412 sequences · 6 usersOpen admin panel
+
+
+
+ 418 sequences640,118 photos9.4 TBConnected to "Studio NAS"2 jobs +
+
+
+
+ + diff --git a/docs/ui/mockups/Settings.html b/docs/ui/mockups/Settings.html new file mode 100644 index 00000000..6991a8d5 --- /dev/null +++ b/docs/ui/mockups/Settings.html @@ -0,0 +1,83 @@ + + + + +Titano — Settings + + + +
+
+ + Titano — Settings + + —▢✕ +
+
+ +
+
+ + + General + Archive + Import + Analysis + Rendering + Formats + Server + Updates + Licence + Advanced + + + +
+
+
RenderingChanges apply to the next job
+
+ Quality profile +
Best · Balanced · Fast
+ +
8 GBof 32 GB installed
+ Cache folder +
1.4 GB used · SSD · 612 GB free
+ Parallelism +
of 16 logical cores
+ Hardware encoding +
+
+
+
Encoders on this PCNVIDIA GeForce RTX 4070 · driver 560.94 · Media Foundation 10.0.26100
+
+
CodecEncoder10-bitMaxSelf-testUsed for
+
HEVCNVIDIA NVENC (hardware)Main108192×8192✓ 142 fps · ok4K archive · 4K HEVC · 1440p · cinema
+
H.264NVIDIA NVENC (hardware)—4096×4096✓ 188 fps · ok1080p share · social · square · 720p
+
AV1NVIDIA NVENC (hardware)10-bit8192×8192✓ 96 fps · oknot in any preset · available in Custom
+
H.264Microsoft (software)—4096×2304✓ 21 fps · okfallback for every H.264 preset
+
MJPEG · AVITitano (built in)—no limit✓ 64 fps · oklossless-ish intermediate
+
GIF · APNGTitano (built in)—1080p✓ okpreviews, social loops
+
+ Intel QSV and AMD AMF appear here on PCs that have them. HEVC and AV1 exist only as hardware encoders: without one, those presets fall back to H.264 and say so in the preset list. +
+
+
+
+
+
+ + diff --git a/docs/ui/mockups/Uploader.html b/docs/ui/mockups/Uploader.html new file mode 100644 index 00000000..653dc74e --- /dev/null +++ b/docs/ui/mockups/Uploader.html @@ -0,0 +1,70 @@ + + + + +Titano Uploader + + + +
+
+ + Titano Uploader + + —✕ +
+
+ + https://nas.local:8443 + · + alberto + · + Connected + + 1.9 TB free of 5 TB + +
+
+
+ + Drop photos, folders or a card here + +
+
+ Target + + + + +
+
+ Queue + 4,812 files · 96.2 GB · 38 MB/s · 41 min left + + + + Limit MB/s +
+
+
+
2026-09-28_18-02-11_0413.CR22,214 of 4,812 sent · 2,201 verified by the server · 0 retries
+
+
+ Watch folders + D:\Cam\Roof · every 60 s + \\garage-pi\cam · every 5 min + +
+ +
+ + + +
+
+
+ + diff --git a/docs/ui/mockups/Welcome.html b/docs/ui/mockups/Welcome.html new file mode 100644 index 00000000..83c9d379 --- /dev/null +++ b/docs/ui/mockups/Welcome.html @@ -0,0 +1,81 @@ + + + + +Titano — First run + + + +
+
+ + Titano + + —▢✕ +
+
+ +
+
Ready
+
+ + Year ▾ + Camera ▾ + Status ▾ +
+
No sequences yet
+
0 sequences0 photosNo archiveNot connected
+
+
+
+
+
+ + Welcome to TitanoWhere should your time-lapses live? + +
+
+ + + +
+
+ + + +
+
+
+ + New card inserted · SD 128 GBCanon EOS R5 · 4,812 photos · not yet known to Titano + + +
+
+ + diff --git a/global.json b/global.json new file mode 100644 index 00000000..d46d21e5 --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature", + "allowPrerelease": false + } +} diff --git a/i18n/en/Shell.resx b/i18n/en/Shell.resx new file mode 100644 index 00000000..dd4fb457 --- /dev/null +++ b/i18n/en/Shell.resx @@ -0,0 +1,10 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Titano + {0:N0} photo + {0:N0} photos + diff --git a/i18n/it/Shell.it.resx b/i18n/it/Shell.it.resx new file mode 100644 index 00000000..7d948680 --- /dev/null +++ b/i18n/it/Shell.it.resx @@ -0,0 +1,9 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + {0:N0} foto + {0:N0} foto + diff --git a/src/Titano.App/App.xaml b/src/Titano.App/App.xaml new file mode 100644 index 00000000..fa7e5103 --- /dev/null +++ b/src/Titano.App/App.xaml @@ -0,0 +1,4 @@ + + diff --git a/src/Titano.App/App.xaml.cs b/src/Titano.App/App.xaml.cs new file mode 100644 index 00000000..83019998 --- /dev/null +++ b/src/Titano.App/App.xaml.cs @@ -0,0 +1,7 @@ +using System.Windows; + +namespace Titano.App; + +public partial class App : Application +{ +} diff --git a/src/Titano.App/Titano.App.csproj b/src/Titano.App/Titano.App.csproj new file mode 100644 index 00000000..5b3bf883 --- /dev/null +++ b/src/Titano.App/Titano.App.csproj @@ -0,0 +1,21 @@ + + + WinExe + net10.0-windows + true + Titano.App + Titano + app.manifest + titano + + + + + + + + + + + + diff --git a/src/Titano.App/app.manifest b/src/Titano.App/app.manifest new file mode 100644 index 00000000..aa6ecd8b --- /dev/null +++ b/src/Titano.App/app.manifest @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2, PerMonitor + true + + + + + + + + diff --git a/src/Titano.Core.Windows/Titano.Core.Windows.csproj b/src/Titano.Core.Windows/Titano.Core.Windows.csproj new file mode 100644 index 00000000..a70192ff --- /dev/null +++ b/src/Titano.Core.Windows/Titano.Core.Windows.csproj @@ -0,0 +1,13 @@ + + + net10.0-windows + Titano.Core.Windows + + + + + + + + + diff --git a/src/Titano.Core.Windows/WindowsPlatform.cs b/src/Titano.Core.Windows/WindowsPlatform.cs new file mode 100644 index 00000000..c7dcd4a1 --- /dev/null +++ b/src/Titano.Core.Windows/WindowsPlatform.cs @@ -0,0 +1,7 @@ +namespace Titano.Core.Windows; + +/// Windows-only providers (WIC, Media Foundation, DXGI, devices). +public static class WindowsPlatform +{ + public static bool IsSupported => OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17763); +} diff --git a/src/Titano.Core/Branding/BrandMark.cs b/src/Titano.Core/Branding/BrandMark.cs new file mode 100644 index 00000000..f7a15f02 --- /dev/null +++ b/src/Titano.Core/Branding/BrandMark.cs @@ -0,0 +1,204 @@ +namespace Titano.Core.Branding; + +public enum BrandVariant +{ + /// Titano desktop client: plate, ring, sun. + App, + + /// Titano Server: App mark plus the three-bar rack badge (≥ 48 px). + Server, + + /// Titano Uploader: App mark plus the up-arrow badge (≥ 48 px). + Uploader, + + /// White mark without plate, for the tray. + Mono, +} + +/// +/// The time-lapse aperture-clock mark (BRIEF §17, DESIGN §6), defined as geometry on a 256-unit canvas +/// and rasterised with analytic anti-aliasing from signed distance fields. Single source of truth for +/// the ICO/PNG sets, the admin favicon and the WPF DrawingImage. +/// +public static class BrandMark +{ + public const double Canvas = 256; + public const double PlateRadius = 56; + public const double RingRadius = 92; + public const double StrokeWidth = 20; + public const int TickCount = 12; + public const double TickSweepDegrees = 12; + public const double TickPitchDegrees = 30; + public const double FirstTickStartDegrees = 9; + public const double SunX = 152, SunY = 104, SunRadius = 30; + + public static readonly Rgb Plate = new(0x1A, 0x1A, 0x1E); + public static readonly Rgb Accent = new(0x4C, 0xC2, 0xFF); + public static readonly Rgb Sun = new(0xF5, 0xA5, 0x24); + public static readonly Rgb White = new(0xFF, 0xFF, 0xFF); + + /// Opacity of tick (0 = first clockwise from 12 o'clock). + public static double TickOpacity(int i) => Math.Round(0.14 + (1.0 - 0.14) * i / (TickCount - 1), 2); + + /// Start and end angle of tick in degrees, clockwise from 12 o'clock. + public static (double Start, double End) TickAngles(int i) + { + var start = FirstTickStartDegrees + i * TickPitchDegrees; + return (start, start + TickSweepDegrees); + } + + /// Renders the mark as straight-alpha RGBA8 (row-major, top-down). + public static byte[] Render(BrandVariant variant, int size) + { + ArgumentOutOfRangeException.ThrowIfLessThan(size, 8); + var scale = size / Canvas; + // Below 32 px the stroke would vanish; keep it at least ~1.3 px wide. + var stroke = Math.Max(StrokeWidth, 1.3 / scale); + var badge = size >= 48 && variant is BrandVariant.Server or BrandVariant.Uploader; + var ringColor = variant == BrandVariant.Mono ? White : Accent; + var sunColor = variant == BrandVariant.Mono ? White : Sun; + + var pixels = new byte[size * size * 4]; + var px = 1.0 / scale; // one pixel in canvas units + for (var y = 0; y < size; y++) + { + for (var x = 0; x < size; x++) + { + var cx = (x + 0.5) * px; + var cy = (y + 0.5) * px; + var c = new Rgba(0, 0, 0, 0); + + if (variant != BrandVariant.Mono) + c = Over(c, Plate, Coverage(RoundedBox(cx, cy, 0, 0, Canvas, Canvas, PlateRadius), px)); + + for (var i = 0; i < TickCount; i++) + { + var (a0, a1) = TickAngles(i); + var d = ArcStroke(cx, cy, 128, 128, RingRadius, a0, a1, stroke); + if (d < px) c = Over(c, ringColor, Coverage(d, px) * TickOpacity(i)); + } + + c = Over(c, sunColor, Coverage(Circle(cx, cy, SunX, SunY, SunRadius), px)); + + if (badge) + { + var badgeColor = variant == BrandVariant.Server ? Accent : Sun; + // Badge disc in plate colour with a 6-unit outline. + c = Over(c, Plate, Coverage(Circle(cx, cy, 204, 204, 43), px)); + c = Over(c, badgeColor, Coverage(Math.Abs(Circle(cx, cy, 204, 204, 40)) - 3, px)); + if (variant == BrandVariant.Server) + { + c = Over(c, badgeColor, Coverage(RoundedBox(cx, cy, 185, 188, 38, 12, 4), px)); + c = Over(c, badgeColor, Coverage(RoundedBox(cx, cy, 185, 208, 38, 12, 4), px)); + } + else + { + var arrow = Math.Min( + Segment(cx, cy, 204, 226, 204, 186), + Math.Min(Segment(cx, cy, 188, 202, 204, 186), Segment(cx, cy, 204, 186, 220, 202))) - 4; + c = Over(c, badgeColor, Coverage(arrow, px)); + } + } + + var o = (y * size + x) * 4; + pixels[o] = ToByte(c.R); + pixels[o + 1] = ToByte(c.G); + pixels[o + 2] = ToByte(c.B); + pixels[o + 3] = ToByte(c.A); + } + } + return pixels; + } + + /// The master SVG for a variant (identical geometry to ). + public static string ToSvg(BrandVariant variant) + { + var inv = System.Globalization.CultureInfo.InvariantCulture; + var sb = new System.Text.StringBuilder(); + sb.Append("\n"); + var ring = variant == BrandVariant.Mono ? "#ffffff" : Accent.Hex; + if (variant != BrandVariant.Mono) sb.Append("\n"); + for (var i = 0; i < TickCount; i++) + { + var (a0, a1) = TickAngles(i); + var (x0, y0) = Polar(a0); + var (x1, y1) = Polar(a1); + sb.Append(inv, $"\n"); + } + sb.Append("\n"); + if (variant == BrandVariant.Server) + sb.Append("\n"); + if (variant == BrandVariant.Uploader) + sb.Append("\n"); + sb.Append("\n"); + return sb.ToString(); + } + + /// Point on the ring at clockwise from 12 o'clock. + public static (double X, double Y) Polar(double degrees, double radius = RingRadius) + { + var a = degrees * Math.PI / 180; + return (128 + radius * Math.Sin(a), 128 - radius * Math.Cos(a)); + } + + private static double Coverage(double signedDistance, double pixel) => Math.Clamp(0.5 - signedDistance / pixel, 0, 1); + + private static double Circle(double x, double y, double cx, double cy, double r) => Math.Sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) - r; + + private static double RoundedBox(double x, double y, double left, double top, double w, double h, double r) + { + var hx = w / 2 - r; + var hy = h / 2 - r; + var qx = Math.Abs(x - (left + w / 2)) - hx; + var qy = Math.Abs(y - (top + h / 2)) - hy; + var outside = Math.Sqrt(Math.Max(qx, 0) * Math.Max(qx, 0) + Math.Max(qy, 0) * Math.Max(qy, 0)); + return outside + Math.Min(Math.Max(qx, qy), 0) - r; + } + + private static double Segment(double x, double y, double ax, double ay, double bx, double by) + { + double px = x - ax, py = y - ay, dx = bx - ax, dy = by - ay; + var t = Math.Clamp((px * dx + py * dy) / (dx * dx + dy * dy), 0, 1); + var ex = px - dx * t; + var ey = py - dy * t; + return Math.Sqrt(ex * ex + ey * ey); + } + + private static double ArcStroke(double x, double y, double cx, double cy, double r, double startDeg, double endDeg, double width) + { + var dx = x - cx; + var dy = y - cy; + var angle = Math.Atan2(dx, -dy) * 180 / Math.PI; + if (angle < 0) angle += 360; + double d; + if (angle >= startDeg && angle <= endDeg) + { + d = Math.Abs(Math.Sqrt(dx * dx + dy * dy) - r); + } + else + { + var (sx, sy) = Polar(startDeg, r); + var (ex, ey) = Polar(endDeg, r); + d = Math.Min(Math.Sqrt((x - sx) * (x - sx) + (y - sy) * (y - sy)), Math.Sqrt((x - ex) * (x - ex) + (y - ey) * (y - ey))); + } + return d - width / 2; + } + + private static Rgba Over(Rgba dst, Rgb src, double alpha) + { + if (alpha <= 0) return dst; + var a = alpha + dst.A * (1 - alpha); + if (a <= 0) return new Rgba(0, 0, 0, 0); + double Mix(double s, double d) => (s * alpha + d * dst.A * (1 - alpha)) / a; + return new Rgba(Mix(src.R / 255.0, dst.R), Mix(src.G / 255.0, dst.G), Mix(src.B / 255.0, dst.B), a); + } + + private static byte ToByte(double v) => (byte)Math.Clamp((int)Math.Round(v * 255), 0, 255); + + private readonly record struct Rgba(double R, double G, double B, double A); + + public readonly record struct Rgb(byte R, byte G, byte B) + { + public string Hex => $"#{R:x2}{G:x2}{B:x2}"; + } +} diff --git a/src/Titano.Core/Codecs/Ico/IcoWriter.cs b/src/Titano.Core/Codecs/Ico/IcoWriter.cs new file mode 100644 index 00000000..e0586938 --- /dev/null +++ b/src/Titano.Core/Codecs/Ico/IcoWriter.cs @@ -0,0 +1,78 @@ +using System.Buffers.Binary; +using Titano.Core.Codecs.Png; + +namespace Titano.Core.Codecs.Ico; + +/// +/// Writes Windows ICO files. Sizes ≥ 64 px are stored as PNG; smaller sizes as 32-bit DIBs with an AND +/// mask, which every shell version renders crisply. +/// +public static class IcoWriter +{ + /// Straight-alpha RGBA8 square images keyed by size. + public static byte[] Write(IReadOnlyList<(int Size, byte[] Rgba)> images) + { + var payloads = images.Select(i => i.Size >= 64 + ? PngEncoder.Encode(i.Rgba, i.Size, i.Size, PngColorType.Rgba) + : Dib(i.Rgba, i.Size)).ToList(); + + using var ms = new MemoryStream(); + Span header = stackalloc byte[6]; + BinaryPrimitives.WriteUInt16LittleEndian(header, 0); + BinaryPrimitives.WriteUInt16LittleEndian(header[2..], 1); + BinaryPrimitives.WriteUInt16LittleEndian(header[4..], (ushort)images.Count); + ms.Write(header); + + var offset = 6 + 16 * images.Count; + Span entry = stackalloc byte[16]; + for (var i = 0; i < images.Count; i++) + { + var size = images[i].Size; + entry.Clear(); + entry[0] = (byte)(size >= 256 ? 0 : size); + entry[1] = (byte)(size >= 256 ? 0 : size); + BinaryPrimitives.WriteUInt16LittleEndian(entry[4..], 1); + BinaryPrimitives.WriteUInt16LittleEndian(entry[6..], 32); + BinaryPrimitives.WriteInt32LittleEndian(entry[8..], payloads[i].Length); + BinaryPrimitives.WriteInt32LittleEndian(entry[12..], offset); + ms.Write(entry); + offset += payloads[i].Length; + } + foreach (var p in payloads) ms.Write(p); + return ms.ToArray(); + } + + private static byte[] Dib(byte[] rgba, int size) + { + var maskStride = ((size + 31) / 32) * 4; + var data = new byte[40 + size * size * 4 + maskStride * size]; + var span = data.AsSpan(); + BinaryPrimitives.WriteInt32LittleEndian(span, 40); + BinaryPrimitives.WriteInt32LittleEndian(span[4..], size); + BinaryPrimitives.WriteInt32LittleEndian(span[8..], size * 2); // XOR + AND masks + BinaryPrimitives.WriteUInt16LittleEndian(span[12..], 1); + BinaryPrimitives.WriteUInt16LittleEndian(span[14..], 32); + BinaryPrimitives.WriteInt32LittleEndian(span[20..], size * size * 4); + var o = 40; + for (var y = size - 1; y >= 0; y--) + { + for (var x = 0; x < size; x++) + { + var s = (y * size + x) * 4; + data[o++] = rgba[s + 2]; + data[o++] = rgba[s + 1]; + data[o++] = rgba[s]; + data[o++] = rgba[s + 3]; + } + } + for (var y = size - 1; y >= 0; y--) + { + for (var x = 0; x < size; x++) + { + if (rgba[(y * size + x) * 4 + 3] == 0) data[o + (x >> 3)] |= (byte)(0x80 >> (x & 7)); + } + o += maskStride; + } + return data; + } +} diff --git a/src/Titano.Core/Codecs/Png/PngEncoder.cs b/src/Titano.Core/Codecs/Png/PngEncoder.cs new file mode 100644 index 00000000..6c9273fc --- /dev/null +++ b/src/Titano.Core/Codecs/Png/PngEncoder.cs @@ -0,0 +1,133 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Hashing; + +namespace Titano.Core.Codecs.Png; + +/// PNG colour types written by . +public enum PngColorType : byte +{ + Gray = 0, + Rgb = 2, + GrayAlpha = 4, + Rgba = 6, +} + +/// PNG encoder (8/16-bit, gray/RGB with or without alpha), adaptive filtering, zlib via the BCL. +public static class PngEncoder +{ + private static ReadOnlySpan Signature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + /// Encodes interleaved pixels. 16-bit samples are big-endian in . + public static byte[] Encode(ReadOnlySpan pixels, int width, int height, PngColorType colorType, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize) + { + using var ms = new MemoryStream(); + Encode(ms, pixels, width, height, colorType, bitDepth, level); + return ms.ToArray(); + } + + public static void Encode(Stream output, ReadOnlySpan pixels, int width, int height, PngColorType colorType, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null) + { + if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth)); + var channels = colorType switch + { + PngColorType.Gray => 1, + PngColorType.GrayAlpha => 2, + PngColorType.Rgb => 3, + _ => 4, + }; + var bpp = channels * bitDepth / 8; + var stride = width * bpp; + if (pixels.Length < stride * height) throw new ArgumentException("Pixel buffer too small", nameof(pixels)); + + output.Write(Signature); + Span ihdr = stackalloc byte[13]; + BinaryPrimitives.WriteInt32BigEndian(ihdr, width); + BinaryPrimitives.WriteInt32BigEndian(ihdr[4..], height); + ihdr[8] = (byte)bitDepth; + ihdr[9] = (byte)colorType; + ihdr[10] = 0; + ihdr[11] = 0; + ihdr[12] = 0; + WriteChunk(output, "IHDR", ihdr); + + if (extraChunks is not null) + { + foreach (var (type, data) in extraChunks) WriteChunk(output, type, data); + } + + WriteChunk(output, "IDAT", Compress(pixels, height, stride, bpp, level)); + WriteChunk(output, "IEND", []); + } + + /// Filters every row (adaptive, minimum sum of absolute differences) and deflates the result. + public static byte[] Compress(ReadOnlySpan pixels, int height, int stride, int bpp, CompressionLevel level) + { + using var ms = new MemoryStream(); + using (var z = new ZLibStream(ms, level, leaveOpen: true)) + { + var filtered = new byte[stride + 1]; + var best = new byte[stride + 1]; + for (var y = 0; y < height; y++) + { + var row = pixels.Slice(y * stride, stride); + var prev = y > 0 ? pixels.Slice((y - 1) * stride, stride) : default; + var bestScore = long.MaxValue; + for (byte f = 0; f <= 4; f++) + { + filtered[0] = f; + long score = 0; + for (var i = 0; i < stride; i++) + { + int a = i >= bpp ? row[i - bpp] : 0; + int b = y > 0 ? prev[i] : 0; + int c = i >= bpp && y > 0 ? prev[i - bpp] : 0; + var v = f switch + { + 0 => row[i], + 1 => row[i] - a, + 2 => row[i] - b, + 3 => row[i] - ((a + b) >> 1), + _ => row[i] - Paeth(a, b, c), + }; + var bv = (byte)v; + filtered[i + 1] = bv; + score += bv < 128 ? bv : 256 - bv; + } + if (score < bestScore) + { + bestScore = score; + filtered.CopyTo(best, 0); + } + } + z.Write(best); + } + } + return ms.ToArray(); + } + + public static void WriteChunk(Stream output, string type, ReadOnlySpan data) + { + Span header = stackalloc byte[8]; + BinaryPrimitives.WriteInt32BigEndian(header, data.Length); + for (var i = 0; i < 4; i++) header[4 + i] = (byte)type[i]; + output.Write(header); + output.Write(data); + var crc = new Crc32(); + crc.Append(header[4..]); + crc.Append(data); + Span trailer = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(trailer, crc.GetCurrentHashAsUInt32()); + output.Write(trailer); + } + + internal static int Paeth(int a, int b, int c) + { + var p = a + b - c; + var pa = Math.Abs(p - a); + var pb = Math.Abs(p - b); + var pc = Math.Abs(p - c); + if (pa <= pb && pa <= pc) return a; + return pb <= pc ? b : c; + } +} diff --git a/src/Titano.Core/Diagnostics/Log.cs b/src/Titano.Core/Diagnostics/Log.cs new file mode 100644 index 00000000..0aa6da57 --- /dev/null +++ b/src/Titano.Core/Diagnostics/Log.cs @@ -0,0 +1,116 @@ +using System.Globalization; + +namespace Titano.Core.Diagnostics; + +public enum LogLevel +{ + Trace, + Debug, + Info, + Warning, + Error, +} + +/// Destination for engine log events (file logger on desktop, ILogger bridge on the server). +public interface ILogSink +{ + void Write(LogLevel level, string category, string message, Exception? exception); +} + +/// Tiny engine-wide logger. Core code logs through it; hosts plug in a sink. +public static class Log +{ + private static ILogSink _sink = new ConsoleSink(); + + public static LogLevel MinimumLevel { get; set; } = LogLevel.Info; + + public static void SetSink(ILogSink sink) => _sink = sink ?? throw new ArgumentNullException(nameof(sink)); + + public static void Debug(string category, string message) => Write(LogLevel.Debug, category, message, null); + public static void Info(string category, string message) => Write(LogLevel.Info, category, message, null); + public static void Warning(string category, string message, Exception? ex = null) => Write(LogLevel.Warning, category, message, ex); + public static void Error(string category, string message, Exception? ex = null) => Write(LogLevel.Error, category, message, ex); + + public static void Write(LogLevel level, string category, string message, Exception? exception) + { + if (level < MinimumLevel) return; + try + { + _sink.Write(level, category, message, exception); + } + catch (IOException) + { + // Logging must never take the process down. + } + } + + private sealed class ConsoleSink : ILogSink + { + public void Write(LogLevel level, string category, string message, Exception? exception) + { + var line = string.Create(CultureInfo.InvariantCulture, $"{DateTime.UtcNow:O} {level,-7} {category}: {message}"); + if (exception is not null) line += Environment.NewLine + exception; + Console.Error.WriteLine(line); + } + } +} + +/// Appends log lines to rotating files (one per day, kept for retainDays). +public sealed class FileLogSink : ILogSink, IDisposable +{ + private readonly string _directory; + private readonly string _prefix; + private readonly int _retainDays; + private readonly Lock _gate = new(); + private StreamWriter? _writer; + private DateOnly _day; + + public FileLogSink(string directory, string prefix, int retainDays = 14) + { + _directory = directory; + _prefix = prefix; + _retainDays = retainDays; + Directory.CreateDirectory(directory); + } + + public string CurrentPath => Path.Combine(_directory, $"{_prefix}-{_day:yyyyMMdd}.log"); + + public void Write(LogLevel level, string category, string message, Exception? exception) + { + lock (_gate) + { + var today = DateOnly.FromDateTime(DateTime.UtcNow); + if (_writer is null || today != _day) + { + _writer?.Dispose(); + _day = today; + _writer = new StreamWriter(new FileStream(CurrentPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { AutoFlush = true }; + Prune(); + } + _writer.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{DateTime.UtcNow:O} {level,-7} {category}: {message}")); + if (exception is not null) _writer.WriteLine(exception.ToString()); + } + } + + private void Prune() + { + foreach (var file in Directory.EnumerateFiles(_directory, _prefix + "-*.log")) + { + if (File.GetLastWriteTimeUtc(file) < DateTime.UtcNow.AddDays(-_retainDays)) + { + try + { + File.Delete(file); + } + catch (IOException) + { + } + } + } + } + + public void Dispose() + { + lock (_gate) _writer?.Dispose(); + } +} diff --git a/src/Titano.Core/Hashing/Crc32.cs b/src/Titano.Core/Hashing/Crc32.cs new file mode 100644 index 00000000..65504080 --- /dev/null +++ b/src/Titano.Core/Hashing/Crc32.cs @@ -0,0 +1,47 @@ +namespace Titano.Core.Hashing; + +/// CRC-32 (IEEE 802.3, reflected 0xEDB88320) as used by PNG, ZIP and gzip. Slicing-by-8. +public sealed class Crc32 +{ + private static readonly uint[] Table = BuildTable(); + private uint _crc = 0xFFFFFFFFu; + + public void Append(ReadOnlySpan data) => _crc = Update(_crc, data); + + public uint GetCurrentHashAsUInt32() => ~_crc; + + public void Reset() => _crc = 0xFFFFFFFFu; + + public static uint Compute(ReadOnlySpan data) => ~Update(0xFFFFFFFFu, data); + + private static uint Update(uint crc, ReadOnlySpan data) + { + var t = Table; + var i = 0; + for (; i + 8 <= data.Length; i += 8) + { + var one = (uint)(data[i] | data[i + 1] << 8 | data[i + 2] << 16 | data[i + 3] << 24) ^ crc; + var two = (uint)(data[i + 4] | data[i + 5] << 8 | data[i + 6] << 16 | data[i + 7] << 24); + crc = t[7 * 256 + (one & 0xFF)] ^ t[6 * 256 + ((one >> 8) & 0xFF)] ^ t[5 * 256 + ((one >> 16) & 0xFF)] ^ t[4 * 256 + (one >> 24)] + ^ t[3 * 256 + (two & 0xFF)] ^ t[2 * 256 + ((two >> 8) & 0xFF)] ^ t[256 + ((two >> 16) & 0xFF)] ^ t[two >> 24]; + } + for (; i < data.Length; i++) crc = t[(crc ^ data[i]) & 0xFF] ^ (crc >> 8); + return crc; + } + + private static uint[] BuildTable() + { + var t = new uint[8 * 256]; + for (uint n = 0; n < 256; n++) + { + var c = n; + for (var k = 0; k < 8; k++) c = (c & 1) != 0 ? 0xEDB88320u ^ (c >> 1) : c >> 1; + t[n] = c; + } + for (var s = 1; s < 8; s++) + { + for (var n = 0; n < 256; n++) t[s * 256 + n] = t[(s - 1) * 256 + n] >> 8 ^ t[t[(s - 1) * 256 + n] & 0xFF]; + } + return t; + } +} diff --git a/src/Titano.Core/IO/AtomicFile.cs b/src/Titano.Core/IO/AtomicFile.cs new file mode 100644 index 00000000..ed8e7b8b --- /dev/null +++ b/src/Titano.Core/IO/AtomicFile.cs @@ -0,0 +1,81 @@ +using System.Text; + +namespace Titano.Core.IO; + +/// +/// Crash-safe writes: content goes to a temporary sibling, is flushed to disk, then renamed over the +/// target (BRIEF §7 "temp → fsync → rename"). +/// +public static class AtomicFile +{ + public static void WriteAllBytes(string path, ReadOnlySpan content) + { + var temp = TempPathFor(path); + try + { + using (var fs = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.WriteThrough)) + { + fs.Write(content); + fs.Flush(flushToDisk: true); + } + File.Move(temp, path, overwrite: true); + } + catch + { + TryDelete(temp); + throw; + } + } + + public static void WriteAllText(string path, string content) => WriteAllBytes(path, new UTF8Encoding(false).GetBytes(content)); + + /// Streams content produced by and commits it atomically. + public static async Task WriteAsync(string path, Func write, CancellationToken cancellationToken = default) + { + var temp = TempPathFor(path); + try + { + await using (var fs = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous)) + { + await write(fs, cancellationToken).ConfigureAwait(false); + await fs.FlushAsync(cancellationToken).ConfigureAwait(false); + fs.Flush(flushToDisk: true); + } + File.Move(temp, path, overwrite: true); + } + catch + { + TryDelete(temp); + throw; + } + } + + /// Commits an already-written temporary file over after flushing it. + public static void Commit(string tempPath, string path) + { + using (var fs = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + fs.Flush(flushToDisk: true); + File.Move(tempPath, path, overwrite: true); + } + + public static string TempPathFor(string path) + { + var dir = Path.GetDirectoryName(Path.GetFullPath(path)) ?? "."; + Directory.CreateDirectory(dir); + return Path.Combine(dir, "." + Path.GetFileName(path) + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp"); + } + + private static void TryDelete(string path) + { + try + { + if (File.Exists(path)) File.Delete(path); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } +} diff --git a/src/Titano.Core/IO/LongPath.cs b/src/Titano.Core/IO/LongPath.cs new file mode 100644 index 00000000..8d3cbb5b --- /dev/null +++ b/src/Titano.Core/IO/LongPath.cs @@ -0,0 +1,23 @@ +namespace Titano.Core.IO; + +/// Helpers for UNC and long paths on Windows network archives (BRIEF §7). +public static class LongPath +{ + /// Adds the \\?\ prefix on Windows when a path exceeds MAX_PATH. + public static string Normalize(string path) + { + if (!OperatingSystem.IsWindows()) return path; + var full = Path.GetFullPath(path); + if (full.Length < 248 || full.StartsWith(@"\\?\", StringComparison.Ordinal)) return full; + return full.StartsWith(@"\\", StringComparison.Ordinal) + ? @"\\?\UNC\" + full[2..] + : @"\\?\" + full; + } + + /// Relative path with forward slashes, as stored in sidecars and the database. + public static string ToPortableRelative(string root, string path) => + Path.GetRelativePath(root, path).Replace('\\', '/'); + + public static string FromPortableRelative(string root, string relative) => + Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar)); +} diff --git a/src/Titano.Core/Imaging/Decoding.cs b/src/Titano.Core/Imaging/Decoding.cs new file mode 100644 index 00000000..98f5f519 --- /dev/null +++ b/src/Titano.Core/Imaging/Decoding.cs @@ -0,0 +1,112 @@ +namespace Titano.Core.Imaging; + +/// How a frame's pixels were obtained (BRIEF §8.2). Logged per frame. +public enum DecodeTier +{ + /// Full-resolution decode of the main image (in-house or WIC). + Native = 1, + + /// Largest embedded JPEG preview; output resolution is capped to its size. + EmbeddedPreview = 2, + + /// No decoder could produce pixels; the frame is excluded from renders. + Unavailable = 3, +} + +public enum DecodePurpose +{ + Thumbnail, + Analysis, + Proxy, + Render, +} + +/// A request to decode one file. +/// Absolute path of the source file. +/// Maximum long edge of the result in pixels; 0 = native size. +/// Lets providers trade quality for speed (e.g. bilinear demosaic for thumbnails). +/// Rotate/flip according to the Exif orientation. +/// Accept the embedded-preview tier when native decode is impossible. +/// Use the embedded preview even when native decode is possible (fast paths). +public sealed record DecodeRequest( + string Path, + int MaxLongEdge = 0, + DecodePurpose Purpose = DecodePurpose.Render, + bool ApplyOrientation = true, + bool AllowPreview = true, + bool ForcePreview = false); + +/// Decoded pixels plus how they were produced. Dispose to return the buffer to the pool. +public sealed class DecodedImage(ImageBuffer pixels, DecodeTier tier, string decoder, int sourceWidth, int sourceHeight) : IDisposable +{ + public ImageBuffer Pixels { get; } = pixels; + public DecodeTier Tier { get; } = tier; + + /// Short provider/decoder name for logs ("wic", "managed-jpeg", "managed-dng"). + public string Decoder { get; } = decoder; + + /// Dimensions of the full-resolution source (before scaling), oriented. + public int SourceWidth { get; } = sourceWidth; + + public int SourceHeight { get; } = sourceHeight; + + public void Dispose() => Pixels.Dispose(); +} + +/// A platform image decoder (WIC on Windows, managed codecs everywhere). +public interface IImageDecoderProvider +{ + /// Short name for logs and the Settings › Formats table. + string Name { get; } + + /// The best tier this provider can deliver for the format on this machine, or null. + DecodeTier? TierFor(ImageFileFormat format); + + bool CanDecode(ImageFormatInfo format) => TierFor(format.Format) is not null; + + /// Decodes or returns null when this provider cannot handle the specific file. + DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default); +} + +/// Tries providers in priority order and applies the tier rules of BRIEF §8.2. +public sealed class ImageDecoder(IReadOnlyList providers) +{ + public IReadOnlyList Providers { get; } = providers; + + /// Best tier available for across all providers. + public DecodeTier TierFor(ImageFileFormat format) + { + var best = DecodeTier.Unavailable; + foreach (var p in Providers) + { + if (p.TierFor(format) is { } t && t < best) best = t; + } + return best; + } + + /// Decodes with the first provider that succeeds; null means . + public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) + { + var format = ImageFormatInfo.FromPath(request.Path); + List? errors = null; + foreach (var provider in Providers.OrderBy(p => p.TierFor(format.Format) ?? DecodeTier.Unavailable)) + { + if (provider.TierFor(format.Format) is null) continue; + cancellationToken.ThrowIfCancellationRequested(); + try + { + var result = provider.Decode(request, cancellationToken); + if (result is not null) return result; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) when (ex is IOException or InvalidDataException or NotSupportedException or FormatException or InvalidOperationException or System.Runtime.InteropServices.COMException) + { + (errors ??= []).Add(ex); + } + } + return null; + } +} diff --git a/src/Titano.Core/Imaging/ImageBuffer.cs b/src/Titano.Core/Imaging/ImageBuffer.cs new file mode 100644 index 00000000..4e78ebfc --- /dev/null +++ b/src/Titano.Core/Imaging/ImageBuffer.cs @@ -0,0 +1,74 @@ +using System.Buffers; + +namespace Titano.Core.Imaging; + +/// +/// Planar 32-bit float image in linear light (Rec.709/sRGB primaries). Channel 0..2 = R, G, B +/// (or a single luminance channel). Nominal range 0..1; highlights may exceed 1. +/// Storage is rented from and returned on . +/// +public sealed class ImageBuffer : IDisposable +{ + private float[]? _data; + + public ImageBuffer(int width, int height, int channels = 3, bool clear = true) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (channels is not (1 or 3 or 4)) throw new ArgumentOutOfRangeException(nameof(channels), "1, 3 or 4 channels"); + Width = width; + Height = height; + Channels = channels; + var length = checked(width * height * channels); + _data = ArrayPool.Shared.Rent(length); + if (clear) Array.Clear(_data, 0, length); + } + + public int Width { get; } + public int Height { get; } + public int Channels { get; } + public int PlaneLength => Width * Height; + + /// All planes, channel-major: plane c starts at c * Width * Height. + public Span Data => Storage.AsSpan(0, PlaneLength * Channels); + + public Span Plane(int channel) + { + if ((uint)channel >= (uint)Channels) throw new ArgumentOutOfRangeException(nameof(channel)); + return Storage.AsSpan(channel * PlaneLength, PlaneLength); + } + + public Span Row(int channel, int y) => Plane(channel).Slice(y * Width, Width); + + public float this[int channel, int x, int y] + { + get => Storage[channel * PlaneLength + y * Width + x]; + set => Storage[channel * PlaneLength + y * Width + x] = value; + } + + /// Underlying array (may be longer than the image). Exposed for SIMD kernels. + public float[] Storage => _data ?? throw new ObjectDisposedException(nameof(ImageBuffer)); + + public ImageBuffer Clone() + { + var copy = new ImageBuffer(Width, Height, Channels, clear: false); + Data.CopyTo(copy.Data); + return copy; + } + + public void CopyTo(ImageBuffer target) + { + if (target.Width != Width || target.Height != Height || target.Channels != Channels) + throw new ArgumentException("Dimensions differ", nameof(target)); + Data.CopyTo(target.Data); + } + + /// Approximate managed memory held by the buffer, in bytes. + public long ByteSize => (long)PlaneLength * Channels * sizeof(float); + + public void Dispose() + { + var data = Interlocked.Exchange(ref _data, null); + if (data is not null) ArrayPool.Shared.Return(data); + } +} diff --git a/src/Titano.Core/Imaging/ImageFileFormat.cs b/src/Titano.Core/Imaging/ImageFileFormat.cs new file mode 100644 index 00000000..aceda4d7 --- /dev/null +++ b/src/Titano.Core/Imaging/ImageFileFormat.cs @@ -0,0 +1,109 @@ +namespace Titano.Core.Imaging; + +/// Container/file formats recognised by signature and extension (BRIEF §8.1). +public enum ImageFileFormat +{ + Unknown = 0, + Jpeg, + Png, + Tiff, + Dng, + Cr2, + Cr3, + Crw, + Nef, + Nrw, + Arw, + Srf, + Sr2, + Raf, + Orf, + Rw2, + Raw, + Pef, + Srw, + ThreeFr, + Fff, + Iiq, + Rwl, + Gpr, + Heif, + Avif, + WebP, + JpegXl, + JpegXr, + Bmp, + Gif, +} + +public enum ImageFamily +{ + Unknown, + Jpeg, + Png, + Tiff, + Dng, + CameraRaw, + Heif, + WebP, + Other, +} + +/// Static facts about a format: family, extensions, whether it is a camera RAW. +public sealed record ImageFormatInfo(ImageFileFormat Format, ImageFamily Family, IReadOnlyList Extensions) +{ + public bool IsRaw => Family is ImageFamily.CameraRaw or ImageFamily.Dng; + + private static readonly ImageFormatInfo[] All = + [ + new(ImageFileFormat.Jpeg, ImageFamily.Jpeg, ["jpg", "jpeg", "jpe", "jfif"]), + new(ImageFileFormat.Png, ImageFamily.Png, ["png"]), + new(ImageFileFormat.Tiff, ImageFamily.Tiff, ["tif", "tiff"]), + new(ImageFileFormat.Dng, ImageFamily.Dng, ["dng"]), + new(ImageFileFormat.Cr2, ImageFamily.CameraRaw, ["cr2"]), + new(ImageFileFormat.Cr3, ImageFamily.CameraRaw, ["cr3"]), + new(ImageFileFormat.Crw, ImageFamily.CameraRaw, ["crw"]), + new(ImageFileFormat.Nef, ImageFamily.CameraRaw, ["nef"]), + new(ImageFileFormat.Nrw, ImageFamily.CameraRaw, ["nrw"]), + new(ImageFileFormat.Arw, ImageFamily.CameraRaw, ["arw"]), + new(ImageFileFormat.Srf, ImageFamily.CameraRaw, ["srf"]), + new(ImageFileFormat.Sr2, ImageFamily.CameraRaw, ["sr2"]), + new(ImageFileFormat.Raf, ImageFamily.CameraRaw, ["raf"]), + new(ImageFileFormat.Orf, ImageFamily.CameraRaw, ["orf"]), + new(ImageFileFormat.Rw2, ImageFamily.CameraRaw, ["rw2"]), + new(ImageFileFormat.Raw, ImageFamily.CameraRaw, ["raw"]), + new(ImageFileFormat.Pef, ImageFamily.CameraRaw, ["pef"]), + new(ImageFileFormat.Srw, ImageFamily.CameraRaw, ["srw"]), + new(ImageFileFormat.ThreeFr, ImageFamily.CameraRaw, ["3fr"]), + new(ImageFileFormat.Fff, ImageFamily.CameraRaw, ["fff"]), + new(ImageFileFormat.Iiq, ImageFamily.CameraRaw, ["iiq"]), + new(ImageFileFormat.Rwl, ImageFamily.CameraRaw, ["rwl"]), + new(ImageFileFormat.Gpr, ImageFamily.CameraRaw, ["gpr"]), + new(ImageFileFormat.Heif, ImageFamily.Heif, ["heic", "heif", "hif"]), + new(ImageFileFormat.Avif, ImageFamily.Heif, ["avif"]), + new(ImageFileFormat.WebP, ImageFamily.WebP, ["webp"]), + new(ImageFileFormat.JpegXl, ImageFamily.Other, ["jxl"]), + new(ImageFileFormat.JpegXr, ImageFamily.Other, ["jxr", "wdp", "hdp"]), + new(ImageFileFormat.Bmp, ImageFamily.Other, ["bmp"]), + new(ImageFileFormat.Gif, ImageFamily.Other, ["gif"]), + ]; + + private static readonly Dictionary ByExtension = + All.SelectMany(i => i.Extensions.Select(e => (e, i))).ToDictionary(p => p.e, p => p.i, StringComparer.OrdinalIgnoreCase); + + public static IReadOnlyList Known => All; + + public static ImageFormatInfo Unknown { get; } = new(ImageFileFormat.Unknown, ImageFamily.Unknown, []); + + public static ImageFormatInfo Of(ImageFileFormat format) => All.FirstOrDefault(i => i.Format == format) ?? Unknown; + + /// Format implied by a file name's extension (signature sniffing lives in Metadata). + public static ImageFormatInfo FromPath(string path) + { + var ext = Path.GetExtension(path).TrimStart('.'); + return ByExtension.TryGetValue(ext, out var info) ? info : Unknown; + } + + /// True when the extension is one Titano imports as a photo. + public static bool IsSupportedExtension(string path) => FromPath(path).Format != ImageFileFormat.Unknown; +} diff --git a/src/Titano.Core/Localization/Languages.cs b/src/Titano.Core/Localization/Languages.cs new file mode 100644 index 00000000..349197bf --- /dev/null +++ b/src/Titano.Core/Localization/Languages.cs @@ -0,0 +1,39 @@ +using System.Globalization; + +namespace Titano.Core.Localization; + +/// Languages shipped with Titano (BRIEF §16). English is the source. +public static class Languages +{ + public static readonly IReadOnlyList Shipped = + [ + "en", "it", "de", "fr", "es", "pt-BR", "pt-PT", "nl", "pl", "cs", "sk", "hu", "ro", "sv", "da", "nb", + "fi", "ru", "uk", "tr", "el", "bg", "hr", "sl", "lt", "lv", "et", "ja", "zh-Hans", "zh-Hant", "ko", + "ar", "he", "hi", "id", "ms", "vi", "th", + ]; + + /// Languages whose UI layout is mirrored. + public static readonly IReadOnlySet RightToLeft = new HashSet(StringComparer.OrdinalIgnoreCase) { "ar", "he", "fa", "ur" }; + + /// The shipped language that best matches , falling back to English. + public static CultureInfo BestMatch(CultureInfo culture) + { + for (var c = culture; !Equals(c, CultureInfo.InvariantCulture); c = c.Parent) + { + var hit = Shipped.FirstOrDefault(s => s.Equals(c.Name, StringComparison.OrdinalIgnoreCase)); + if (hit is not null) return CultureInfo.GetCultureInfo(hit); + } + if (culture.TwoLetterISOLanguageName == "pt") return CultureInfo.GetCultureInfo("pt-PT"); + if (culture.TwoLetterISOLanguageName == "zh") return CultureInfo.GetCultureInfo("zh-Hans"); + if (culture.TwoLetterISOLanguageName is "no" or "nn") return CultureInfo.GetCultureInfo("nb"); + return CultureInfo.GetCultureInfo("en"); + } + + /// Native display name ("Italiano", "日本語"). + public static string NativeName(string code) + { + var c = CultureInfo.GetCultureInfo(code); + var name = c.NativeName; + return name.Length > 0 ? char.ToUpper(name[0], c) + name[1..] : code; + } +} diff --git a/src/Titano.Core/Localization/Loc.cs b/src/Titano.Core/Localization/Loc.cs new file mode 100644 index 00000000..feb4352c --- /dev/null +++ b/src/Titano.Core/Localization/Loc.cs @@ -0,0 +1,114 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Resources; + +namespace Titano.Core.Localization; + +/// +/// Runtime string catalog. Keys are stable identifiers of the form Area.Group.Name; the first +/// segment selects the resource file i18n/<culture>/<Area>.resx. English is the source. +/// +public static class Loc +{ + private const string BaseNamePrefix = "Titano.Core.i18n."; + private static readonly ConcurrentDictionary Managers = new(StringComparer.Ordinal); + private static CultureInfo _culture = CultureInfo.CurrentUICulture; + + /// Raised after so bound UI can refresh without restart. + public static event EventHandler? CultureChanged; + + /// Raised once per missing key (used by tests and diagnostics). + public static event Action? MissingKey; + + public static CultureInfo Culture => _culture; + + /// Text direction of the current culture. + public static bool IsRightToLeft => _culture.TextInfo.IsRightToLeft; + + public static void SetCulture(CultureInfo culture) + { + ArgumentNullException.ThrowIfNull(culture); + if (Equals(culture, _culture)) return; + _culture = culture; + CultureChanged?.Invoke(null, EventArgs.Empty); + } + + /// Returns the localized string for in the current culture. + public static string L(string key) => Get(key, _culture) ?? Missing(key); + + /// Returns the localized composite format for filled with . + public static string L(string key, params object?[] args) + { + var format = Get(key, _culture); + if (format is null) return Missing(key); + return args.Length == 0 ? format : string.Format(_culture, format, args); + } + + /// + /// Plural-aware lookup: resolves key.one, key.few, key.many or key.other + /// using CLDR rules of the current language; {0} receives the count. + /// + public static string Plural(string key, long count, params object?[] args) + { + var category = PluralRules.Select(_culture, count); + var format = Get(key + "." + PluralRules.Suffix(category), _culture) ?? Get(key + ".other", _culture); + if (format is null) return Missing(key); + var all = new object?[args.Length + 1]; + all[0] = count; + Array.Copy(args, 0, all, 1, args.Length); + return string.Format(_culture, format, all); + } + + /// Looks a key up in a specific culture (falls back to parents and English); null when absent. + public static string? Get(string key, CultureInfo culture) + { + var dot = key.IndexOf('.', StringComparison.Ordinal); + if (dot <= 0) return null; + var area = key[..dot]; + var manager = Managers.GetOrAdd(area, static a => new ResourceManager(BaseNamePrefix + a, typeof(Loc).Assembly)); + try + { + return manager.GetString(key, culture); + } + catch (MissingManifestResourceException) + { + return null; + } + } + + /// Every key and English value of an area, for tooling and the web admin export. + public static IReadOnlyDictionary GetArea(string area, CultureInfo culture) + { + var manager = Managers.GetOrAdd(area, static a => new ResourceManager(BaseNamePrefix + a, typeof(Loc).Assembly)); + var result = new Dictionary(StringComparer.Ordinal); + // Walk from invariant to specific so the most specific value wins. + var chain = new List(); + for (var c = culture; !Equals(c, CultureInfo.InvariantCulture); c = c.Parent) chain.Add(c); + chain.Add(CultureInfo.InvariantCulture); + chain.Reverse(); + foreach (var c in chain) + { + ResourceSet? set; + try + { + set = manager.GetResourceSet(c, createIfNotExists: true, tryParents: false); + } + catch (MissingManifestResourceException) + { + continue; + } + if (set is null) continue; + foreach (System.Collections.DictionaryEntry entry in set) + { + if (entry.Key is string k && entry.Value is string v) result[k] = v; + } + } + return result; + } + + private static string Missing(string key) + { + MissingKey?.Invoke(key); + return "⟦" + key + "⟧"; + } +} diff --git a/src/Titano.Core/Localization/PluralRules.cs b/src/Titano.Core/Localization/PluralRules.cs new file mode 100644 index 00000000..fd6d1926 --- /dev/null +++ b/src/Titano.Core/Localization/PluralRules.cs @@ -0,0 +1,103 @@ +using System.Globalization; + +namespace Titano.Core.Localization; + +public enum PluralCategory +{ + One, + Few, + Many, + Other, +} + +/// +/// Minimal CLDR cardinal plural rules for the shipped languages (integers only, which is all the UI needs). +/// +public static class PluralRules +{ + public static string Suffix(PluralCategory c) => c switch + { + PluralCategory.One => "one", + PluralCategory.Few => "few", + PluralCategory.Many => "many", + _ => "other", + }; + + public static PluralCategory Select(CultureInfo culture, long count) + { + var n = Math.Abs(count); + var lang = culture.TwoLetterISOLanguageName; + long mod10 = n % 10, mod100 = n % 100; + switch (lang) + { + // No plural distinction. + case "ja" or "zh" or "ko" or "vi" or "th" or "id" or "ms": + return PluralCategory.Other; + + // one: 0 and 1. + case "fr" or "hi": + return n is 0 or 1 ? PluralCategory.One : PluralCategory.Other; + + case "pt" when culture.Name.Equals("pt-BR", StringComparison.OrdinalIgnoreCase): + return n is 0 or 1 ? PluralCategory.One : PluralCategory.Other; + + // East Slavic. + case "ru" or "uk": + if (mod10 == 1 && mod100 != 11) return PluralCategory.One; + if (mod10 is >= 2 and <= 4 && mod100 is < 12 or > 14) return PluralCategory.Few; + return PluralCategory.Many; + + case "pl": + if (n == 1) return PluralCategory.One; + if (mod10 is >= 2 and <= 4 && mod100 is < 12 or > 14) return PluralCategory.Few; + return PluralCategory.Many; + + case "cs" or "sk": + if (n == 1) return PluralCategory.One; + if (n is >= 2 and <= 4) return PluralCategory.Few; + return PluralCategory.Other; + + case "hr" or "sr" or "bs": + if (mod10 == 1 && mod100 != 11) return PluralCategory.One; + if (mod10 is >= 2 and <= 4 && mod100 is < 12 or > 14) return PluralCategory.Few; + return PluralCategory.Other; + + case "sl": + if (mod100 == 1) return PluralCategory.One; + if (mod100 == 2) return PluralCategory.Few; // CLDR "two", folded into few + if (mod100 is 3 or 4) return PluralCategory.Few; + return PluralCategory.Other; + + case "lt": + if (mod10 == 1 && mod100 is < 11 or > 19) return PluralCategory.One; + if (mod10 is >= 2 and <= 9 && mod100 is < 11 or > 19) return PluralCategory.Few; + return PluralCategory.Other; + + case "lv": + if (mod10 == 0 || mod100 is >= 11 and <= 19) return PluralCategory.Many; // CLDR "zero" + if (mod10 == 1 && mod100 != 11) return PluralCategory.One; + return PluralCategory.Other; + + case "ro": + if (n == 1) return PluralCategory.One; + if (n == 0 || mod100 is >= 2 and <= 19) return PluralCategory.Few; + return PluralCategory.Other; + + case "ar": + if (n == 1) return PluralCategory.One; + if (n == 2) return PluralCategory.Few; // CLDR "two", folded + if (mod100 is >= 3 and <= 10) return PluralCategory.Few; + if (mod100 is >= 11 and <= 99) return PluralCategory.Many; + return PluralCategory.Other; + + case "he": + if (n == 1) return PluralCategory.One; + if (n == 2) return PluralCategory.Few; // CLDR "two", folded + return PluralCategory.Other; + + // Default Germanic/Romance rule: one for exactly 1. + default: + return n == 1 ? PluralCategory.One : PluralCategory.Other; + } + } +} diff --git a/src/Titano.Core/Metadata/FrameMetadata.cs b/src/Titano.Core/Metadata/FrameMetadata.cs new file mode 100644 index 00000000..e38d2714 --- /dev/null +++ b/src/Titano.Core/Metadata/FrameMetadata.cs @@ -0,0 +1,71 @@ +using Titano.Core.Imaging; +using Titano.Core.Model; + +namespace Titano.Core.Metadata; + +public enum PreviewKind +{ + Thumbnail, + Preview, + FullSize, +} + +/// An embedded JPEG inside a RAW/TIFF/HEIF/JPEG(MPF) container. +public sealed record EmbeddedPreview(long Offset, long Length, int Width, int Height, PreviewKind Kind); + +public sealed record GpsPosition(double Latitude, double Longitude, double? Altitude, DateTime? UtcTimestamp); + +/// Everything Titano reads from one photo's metadata (BRIEF §9). Never throws while parsing: +/// malformed input yields partial data plus . +public sealed record FrameMetadata +{ + public ImageFileFormat Format { get; init; } + public string? Make { get; init; } + public string? Model { get; init; } + public string? BodySerial { get; init; } + public string? LensModel { get; init; } + public string? Software { get; init; } + public string? Artist { get; init; } + public string? Copyright { get; init; } + + /// Camera wall-clock time including sub-seconds (DateTimeKind.Unspecified). + public DateTime? CapturedAt { get; init; } + + public int? UtcOffsetMinutes { get; init; } + public TimestampSource TimestampSource { get; init; } + public double? ExposureTime { get; init; } + public double? FNumber { get; init; } + public int? Iso { get; init; } + public double? FocalLength { get; init; } + public double? FocalLength35 { get; init; } + public double? ExposureBias { get; init; } + public int? ExposureProgram { get; init; } + public int? MeteringMode { get; init; } + public int? WhiteBalanceMode { get; init; } + public int? ColorTemperature { get; init; } + public int? Flash { get; init; } + + /// Exif orientation 1–8. + public int Orientation { get; init; } = 1; + + /// Dimensions of the main (largest) image as stored, before orientation. + public int Width { get; init; } + + public int Height { get; init; } + public int? BitsPerSample { get; init; } + public GpsPosition? Gps { get; init; } + public int? Rating { get; init; } + public string? Label { get; init; } + public long? ShutterCount { get; init; } + public bool? ImageStabilization { get; init; } + + /// Embedded JPEGs, largest first. + public IReadOnlyList Previews { get; init; } = []; + + public IReadOnlyList Warnings { get; init; } = []; + + /// Width/height after applying orientation 5–8 (90° rotations). + public (int Width, int Height) OrientedSize => Orientation is >= 5 and <= 8 ? (Height, Width) : (Width, Height); + + public EmbeddedPreview? LargestPreview => Previews.Count > 0 ? Previews[0] : null; +} diff --git a/src/Titano.Core/Metadata/Tiff/TiffReader.cs b/src/Titano.Core/Metadata/Tiff/TiffReader.cs new file mode 100644 index 00000000..112a5874 --- /dev/null +++ b/src/Titano.Core/Metadata/Tiff/TiffReader.cs @@ -0,0 +1,251 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Titano.Core.Metadata.Tiff; + +/// One IFD entry. Small values (≤ 4 bytes) are inline; larger ones live at . +public readonly record struct IfdEntry(ushort Tag, TiffType Type, uint Count, uint ValueOffset, long EntryPosition) +{ + public long ByteLength => (long)Count * TiffTypeInfo.Size(Type); + public bool IsInline => ByteLength <= 4; + + /// Absolute file position of the value bytes (inline values sit inside the entry). + public long ValuePosition(long tiffBase) => IsInline ? EntryPosition + 8 : tiffBase + ValueOffset; +} + +/// An image file directory: its entries and the offset of the next IFD (0 = none). +public sealed class Ifd(long position, IReadOnlyDictionary entries, uint nextOffset) +{ + public long Position { get; } = position; + public IReadOnlyDictionary Entries { get; } = entries; + public uint NextOffset { get; } = nextOffset; + public bool Has(ushort tag) => Entries.ContainsKey(tag); +} + +/// +/// Fuzz-safe TIFF structure reader over a seekable stream. Reads only the bytes it needs (never the whole +/// file), validates every offset against the stream length, caps entry counts and detects IFD loops. +/// Also used for TIFF structures embedded at a base offset (Exif APP1, RAF, CR3 CMT boxes, MakerNotes). +/// +public sealed class TiffReader +{ + public const int MaxEntriesPerIfd = 4096; + public const int MaxIfdChain = 64; + public const long MaxValueBytes = 64L * 1024 * 1024; + + private readonly Stream _stream; + private readonly List _warnings = []; + + private TiffReader(Stream stream, long tiffBase, bool littleEndian, uint firstIfdOffset) + { + _stream = stream; + Base = tiffBase; + LittleEndian = littleEndian; + FirstIfdOffset = firstIfdOffset; + } + + /// Absolute position of the TIFF header ("II*\0"/"MM\0*"); IFD offsets are relative to it. + public long Base { get; } + + public bool LittleEndian { get; } + public uint FirstIfdOffset { get; } + public IReadOnlyList Warnings => _warnings; + public long StreamLength => _stream.Length; + + /// Opens a TIFF header at ; null when the bytes are not a TIFF header. + /// Accepts the ORF ("IIRO"/"IIRS") and RW2 ("IIU\0") header variants. + public static TiffReader? Open(Stream stream, long tiffBase = 0) + { + if (!stream.CanSeek || tiffBase < 0 || tiffBase + 8 > stream.Length) return null; + Span h = stackalloc byte[8]; + stream.Position = tiffBase; + if (stream.ReadAtLeast(h, 8, throwOnEndOfStream: false) < 8) return null; + bool le; + if (h[0] == 'I' && h[1] == 'I') le = true; + else if (h[0] == 'M' && h[1] == 'M') le = false; + else return null; + var magic = le ? BinaryPrimitives.ReadUInt16LittleEndian(h[2..]) : BinaryPrimitives.ReadUInt16BigEndian(h[2..]); + if (magic is not (42 or 0x4F52 or 0x5352 or 0x0055)) return null; + var first = le ? BinaryPrimitives.ReadUInt32LittleEndian(h[4..]) : BinaryPrimitives.ReadUInt32BigEndian(h[4..]); + return new TiffReader(stream, tiffBase, le, first); + } + + /// Creates a reader for an IFD structure without a header (e.g. maker notes) with a known byte order. + public static TiffReader ForEmbedded(Stream stream, long tiffBase, bool littleEndian) => new(stream, tiffBase, littleEndian, 0); + + /// Reads the chain of top-level IFDs (IFD0, IFD1, …). + public IReadOnlyList ReadChain() + { + var list = new List(); + var seen = new HashSet(); + var offset = FirstIfdOffset; + while (offset != 0 && list.Count < MaxIfdChain) + { + var ifd = ReadIfd(offset, seen); + if (ifd is null) break; + list.Add(ifd); + offset = ifd.NextOffset; + } + return list; + } + + /// Reads one IFD at a base-relative offset; null if out of bounds or already visited. + public Ifd? ReadIfd(uint offset, HashSet? visited = null) + { + var pos = Base + offset; + if (pos + 2 > _stream.Length || pos < 0) + { + Warn($"IFD offset {offset} beyond end of file"); + return null; + } + if (visited is not null && !visited.Add(pos)) + { + Warn($"IFD loop at {offset}"); + return null; + } + Span two = stackalloc byte[2]; + if (!ReadAt(pos, two)) return null; + var count = U16(two); + if (count == 0 || count > MaxEntriesPerIfd) + { + Warn($"IFD at {offset} has {count} entries"); + return null; + } + var bytes = new byte[count * 12 + 4]; + var available = (int)Math.Min(bytes.Length, _stream.Length - (pos + 2)); + if (!ReadAt(pos + 2, bytes.AsSpan(0, available))) return null; + var entries = new Dictionary(count); + var complete = available / 12; + for (var i = 0; i < Math.Min(count, complete); i++) + { + var e = bytes.AsSpan(i * 12, 12); + var tag = U16(e); + var type = (TiffType)U16(e[2..]); + var n = U32(e[4..]); + var value = U32(e[8..]); + if (TiffTypeInfo.Size(type) == 0) continue; + entries.TryAdd(tag, new IfdEntry(tag, type, n, value, pos + 2 + i * 12)); + } + if (complete < count) Warn($"IFD at {offset} truncated"); + var next = available >= count * 12 + 4 ? U32(bytes.AsSpan(count * 12)) : 0u; + return new Ifd(pos, entries, next); + } + + /// Raw value bytes of an entry (bounded by ); null when invalid. + public byte[]? ReadBytes(IfdEntry e, long maxBytes = MaxValueBytes) + { + var length = e.ByteLength; + if (length <= 0 || length > maxBytes) return null; + var pos = e.ValuePosition(Base); + if (pos < 0 || pos + length > _stream.Length) + { + Warn($"Tag 0x{e.Tag:X4} value outside file"); + return null; + } + var buffer = new byte[length]; + return ReadAt(pos, buffer) ? buffer : null; + } + + public uint? GetUInt(Ifd ifd, ushort tag) => ifd.Entries.TryGetValue(tag, out var e) ? GetUInts(e) is { Length: > 0 } v ? v[0] : null : null; + + public uint[]? GetUInts(Ifd ifd, ushort tag) => ifd.Entries.TryGetValue(tag, out var e) ? GetUInts(e) : null; + + /// Integer values of BYTE/SHORT/LONG/IFD (and signed variants) entries. + public uint[]? GetUInts(IfdEntry e) + { + var raw = ReadBytes(e); + if (raw is null) return null; + var size = TiffTypeInfo.Size(e.Type); + var result = new uint[e.Count]; + for (var i = 0; i < e.Count; i++) + { + var s = raw.AsSpan(i * size); + result[i] = e.Type switch + { + TiffType.Byte or TiffType.Undefined or TiffType.Ascii => s[0], + TiffType.SByte => (uint)(sbyte)s[0], + TiffType.Short => U16(s), + TiffType.SShort => (uint)(short)U16(s), + TiffType.Long or TiffType.Ifd or TiffType.SLong => U32(s), + _ => 0, + }; + } + return result; + } + + public double? GetDouble(Ifd ifd, ushort tag) => GetDoubles(ifd, tag) is { Length: > 0 } v ? v[0] : null; + + public double[]? GetDoubles(Ifd ifd, ushort tag) => ifd.Entries.TryGetValue(tag, out var e) ? GetDoubles(e) : null; + + /// Numeric values of any numeric type as doubles (rationals divided; 0-denominator → NaN skipped as 0). + public double[]? GetDoubles(IfdEntry e) + { + var raw = ReadBytes(e); + if (raw is null) return null; + var size = TiffTypeInfo.Size(e.Type); + var result = new double[e.Count]; + for (var i = 0; i < e.Count; i++) + { + var s = raw.AsSpan(i * size); + result[i] = e.Type switch + { + TiffType.Rational => U32(s[4..]) == 0 ? 0 : (double)U32(s) / U32(s[4..]), + TiffType.SRational => (int)U32(s[4..]) == 0 ? 0 : (double)(int)U32(s) / (int)U32(s[4..]), + TiffType.Float => BitConverter.Int32BitsToSingle((int)U32(s)), + TiffType.Double => BitConverter.Int64BitsToDouble((long)U64(s)), + TiffType.Byte or TiffType.Undefined => s[0], + TiffType.SByte => (sbyte)s[0], + TiffType.Short => U16(s), + TiffType.SShort => (short)U16(s), + TiffType.Long or TiffType.Ifd => U32(s), + TiffType.SLong => (int)U32(s), + _ => 0, + }; + } + return result; + } + + /// ASCII/UTF-8 string value with trailing NULs and spaces trimmed; null when empty. + public string? GetString(Ifd ifd, ushort tag) + { + if (!ifd.Entries.TryGetValue(tag, out var e)) return null; + var raw = ReadBytes(e, 1 << 20); + if (raw is null) return null; + var end = Array.IndexOf(raw, (byte)0); + var s = Encoding.UTF8.GetString(raw, 0, end < 0 ? raw.Length : end).Trim(); + return s.Length == 0 ? null : s; + } + + /// Reads arbitrary bytes at a base-relative offset (bounds-checked). + public byte[]? ReadRelative(long offset, int length) + { + if (length <= 0 || length > MaxValueBytes) return null; + var pos = Base + offset; + if (pos < 0 || pos + length > _stream.Length) return null; + var buffer = new byte[length]; + return ReadAt(pos, buffer) ? buffer : null; + } + + public ushort U16(ReadOnlySpan s) => LittleEndian ? BinaryPrimitives.ReadUInt16LittleEndian(s) : BinaryPrimitives.ReadUInt16BigEndian(s); + public uint U32(ReadOnlySpan s) => LittleEndian ? BinaryPrimitives.ReadUInt32LittleEndian(s) : BinaryPrimitives.ReadUInt32BigEndian(s); + public ulong U64(ReadOnlySpan s) => LittleEndian ? BinaryPrimitives.ReadUInt64LittleEndian(s) : BinaryPrimitives.ReadUInt64BigEndian(s); + + public void Warn(string message) + { + if (_warnings.Count < 32) _warnings.Add(message); + } + + private bool ReadAt(long position, Span buffer) + { + try + { + _stream.Position = position; + return _stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) == buffer.Length; + } + catch (IOException ex) + { + Warn("I/O error: " + ex.Message); + return false; + } + } +} diff --git a/src/Titano.Core/Metadata/Tiff/TiffTags.cs b/src/Titano.Core/Metadata/Tiff/TiffTags.cs new file mode 100644 index 00000000..e279e5a1 --- /dev/null +++ b/src/Titano.Core/Metadata/Tiff/TiffTags.cs @@ -0,0 +1,126 @@ +namespace Titano.Core.Metadata.Tiff; + +/// Tag numbers used across TIFF, Exif, GPS and DNG. +public static class TiffTags +{ + // Baseline TIFF + public const ushort NewSubfileType = 0x00FE; + public const ushort ImageWidth = 0x0100; + public const ushort ImageLength = 0x0101; + public const ushort BitsPerSample = 0x0102; + public const ushort Compression = 0x0103; + public const ushort PhotometricInterpretation = 0x0106; + public const ushort ImageDescription = 0x010E; + public const ushort Make = 0x010F; + public const ushort Model = 0x0110; + public const ushort StripOffsets = 0x0111; + public const ushort Orientation = 0x0112; + public const ushort SamplesPerPixel = 0x0115; + public const ushort RowsPerStrip = 0x0116; + public const ushort StripByteCounts = 0x0117; + public const ushort XResolution = 0x011A; + public const ushort YResolution = 0x011B; + public const ushort PlanarConfiguration = 0x011C; + public const ushort ResolutionUnit = 0x0128; + public const ushort Software = 0x0131; + public const ushort DateTime = 0x0132; + public const ushort Artist = 0x013B; + public const ushort Predictor = 0x013D; + public const ushort TileWidth = 0x0142; + public const ushort TileLength = 0x0143; + public const ushort TileOffsets = 0x0144; + public const ushort TileByteCounts = 0x0145; + public const ushort SubIfds = 0x014A; + public const ushort ExtraSamples = 0x0152; + public const ushort SampleFormat = 0x0153; + public const ushort JpegTables = 0x015B; + public const ushort JpegInterchangeFormat = 0x0201; + public const ushort JpegInterchangeFormatLength = 0x0202; + public const ushort YCbCrSubSampling = 0x0212; + public const ushort Rating = 0x4746; + public const ushort Xmp = 0x02BC; + public const ushort Copyright = 0x8298; + public const ushort ExifIfd = 0x8769; + public const ushort GpsIfd = 0x8825; + public const ushort InteropIfd = 0xA005; + + // Exif + public const ushort ExposureTime = 0x829A; + public const ushort FNumber = 0x829D; + public const ushort ExposureProgram = 0x8822; + public const ushort IsoSpeedRatings = 0x8827; + public const ushort SensitivityType = 0x8830; + public const ushort RecommendedExposureIndex = 0x8832; + public const ushort ExifVersion = 0x9000; + public const ushort DateTimeOriginal = 0x9003; + public const ushort DateTimeDigitized = 0x9004; + public const ushort OffsetTime = 0x9010; + public const ushort OffsetTimeOriginal = 0x9011; + public const ushort OffsetTimeDigitized = 0x9012; + public const ushort ShutterSpeedValue = 0x9201; + public const ushort ApertureValue = 0x9202; + public const ushort ExposureBiasValue = 0x9204; + public const ushort MeteringMode = 0x9207; + public const ushort Flash = 0x9209; + public const ushort FocalLength = 0x920A; + public const ushort MakerNote = 0x927C; + public const ushort SubSecTime = 0x9290; + public const ushort SubSecTimeOriginal = 0x9291; + public const ushort SubSecTimeDigitized = 0x9292; + public const ushort ColorSpace = 0xA001; + public const ushort PixelXDimension = 0xA002; + public const ushort PixelYDimension = 0xA003; + public const ushort WhiteBalance = 0xA403; + public const ushort FocalLengthIn35mmFilm = 0xA405; + public const ushort BodySerialNumber = 0xA431; + public const ushort LensSpecification = 0xA432; + public const ushort LensMake = 0xA433; + public const ushort LensModel = 0xA434; + + // GPS + public const ushort GpsLatitudeRef = 0x0001; + public const ushort GpsLatitude = 0x0002; + public const ushort GpsLongitudeRef = 0x0003; + public const ushort GpsLongitude = 0x0004; + public const ushort GpsAltitudeRef = 0x0005; + public const ushort GpsAltitude = 0x0006; + public const ushort GpsTimeStamp = 0x0007; + public const ushort GpsDateStamp = 0x001D; + + // DNG + public const ushort CfaRepeatPatternDim = 0x828D; + public const ushort CfaPattern = 0x828E; + public const ushort DngVersion = 0xC612; + public const ushort DngBackwardVersion = 0xC613; + public const ushort UniqueCameraModel = 0xC614; + public const ushort CfaPlaneColor = 0xC616; + public const ushort CfaLayout = 0xC617; + public const ushort LinearizationTable = 0xC618; + public const ushort BlackLevelRepeatDim = 0xC619; + public const ushort BlackLevel = 0xC61A; + public const ushort BlackLevelDeltaH = 0xC61B; + public const ushort BlackLevelDeltaV = 0xC61C; + public const ushort WhiteLevel = 0xC61D; + public const ushort DefaultScale = 0xC61E; + public const ushort DefaultCropOrigin = 0xC61F; + public const ushort DefaultCropSize = 0xC620; + public const ushort ColorMatrix1 = 0xC621; + public const ushort ColorMatrix2 = 0xC622; + public const ushort CameraCalibration1 = 0xC623; + public const ushort CameraCalibration2 = 0xC624; + public const ushort AnalogBalance = 0xC627; + public const ushort AsShotNeutral = 0xC628; + public const ushort AsShotWhiteXy = 0xC629; + public const ushort BaselineExposure = 0xC62A; + public const ushort CameraSerialNumber = 0xC62F; + public const ushort LensInfo = 0xC630; + public const ushort ActiveArea = 0xC68D; + public const ushort CalibrationIlluminant1 = 0xC65A; + public const ushort CalibrationIlluminant2 = 0xC65B; + public const ushort OpcodeList1 = 0xC740; + public const ushort OpcodeList2 = 0xC741; + public const ushort OpcodeList3 = 0xC74E; + public const ushort ForwardMatrix1 = 0xC714; + public const ushort ForwardMatrix2 = 0xC715; + public const ushort NewRawImageDigest = 0xC7A7; +} diff --git a/src/Titano.Core/Metadata/Tiff/TiffType.cs b/src/Titano.Core/Metadata/Tiff/TiffType.cs new file mode 100644 index 00000000..fafd8605 --- /dev/null +++ b/src/Titano.Core/Metadata/Tiff/TiffType.cs @@ -0,0 +1,32 @@ +namespace Titano.Core.Metadata.Tiff; + +/// TIFF 6.0 field types (plus IFD = 13). +public enum TiffType : ushort +{ + Byte = 1, + Ascii = 2, + Short = 3, + Long = 4, + Rational = 5, + SByte = 6, + Undefined = 7, + SShort = 8, + SLong = 9, + SRational = 10, + Float = 11, + Double = 12, + Ifd = 13, +} + +public static class TiffTypeInfo +{ + /// Size in bytes of one value; 0 for unknown types. + public static int Size(TiffType type) => type switch + { + TiffType.Byte or TiffType.Ascii or TiffType.SByte or TiffType.Undefined => 1, + TiffType.Short or TiffType.SShort => 2, + TiffType.Long or TiffType.SLong or TiffType.Float or TiffType.Ifd => 4, + TiffType.Rational or TiffType.SRational or TiffType.Double => 8, + _ => 0, + }; +} diff --git a/src/Titano.Core/Model/Entities.cs b/src/Titano.Core/Model/Entities.cs new file mode 100644 index 00000000..2ba34ddc --- /dev/null +++ b/src/Titano.Core/Model/Entities.cs @@ -0,0 +1,238 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Model; + +/// A rooted folder tree that holds originals, sidecars, proxies and exports (BRIEF §7). +public sealed record Archive +{ + public required Guid Id { get; init; } + public required string Name { get; init; } + public required string RootPath { get; init; } + public string FolderTemplate { get; init; } = Naming.TemplateDefaults.Folder; + public string FileTemplate { get; init; } = Naming.TemplateDefaults.File; + public int SchemaVersion { get; init; } = 1; + public DateTimeOffset Created { get; init; } + + /// Proxy long edge in pixels; 0 = full size, -1 = proxies disabled. + public int ProxyLongEdge { get; init; } = 1920; +} + +/// One shoot: a folder of frames that becomes one project (BRIEF §5). +public sealed record Sequence +{ + public required Guid Id { get; init; } + public required Guid ArchiveId { get; init; } + public string? Title { get; init; } + + /// Folder relative to the archive root, forward slashes. + public required string Folder { get; init; } + + public string? CameraMake { get; init; } + public string? CameraModel { get; init; } + public string? CameraSerial { get; init; } + public string? Lens { get; init; } + public DateTime? FirstCapture { get; init; } + public DateTime? LastCapture { get; init; } + public int FrameCount { get; init; } + + /// Median capture interval in seconds. + public double? MedianInterval { get; init; } + + public long TotalBytes { get; init; } + public SequenceStatus Status { get; init; } + public int RenderedCount { get; init; } + public DateTimeOffset? VerifiedAt { get; init; } + public Guid? HeroFrameId { get; init; } + public IReadOnlyList Tags { get; init; } = []; + public int Rating { get; init; } + public string? Notes { get; init; } + + /// Render settings ("project") as JSON. + public string? SettingsJson { get; init; } + + /// Compact analysis summary as JSON; the full report lives in .titano/analysis.json. + public string? AnalysisJson { get; init; } + + public SequenceOrigin Origin { get; init; } + public SyncState SyncState { get; init; } + public int SettingsVersion { get; init; } + public int FramesVersion { get; init; } + public Guid? OwnerUserId { get; init; } + public int WarningCount { get; init; } + public DateTimeOffset UpdatedAt { get; init; } + + /// User title or "{date} {camera}". + public string DisplayTitle => !string.IsNullOrWhiteSpace(Title) + ? Title! + : $"{FirstCapture:yyyy-MM-dd} {CameraModel}".Trim(); +} + +/// One photo of a sequence. +public sealed record Frame +{ + public required Guid Id { get; init; } + public required Guid SequenceId { get; init; } + public required int Index { get; init; } + + /// Path relative to the archive root, forward slashes. + public required string RelativePath { get; init; } + + public required string FileName { get; init; } + public string? OriginalFileName { get; init; } + public long Size { get; init; } + + /// Lower-case hex SHA-256 of the original file. + public string? Sha256 { get; init; } + + /// Camera wall-clock time including sub-seconds (unspecified kind). + public DateTime? CapturedAt { get; init; } + + /// UTC offset of when known, in minutes. + public int? UtcOffsetMinutes { get; init; } + + public TimestampSource TimestampSource { get; init; } + public double? ExposureTime { get; init; } + public double? FNumber { get; init; } + public int? Iso { get; init; } + public double? FocalLength { get; init; } + public double? ExposureBias { get; init; } + public int? WhiteBalance { get; init; } + public int Orientation { get; init; } = 1; + public int Width { get; init; } + public int Height { get; init; } + public ImageFileFormat Format { get; init; } + public long? PreviewOffset { get; init; } + public long? PreviewLength { get; init; } + + /// Mean log2 luminance once analysed. + public double? MeanLogLuminance { get; init; } + + public double? ClipLow { get; init; } + public double? ClipHigh { get; init; } + public FrameFlags Flags { get; init; } + + /// Exposure value at ISO 100: log2(N²/t) − log2(ISO/100). + public double? ExposureValue => ExposureTime is > 0 && FNumber is > 0 + ? Math.Log2(FNumber.Value * FNumber.Value / ExposureTime.Value) - Math.Log2((Iso ?? 100) / 100.0) + : null; +} + +/// An exported video or image sequence. +public sealed record Render +{ + public required Guid Id { get; init; } + public required Guid SequenceId { get; init; } + public required string PresetName { get; init; } + public string? SettingsJson { get; init; } + public required string OutputPath { get; init; } + public string? Codec { get; init; } + public int Width { get; init; } + public int Height { get; init; } + public double Fps { get; init; } + public double DurationSeconds { get; init; } + public long Bytes { get; init; } + public DateTimeOffset Created { get; init; } + public string? ProducedBy { get; init; } +} + +/// Any long operation: resumable, cancellable, logged (BRIEF §5, §14.6). +public sealed record Job +{ + public required Guid Id { get; init; } + public required JobKind Kind { get; init; } + public IReadOnlyList TargetIds { get; init; } = []; + + /// Human-readable target ("Harbour sunset", "Archive · 2024"). + public string? TargetLabel { get; init; } + + public string? ParametersJson { get; init; } + public JobState State { get; init; } + public JobPriority Priority { get; init; } = JobPriority.Normal; + public long ProgressDone { get; init; } + public long ProgressTotal { get; init; } + public double? ItemsPerSecond { get; init; } + public TimeSpan? Eta { get; init; } + + /// Opaque resume cursor written at checkpoints. + public string? Checkpoint { get; init; } + + public string? LogTail { get; init; } + public Guid? CreatedBy { get; init; } + public string? NodeId { get; init; } + public int Attempts { get; init; } + public string? Error { get; init; } + public DateTimeOffset Created { get; init; } + public DateTimeOffset? Started { get; init; } + public DateTimeOffset? Finished { get; init; } +} + +/// A memory card known to this client (BRIEF §13). +public sealed record MediaCard +{ + public required Guid Id { get; init; } + + /// {volumeSerial}-{label}-{capacity}. + public required string Identity { get; init; } + + public uint VolumeSerial { get; init; } + public string? Label { get; init; } + public long Capacity { get; init; } + public string? Nickname { get; init; } + public string? CameraMake { get; init; } + public string? CameraModel { get; init; } + public string? CameraSerial { get; init; } + public string? ProfileJson { get; init; } + public bool AutoImport { get; init; } + public DateTimeOffset FirstSeen { get; init; } + public DateTimeOffset LastSeen { get; init; } +} + +public sealed record User +{ + public required Guid Id { get; init; } + public required string Username { get; init; } + public string? DisplayName { get; init; } + public required string PasswordHash { get; init; } + public UserRole Role { get; init; } + public Permissions Permissions { get; init; } + public long QuotaBytes { get; init; } + public long UsedBytes { get; init; } + public bool Disabled { get; init; } + public bool MustChangePassword { get; init; } + public DateTimeOffset Created { get; init; } + public DateTimeOffset? LastLogin { get; init; } +} + +public sealed record SessionToken +{ + public required string TokenHash { get; init; } + public required Guid UserId { get; init; } + public string? ClientName { get; init; } + public DateTimeOffset Created { get; init; } + public DateTimeOffset Expires { get; init; } + public DateTimeOffset LastUsed { get; init; } + public bool Revoked { get; init; } +} + +public sealed record RenderNode +{ + public required Guid Id { get; init; } + public required Guid UserId { get; init; } + public required string ClientName { get; init; } + public string? CapabilitiesJson { get; init; } + public DateTimeOffset LastHeartbeat { get; init; } + public string State { get; init; } = "idle"; +} + +public sealed record AuditEntry +{ + public required Guid Id { get; init; } + public DateTimeOffset At { get; init; } + public Guid? UserId { get; init; } + public string? Username { get; init; } + public required string Action { get; init; } + public string? TargetKind { get; init; } + public string? TargetId { get; init; } + public string? Details { get; init; } + public string? RemoteAddress { get; init; } +} diff --git a/src/Titano.Core/Model/Enums.cs b/src/Titano.Core/Model/Enums.cs new file mode 100644 index 00000000..a032754e --- /dev/null +++ b/src/Titano.Core/Model/Enums.cs @@ -0,0 +1,126 @@ +namespace Titano.Core.Model; + +/// Where a capture timestamp came from. +public enum TimestampSource +{ + Unknown = 0, + ExifOriginal, + ExifCreate, + Xmp, + QuickTime, + Gps, + FileSystem, +} + +[Flags] +public enum FrameFlags +{ + None = 0, + Missing = 1, + Corrupt = 2, + Duplicate = 4, + Excluded = 8, + PreviewOnly = 16, + Undecodable = 32, + Black = 64, + White = 128, +} + +[Flags] +public enum SequenceStatus +{ + None = 0, + AnalyzedLight = 1, + AnalyzedDeep = 2, + ProxiesBuilt = 4, + ThumbsBuilt = 8, + Verified = 16, + HasWarnings = 32, + HasErrors = 64, +} + +public enum SequenceOrigin +{ + Local, + Server, +} + +public enum SyncState +{ + LocalOnly, + InSync, + LocalAhead, + ServerAhead, + Conflict, + RemoteOnly, +} + +public enum JobKind +{ + Scan, + Rebuild, + Verify, + LightAnalyse, + DeepAnalyse, + Proxies, + Thumbs, + Render, + Import, + UploadCommit, + Maintenance, + Duplicates, + Orphans, + Adopt, + Move, +} + +public enum JobState +{ + Queued, + Running, + Paused, + Done, + Failed, + Cancelled, +} + +public enum JobPriority +{ + Background = 0, + Normal = 1, + User = 2, +} + +public enum UserRole +{ + Viewer, + Uploader, + Editor, + Admin, +} + +[Flags] +public enum Permissions : long +{ + None = 0, + Read = 1, + Upload = 2, + Edit = 4, + Delete = 8, + Render = 16, + RenderNode = 32, + ManageArchive = 64, + ManageUsers = 128, + All = Read | Upload | Edit | Delete | Render | RenderNode | ManageArchive | ManageUsers, +} + +public static class RolePermissions +{ + public static Permissions Default(UserRole role) => role switch + { + UserRole.Admin => Permissions.All, + UserRole.Editor => Permissions.Read | Permissions.Upload | Permissions.Edit | Permissions.Delete | Permissions.Render | Permissions.RenderNode, + UserRole.Uploader => Permissions.Read | Permissions.Upload, + _ => Permissions.Read, + }; +} diff --git a/src/Titano.Core/Naming/TemplateDefaults.cs b/src/Titano.Core/Naming/TemplateDefaults.cs new file mode 100644 index 00000000..23b2577d --- /dev/null +++ b/src/Titano.Core/Naming/TemplateDefaults.cs @@ -0,0 +1,8 @@ +namespace Titano.Core.Naming; + +/// Default naming templates (BRIEF §7.1). +public static class TemplateDefaults +{ + public const string Folder = "{year}/{date} {camera}"; + public const string File = "{date}_{time}_{n:0000}"; +} diff --git a/src/Titano.Core/Titano.Core.csproj b/src/Titano.Core/Titano.Core.csproj new file mode 100644 index 00000000..0a91bf3a --- /dev/null +++ b/src/Titano.Core/Titano.Core.csproj @@ -0,0 +1,11 @@ + + + net10.0 + Titano.Core + true + + + + + + diff --git a/src/Titano.Core/Video/Encoding.cs b/src/Titano.Core/Video/Encoding.cs new file mode 100644 index 00000000..e3e1bb42 --- /dev/null +++ b/src/Titano.Core/Video/Encoding.cs @@ -0,0 +1,134 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Video; + +public enum VideoCodec +{ + H264, + Hevc, + Av1, + Mjpeg, + JpegSequence, + PngSequence, + Tiff16Sequence, + LinearDngSequence, + Gif, + Apng, +} + +public enum ContainerFormat +{ + Mp4, + Avi, + ImageSequence, + Gif, + Apng, +} + +public enum RateControl +{ + Vbr, + Cbr, + Quality, +} + +public enum CodecProfile +{ + Auto, + H264Baseline, + H264Main, + H264High, + HevcMain, + HevcMain10, + Av1Main, +} + +public static class VideoCodecInfo +{ + public static ContainerFormat DefaultContainer(VideoCodec codec) => codec switch + { + VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1 => ContainerFormat.Mp4, + VideoCodec.Mjpeg => ContainerFormat.Avi, + VideoCodec.Gif => ContainerFormat.Gif, + VideoCodec.Apng => ContainerFormat.Apng, + _ => ContainerFormat.ImageSequence, + }; + + /// True for codecs every platform can produce without an OS encoder. + public static bool IsManaged(VideoCodec codec) => codec is not (VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1); + + public static string FileExtension(VideoCodec codec) => codec switch + { + VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1 => ".mp4", + VideoCodec.Mjpeg => ".avi", + VideoCodec.Gif => ".gif", + VideoCodec.Apng => ".png", + VideoCodec.JpegSequence => ".jpg", + VideoCodec.PngSequence => ".png", + VideoCodec.Tiff16Sequence => ".tif", + VideoCodec.LinearDngSequence => ".dng", + _ => ".bin", + }; +} + +/// What an encoder on this machine can do (shown in Settings › Rendering). +public sealed record EncoderCapability( + VideoCodec Codec, + string Name, + bool Hardware, + int MaxWidth, + int MaxHeight, + bool SupportsTenBit, + string? Vendor = null); + +/// Complete parameters of one encode. +public sealed record EncodeSettings +{ + public required string OutputPath { get; init; } + public required VideoCodec Codec { get; init; } + public required int Width { get; init; } + public required int Height { get; init; } + public required Rational FrameRate { get; init; } + public CodecProfile Profile { get; init; } = CodecProfile.Auto; + public int BitDepth { get; init; } = 8; + public RateControl RateControl { get; init; } = RateControl.Vbr; + + /// Average bit rate in bits per second (VBR/CBR). + public long BitRate { get; init; } + + /// 0–100 quality for , JPEG/MJPEG and GIF. + public int Quality { get; init; } = 90; + + /// Distance between key frames in frames; 0 = encoder default (≈ 1 s). + public int GopLength { get; init; } + + public int BFrames { get; init; } = 2; + public bool PreferHardware { get; init; } = true; + + /// Optional specific encoder name from . + public string? EncoderName { get; init; } +} + +/// One open encode. Frames are linear-light buffers at the output size. +public interface IVideoEncoderSession : IDisposable +{ + /// Encoder actually used ("NVIDIA NVENC H.264", "Managed MJPEG"). + string EncoderName { get; } + + bool IsHardware { get; } + + /// Appends a frame shown for ticks of a 90 kHz clock. + void WriteFrame(ImageBuffer frame, long duration90k); + + /// Flushes and closes the output. Without it, deletes the partial file. + void Complete(); +} + +/// A family of encoders (Media Foundation on Windows, managed everywhere). +public interface IVideoEncoderProvider +{ + string Name { get; } + IReadOnlyList Capabilities { get; } + bool CanEncode(EncodeSettings settings); + IVideoEncoderSession Open(EncodeSettings settings); +} diff --git a/src/Titano.Core/Video/Rational.cs b/src/Titano.Core/Video/Rational.cs new file mode 100644 index 00000000..cd2372e2 --- /dev/null +++ b/src/Titano.Core/Video/Rational.cs @@ -0,0 +1,29 @@ +using System.Globalization; + +namespace Titano.Core.Video; + +/// An exact frame rate such as 24000/1001. +public readonly record struct Rational(int Numerator, int Denominator) +{ + public double Value => (double)Numerator / Denominator; + + public static Rational Fps23976 { get; } = new(24000, 1001); + public static Rational Fps2997 { get; } = new(30000, 1001); + public static Rational Fps5994 { get; } = new(60000, 1001); + + public static Rational FromFps(double fps) + { + if (Math.Abs(fps - 23.976) < 0.01) return Fps23976; + if (Math.Abs(fps - 29.97) < 0.01) return Fps2997; + if (Math.Abs(fps - 59.94) < 0.01) return Fps5994; + if (Math.Abs(fps - Math.Round(fps)) < 1e-6) return new((int)Math.Round(fps), 1); + return new((int)Math.Round(fps * 1000), 1000); + } + + /// Duration of one frame in 90 kHz ticks (MP4 timescale used by Titano). + public long FrameTicks90k => (long)Math.Round(90000.0 * Denominator / Numerator); + + public override string ToString() => Denominator == 1 + ? Numerator.ToString(CultureInfo.InvariantCulture) + : Value.ToString("0.###", CultureInfo.InvariantCulture); +} diff --git a/src/Titano.Data/Dialect.cs b/src/Titano.Data/Dialect.cs new file mode 100644 index 00000000..4fe4f2fc --- /dev/null +++ b/src/Titano.Data/Dialect.cs @@ -0,0 +1,8 @@ +namespace Titano.Data; + +/// SQL dialect of an IDatabase. +public enum Dialect +{ + Sqlite, + Postgres, +} diff --git a/src/Titano.Data/Titano.Data.csproj b/src/Titano.Data/Titano.Data.csproj new file mode 100644 index 00000000..ee1ac377 --- /dev/null +++ b/src/Titano.Data/Titano.Data.csproj @@ -0,0 +1,13 @@ + + + net10.0 + Titano.Data + + + + + + + + + diff --git a/src/Titano.Protocol/ApiVersion.cs b/src/Titano.Protocol/ApiVersion.cs new file mode 100644 index 00000000..9eb139fd --- /dev/null +++ b/src/Titano.Protocol/ApiVersion.cs @@ -0,0 +1,8 @@ +namespace Titano.Protocol; + +/// API version negotiated through the X-Titano-Api header. +public static class ApiVersion +{ + public const int Current = 1; + public const string Header = "X-Titano-Api"; +} diff --git a/src/Titano.Protocol/Titano.Protocol.csproj b/src/Titano.Protocol/Titano.Protocol.csproj new file mode 100644 index 00000000..085fb7f3 --- /dev/null +++ b/src/Titano.Protocol/Titano.Protocol.csproj @@ -0,0 +1,6 @@ + + + net10.0 + Titano.Protocol + + diff --git a/src/Titano.Server/Admin/web/index.html b/src/Titano.Server/Admin/web/index.html new file mode 100644 index 00000000..7c26771a --- /dev/null +++ b/src/Titano.Server/Admin/web/index.html @@ -0,0 +1 @@ +Titano diff --git a/src/Titano.Server/Program.cs b/src/Titano.Server/Program.cs new file mode 100644 index 00000000..14d0787d --- /dev/null +++ b/src/Titano.Server/Program.cs @@ -0,0 +1,4 @@ +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); +app.MapGet("/health", () => Results.Ok(new { status = "ok" })); +app.Run(); diff --git a/src/Titano.Server/Titano.Server.csproj b/src/Titano.Server/Titano.Server.csproj new file mode 100644 index 00000000..804605ea --- /dev/null +++ b/src/Titano.Server/Titano.Server.csproj @@ -0,0 +1,23 @@ + + + net10.0 + Titano.Server + Titano.Server + $(TitanoIconDir)titano-server.ico + true + false + + + + + + + + + + + + + + + diff --git a/src/Titano.Setup/App.xaml b/src/Titano.Setup/App.xaml new file mode 100644 index 00000000..f0e5e815 --- /dev/null +++ b/src/Titano.Setup/App.xaml @@ -0,0 +1,4 @@ + + diff --git a/src/Titano.Setup/App.xaml.cs b/src/Titano.Setup/App.xaml.cs new file mode 100644 index 00000000..24976df3 --- /dev/null +++ b/src/Titano.Setup/App.xaml.cs @@ -0,0 +1,7 @@ +using System.Windows; + +namespace Titano.Setup; + +public partial class App : Application +{ +} diff --git a/src/Titano.Setup/Titano.Setup.csproj b/src/Titano.Setup/Titano.Setup.csproj new file mode 100644 index 00000000..4aa167fd --- /dev/null +++ b/src/Titano.Setup/Titano.Setup.csproj @@ -0,0 +1,15 @@ + + + WinExe + net10.0-windows + true + Titano.Setup + Titano.Setup + app.manifest + titano + + + + + + diff --git a/src/Titano.Setup/app.manifest b/src/Titano.Setup/app.manifest new file mode 100644 index 00000000..a25dd8ee --- /dev/null +++ b/src/Titano.Setup/app.manifest @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2, PerMonitor + true + + + + + + + + diff --git a/src/Titano.Tools/Commands/I18nCommand.cs b/src/Titano.Tools/Commands/I18nCommand.cs new file mode 100644 index 00000000..2c835d93 --- /dev/null +++ b/src/Titano.Tools/Commands/I18nCommand.cs @@ -0,0 +1,203 @@ +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using Titano.Core.Localization; + +namespace Titano.Tools.Commands; + +/// +/// i18n check: completeness of en and it, placeholder parity, length budgets and that +/// every key used in code/XAML/admin JS exists (BRIEF §16). +/// i18n export --out dir: one JSON per culture for the web admin. +/// +internal sealed partial class I18nCommand : ICommand +{ + private static readonly string[] RequiredCultures = ["en", "it"]; + private static readonly HashSet SentenceAreas = new(StringComparer.Ordinal) { "Tooltips", "Errors", "Advisor" }; + + public string Name => "i18n"; + public string Summary => "check | export --out (resource completeness and web export)"; + + public Task RunAsync(string[] args) + { + var a = new Args(args); + var sub = a.Positional.FirstOrDefault() ?? "check"; + var root = Args.RepoRoot(); + var catalog = Catalog.Load(Path.Combine(root, "i18n")); + return Task.FromResult(sub switch + { + "check" => Check(root, catalog), + "export" => Export(catalog, a.Get("out") ?? throw new ToolException("--out required")), + "missing" => Missing(catalog, a.Get("culture") ?? throw new ToolException("--culture required")), + _ => throw new ToolException($"Unknown i18n subcommand '{sub}'"), + }); + } + + private static int Check(string root, Catalog catalog) + { + var errors = new List(); + var warnings = new List(); + if (!catalog.Cultures.TryGetValue("en", out var en)) throw new ToolException("i18n/en missing"); + + foreach (var (key, entry) in en) + { + var area = key.Split('.')[0]; + if (!entry.File.Equals(area, StringComparison.Ordinal)) + errors.Add($"en: key {key} lives in {entry.File}.resx but its area is {area}"); + var limit = Limit(key, area, entry.Comment); + if (entry.Value.Length > limit) + errors.Add($"en: {key} is {entry.Value.Length} chars (budget {limit})"); + if (string.IsNullOrWhiteSpace(entry.Value)) + errors.Add($"en: {key} is empty"); + } + + foreach (var (culture, strings) in catalog.Cultures) + { + if (culture == "en") continue; + var required = RequiredCultures.Contains(culture); + var missing = 0; + foreach (var (key, entry) in en) + { + if (entry.Comment is not null && entry.Comment.Contains("invariant", StringComparison.OrdinalIgnoreCase)) continue; + if (!strings.TryGetValue(key, out var translated)) + { + if (required) errors.Add($"{culture}: missing {key}"); + else missing++; + continue; + } + var p1 = Placeholders(entry.Value); + var p2 = Placeholders(translated.Value); + if (!p1.SetEquals(p2)) + errors.Add($"{culture}: {key} placeholders {{{string.Join(",", p2)}}} differ from en {{{string.Join(",", p1)}}}"); + var area = key.Split('.')[0]; + var limit = (int)(Limit(key, area, entry.Comment) * 1.6); + if (translated.Value.Length > limit) + warnings.Add($"{culture}: {key} is {translated.Value.Length} chars (soft budget {limit})"); + } + if (missing > 0) warnings.Add($"{culture}: {missing} key(s) not translated yet"); + foreach (var key in strings.Keys.Where(k => !en.ContainsKey(k))) + errors.Add($"{culture}: orphan key {key}"); + } + + foreach (var (file, key) in UsedKeys(root)) + { + if (en.ContainsKey(key)) continue; + // Plural lookups reference the stem; any suffix satisfies them. + if (en.Keys.Any(k => k.StartsWith(key + ".", StringComparison.Ordinal) && PluralSuffix().IsMatch(k[(key.Length + 1)..]))) continue; + errors.Add($"{Path.GetRelativePath(root, file)}: unknown key {key}"); + } + + foreach (var w in warnings.Take(50)) Console.WriteLine("warning: " + w); + if (warnings.Count > 50) Console.WriteLine($"warning: … {warnings.Count - 50} more"); + foreach (var e in errors) Console.Error.WriteLine("error: " + e); + Console.WriteLine($"i18n: {en.Count} keys, {catalog.Cultures.Count} cultures, {errors.Count} error(s), {warnings.Count} warning(s)"); + return errors.Count == 0 ? 0 : 1; + } + + private static int Missing(Catalog catalog, string culture) + { + var en = catalog.Cultures["en"]; + catalog.Cultures.TryGetValue(culture, out var target); + foreach (var (key, entry) in en.OrderBy(k => k.Key, StringComparer.Ordinal)) + { + if (target is null || !target.ContainsKey(key)) Console.WriteLine($"{key}\t{entry.Value}"); + } + return 0; + } + + private static int Limit(string key, string area, string? comment) + { + if (comment is not null && comment.Contains("long", StringComparison.OrdinalIgnoreCase)) return 200; + if (SentenceAreas.Contains(area) || key.EndsWith(".Tip", StringComparison.Ordinal)) return 200; + return 30; + } + + private static int Export(Catalog catalog, string outDir) + { + Directory.CreateDirectory(outDir); + var en = catalog.Cultures["en"]; + foreach (var (culture, strings) in catalog.Cultures) + { + var merged = new SortedDictionary(StringComparer.Ordinal); + foreach (var (k, v) in en) merged[k] = strings.TryGetValue(k, out var t) ? t.Value : v.Value; + var json = JsonSerializer.Serialize(merged, new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); + File.WriteAllText(Path.Combine(outDir, culture + ".json"), json, new UTF8Encoding(false)); + } + Console.WriteLine($"Exported {catalog.Cultures.Count} cultures to {outDir}"); + return 0; + } + + private static HashSet Placeholders(string s) => + [.. PlaceholderRegex().Matches(s).Select(m => m.Groups[1].Value)]; + + /// Keys referenced from C# (L("…"), Plural("…"), Loc.Get("…")), XAML ({l:Loc …}) and admin JS (t("…")). + private static IEnumerable<(string File, string Key)> UsedKeys(string root) + { + var src = Path.Combine(root, "src"); + foreach (var file in Directory.EnumerateFiles(src, "*.*", SearchOption.AllDirectories)) + { + if (file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) + || file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) continue; + var ext = Path.GetExtension(file); + Regex? regex = ext switch + { + ".cs" => CsKeyRegex(), + ".xaml" => XamlKeyRegex(), + ".js" or ".html" => JsKeyRegex(), + _ => null, + }; + if (regex is null) continue; + var text = File.ReadAllText(file); + foreach (Match m in regex.Matches(text)) yield return (file, m.Groups[1].Value); + } + } + + [GeneratedRegex(@"\{(\d+)(?:[,:][^}]*)?\}")] + private static partial Regex PlaceholderRegex(); + + [GeneratedRegex(@"\b(?:L|Plural|Loc\.Get|LocKey)\(\s*""([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)""")] + private static partial Regex CsKeyRegex(); + + [GeneratedRegex(@"\{(?:l|loc):Loc\s+(?:Key=)?([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)")] + private static partial Regex XamlKeyRegex(); + + [GeneratedRegex(@"(?:\bt\(\s*['""]|data-i18n(?:-[a-z]+)?=['""])([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)")] + private static partial Regex JsKeyRegex(); + + [GeneratedRegex(@"^(one|few|many|other)$")] + private static partial Regex PluralSuffix(); + + internal sealed record Entry(string File, string Value, string? Comment); + + internal sealed class Catalog + { + public Dictionary> Cultures { get; } = new(StringComparer.OrdinalIgnoreCase); + + public static Catalog Load(string dir) + { + var c = new Catalog(); + foreach (var cultureDir in Directory.EnumerateDirectories(dir)) + { + var culture = Path.GetFileName(cultureDir); + var strings = new Dictionary(StringComparer.Ordinal); + foreach (var file in Directory.EnumerateFiles(cultureDir, "*.resx")) + { + var area = Path.GetFileName(file).Split('.')[0]; + var doc = XDocument.Load(file); + foreach (var data in doc.Root!.Elements("data")) + { + var name = (string?)data.Attribute("name") ?? throw new ToolException($"{file}: data without name"); + var value = (string?)data.Element("value") ?? string.Empty; + if (!strings.TryAdd(name, new Entry(area, value, (string?)data.Element("comment")))) + throw new ToolException($"{file}: duplicate key {name}"); + } + } + c.Cultures[culture] = strings; + } + foreach (var code in Languages.Shipped.Where(s => !c.Cultures.ContainsKey(s))) + c.Cultures.TryAdd(code, new Dictionary(StringComparer.Ordinal)); + return c; + } + } +} diff --git a/src/Titano.Tools/Commands/MakeIconCommand.cs b/src/Titano.Tools/Commands/MakeIconCommand.cs new file mode 100644 index 00000000..a2fbea23 --- /dev/null +++ b/src/Titano.Tools/Commands/MakeIconCommand.cs @@ -0,0 +1,51 @@ +using Titano.Core.Branding; +using Titano.Core.Codecs.Ico; +using Titano.Core.Codecs.Png; + +namespace Titano.Tools.Commands; + +/// Generates ICO/PNG sets and SVG masters from geometry. +internal sealed class MakeIconCommand : ICommand +{ + private static readonly int[] IcoSizes = [16, 20, 24, 32, 48, 64, 128, 256]; + + public string Name => "make-icon"; + public string Summary => "Generate ICO/PNG/SVG brand assets (--out dir, --svg dir to refresh masters)"; + + public Task RunAsync(string[] args) + { + var a = new Args(args); + var outDir = Path.GetFullPath(a.Get("out", Path.Combine(Args.RepoRoot(), "artifacts", "icons"))); + Directory.CreateDirectory(outDir); + + foreach (var (variant, name) in new[] + { + (BrandVariant.App, "titano"), + (BrandVariant.Server, "titano-server"), + (BrandVariant.Uploader, "titano-uploader"), + (BrandVariant.Mono, "titano-mono"), + }) + { + var images = IcoSizes.Select(s => (s, BrandMark.Render(variant, s))).ToList(); + File.WriteAllBytes(Path.Combine(outDir, name + ".ico"), IcoWriter.Write(images)); + foreach (var size in new[] { 16, 32, 48, 64, 128, 256, 512, 1024 }) + { + var rgba = BrandMark.Render(variant, size); + File.WriteAllBytes(Path.Combine(outDir, $"{name}-{size}.png"), PngEncoder.Encode(rgba, size, size, PngColorType.Rgba)); + } + File.WriteAllText(Path.Combine(outDir, name + ".svg"), BrandMark.ToSvg(variant)); + } + + if (a.Get("svg") is { } svgDir) + { + Directory.CreateDirectory(svgDir); + File.WriteAllText(Path.Combine(svgDir, "titano.svg"), BrandMark.ToSvg(BrandVariant.App)); + File.WriteAllText(Path.Combine(svgDir, "titano-server.svg"), BrandMark.ToSvg(BrandVariant.Server)); + File.WriteAllText(Path.Combine(svgDir, "titano-uploader.svg"), BrandMark.ToSvg(BrandVariant.Uploader)); + File.WriteAllText(Path.Combine(svgDir, "titano-mono.svg"), BrandMark.ToSvg(BrandVariant.Mono)); + } + + Console.WriteLine($"Icons written to {outDir}"); + return Task.FromResult(0); + } +} diff --git a/src/Titano.Tools/Commands/PackageGuardCommand.cs b/src/Titano.Tools/Commands/PackageGuardCommand.cs new file mode 100644 index 00000000..44fa2cc8 --- /dev/null +++ b/src/Titano.Tools/Commands/PackageGuardCommand.cs @@ -0,0 +1,45 @@ +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace Titano.Tools.Commands; + +/// BRIEF §19.2: no PackageReference anywhere and no restored packages in project.assets.json. +internal sealed partial class PackageGuardCommand : ICommand +{ + public string Name => "package-guard"; + public string Summary => "Fail when any project references or restores a package"; + + public Task RunAsync(string[] args) + { + var root = Args.RepoRoot(); + var failures = new List(); + foreach (var file in Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories) + .Where(f => f.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".props", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".targets", StringComparison.OrdinalIgnoreCase)) + .Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) + && !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal))) + { + var text = File.ReadAllText(file); + if (PackageReference().IsMatch(text)) failures.Add($"{Path.GetRelativePath(root, file)}: PackageReference"); + } + + foreach (var assets in Directory.EnumerateFiles(root, "project.assets.json", SearchOption.AllDirectories)) + { + using var doc = JsonDocument.Parse(File.ReadAllText(assets)); + if (doc.RootElement.TryGetProperty("libraries", out var libs)) + { + foreach (var lib in libs.EnumerateObject()) + { + if (lib.Value.TryGetProperty("type", out var type) && type.GetString() == "package") + failures.Add($"{Path.GetRelativePath(root, assets)}: restored package {lib.Name}"); + } + } + } + + foreach (var f in failures) Console.Error.WriteLine(f); + Console.WriteLine(failures.Count == 0 ? "Zero packages: OK" : $"{failures.Count} package violation(s)"); + return Task.FromResult(failures.Count == 0 ? 0 : 1); + } + + [GeneratedRegex(@"<\s*PackageReference\b", RegexOptions.IgnoreCase)] + private static partial Regex PackageReference(); +} diff --git a/src/Titano.Tools/Commands/XamlLintCommand.cs b/src/Titano.Tools/Commands/XamlLintCommand.cs new file mode 100644 index 00000000..bf4c1f2e --- /dev/null +++ b/src/Titano.Tools/Commands/XamlLintCommand.cs @@ -0,0 +1,74 @@ +using System.Xml.Linq; + +namespace Titano.Tools.Commands; + +/// +/// BRIEF §20.3 / DESIGN §4: every actionable control carries a tooltip and no visible text is a literal. +/// Elements inside ControlTemplates are template parts and exempt from the tooltip rule. +/// +internal sealed class XamlLintCommand : ICommand +{ + private static readonly HashSet Actionable = new(StringComparer.Ordinal) + { + "Button", "ToggleButton", "RepeatButton", "Slider", "ComboBox", "CheckBox", "RadioButton", "MenuItem", + "AutoSlider", "IconButton", "SplitButton", + }; + + private static readonly string[] TextAttributes = ["Content", "Text", "Header", "ToolTip", "Title", "Tag"]; + + public string Name => "xaml-lint"; + public string Summary => "Check tooltips and literal text in all XAML under src/"; + + public Task RunAsync(string[] args) + { + var root = Args.RepoRoot(); + var problems = new List(); + var files = Directory.EnumerateFiles(Path.Combine(root, "src"), "*.xaml", SearchOption.AllDirectories) + .Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) + && !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) + .ToList(); + + foreach (var file in files) + { + var doc = XDocument.Load(file, LoadOptions.SetLineInfo); + foreach (var el in doc.Descendants()) + { + var line = ((System.Xml.IXmlLineInfo)el).LineNumber; + var where = $"{Path.GetRelativePath(root, file)}:{line}"; + var name = el.Name.LocalName; + var inTemplate = el.Ancestors().Any(a => a.Name.LocalName is "ControlTemplate" or "Setter" or "Style"); + + if (Actionable.Contains(name) && !inTemplate && !HasToolTip(el) && !IsExempt(el)) + problems.Add($"{where}: <{name}> has no ToolTip"); + + foreach (var attrName in TextAttributes) + { + var attr = el.Attribute(attrName); + if (attr is null) continue; + var v = attr.Value; + if (v.Length == 0 || v.StartsWith('{')) continue; + if (attrName == "Tag" || (attrName == "Content" && inTemplate)) continue; + if (v.Any(char.IsLetter)) + problems.Add($"{where}: literal {attrName}=\"{v}\" on <{name}> (use {{l:Loc …}})"); + } + + // Literal element content such as Hello or Hi. + if (name is "TextBlock" or "Run" or "Label" or "Button" && !el.HasElements && el.Value.Any(char.IsLetter)) + problems.Add($"{where}: literal text in <{name}>"); + } + } + + foreach (var p in problems) Console.Error.WriteLine(p); + Console.WriteLine($"xaml-lint: {files.Count} file(s), {problems.Count} problem(s)"); + return Task.FromResult(problems.Count == 0 ? 0 : 1); + } + + private static bool HasToolTip(XElement el) => + el.Attribute("ToolTip") is not null + || el.Elements().Any(c => c.Name.LocalName.EndsWith(".ToolTip", StringComparison.Ordinal)) + || el.Attributes().Any(a => a.Name.LocalName == "TipKey"); + + /// Opt-out for controls whose tooltip is applied by a style (marked explicitly in XAML). + private static bool IsExempt(XElement el) => + el.Attributes().Any(a => a.Name.LocalName == "ToolTipFromStyle" && a.Value == "True"); +} diff --git a/src/Titano.Tools/ICommand.cs b/src/Titano.Tools/ICommand.cs new file mode 100644 index 00000000..b5767027 --- /dev/null +++ b/src/Titano.Tools/ICommand.cs @@ -0,0 +1,61 @@ +namespace Titano.Tools; + +internal interface ICommand +{ + string Name { get; } + string Summary { get; } + Task RunAsync(string[] args); +} + +internal sealed class ToolException(string message) : Exception(message); + +/// Minimal option parser: --key value, --flag, positional arguments. +internal sealed class Args +{ + private readonly Dictionary _options = new(StringComparer.OrdinalIgnoreCase); + + public Args(string[] args, params string[] flags) + { + for (var i = 0; i < args.Length; i++) + { + var a = args[i]; + if (a.StartsWith("--", StringComparison.Ordinal)) + { + var key = a[2..]; + if (flags.Contains(key, StringComparer.OrdinalIgnoreCase) || i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal)) + _options[key] = null; + else + _options[key] = args[++i]; + } + else + { + Positional.Add(a); + } + } + } + + public List Positional { get; } = []; + + public bool Has(string key) => _options.ContainsKey(key); + + public string? Get(string key) => _options.TryGetValue(key, out var v) ? v : null; + + public string Get(string key, string fallback) => Get(key) ?? fallback; + + public static string RepoRoot() + { + var dir = new DirectoryInfo(Directory.GetCurrentDirectory()); + while (dir is not null) + { + if (File.Exists(Path.Combine(dir.FullName, "Titano.slnx"))) return dir.FullName; + dir = dir.Parent; + } + dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null) + { + if (File.Exists(Path.Combine(dir.FullName, "Titano.slnx"))) return dir.FullName; + dir = dir.Parent; + } + throw new ToolException("Repository root (Titano.slnx) not found."); + } +} diff --git a/src/Titano.Tools/Program.cs b/src/Titano.Tools/Program.cs new file mode 100644 index 00000000..5d569615 --- /dev/null +++ b/src/Titano.Tools/Program.cs @@ -0,0 +1,34 @@ +using Titano.Tools; +using Titano.Tools.Commands; + +var commands = new ICommand[] +{ + new MakeIconCommand(), + new I18nCommand(), + new XamlLintCommand(), + new PackageGuardCommand(), +}; + +if (args.Length == 0 || args[0] is "-h" or "--help" or "help") +{ + Console.WriteLine("Titano.Tools [options]"); + foreach (var c in commands) Console.WriteLine($" {c.Name,-14} {c.Summary}"); + return args.Length == 0 ? 2 : 0; +} + +var command = commands.FirstOrDefault(c => c.Name.Equals(args[0], StringComparison.OrdinalIgnoreCase)); +if (command is null) +{ + Console.Error.WriteLine($"Unknown command '{args[0]}'. Run with --help."); + return 2; +} + +try +{ + return await command.RunAsync(args[1..]); +} +catch (ToolException ex) +{ + Console.Error.WriteLine(ex.Message); + return 2; +} diff --git a/src/Titano.Tools/Titano.Tools.csproj b/src/Titano.Tools/Titano.Tools.csproj new file mode 100644 index 00000000..167ccda0 --- /dev/null +++ b/src/Titano.Tools/Titano.Tools.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0 + Titano.Tools + Titano.Tools + + + + + + + diff --git a/src/Titano.Ui/Titano.Ui.csproj b/src/Titano.Ui/Titano.Ui.csproj new file mode 100644 index 00000000..fba00245 --- /dev/null +++ b/src/Titano.Ui/Titano.Ui.csproj @@ -0,0 +1,10 @@ + + + net10.0-windows + true + Titano.Ui + + + + + diff --git a/src/Titano.Ui/UiAssembly.cs b/src/Titano.Ui/UiAssembly.cs new file mode 100644 index 00000000..70b27ca4 --- /dev/null +++ b/src/Titano.Ui/UiAssembly.cs @@ -0,0 +1,6 @@ +namespace Titano.Ui; + +/// Shared WPF theme, controls and localization bindings for Titano desktop programs. +public static class UiAssembly +{ +} diff --git a/src/Titano.Uploader/App.xaml b/src/Titano.Uploader/App.xaml new file mode 100644 index 00000000..6e70f617 --- /dev/null +++ b/src/Titano.Uploader/App.xaml @@ -0,0 +1,4 @@ + + diff --git a/src/Titano.Uploader/App.xaml.cs b/src/Titano.Uploader/App.xaml.cs new file mode 100644 index 00000000..67a0cc99 --- /dev/null +++ b/src/Titano.Uploader/App.xaml.cs @@ -0,0 +1,7 @@ +using System.Windows; + +namespace Titano.Uploader; + +public partial class App : Application +{ +} diff --git a/src/Titano.Uploader/Titano.Uploader.csproj b/src/Titano.Uploader/Titano.Uploader.csproj new file mode 100644 index 00000000..abfba7d6 --- /dev/null +++ b/src/Titano.Uploader/Titano.Uploader.csproj @@ -0,0 +1,16 @@ + + + WinExe + net10.0-windows + true + Titano.Uploader + Titano.Uploader + app.manifest + titano-uploader + + + + + + + diff --git a/src/Titano.Uploader/app.manifest b/src/Titano.Uploader/app.manifest new file mode 100644 index 00000000..0890c857 --- /dev/null +++ b/src/Titano.Uploader/app.manifest @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2, PerMonitor + true + + + + + + + + diff --git a/tests/Titano.App.Tests/Program.cs b/tests/Titano.App.Tests/Program.cs new file mode 100644 index 00000000..e4838431 --- /dev/null +++ b/tests/Titano.App.Tests/Program.cs @@ -0,0 +1,8 @@ +using Titano.Testing; + +namespace Titano.App.Tests; + +internal static class TestMain +{ + public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); +} diff --git a/tests/Titano.App.Tests/Titano.App.Tests.csproj b/tests/Titano.App.Tests/Titano.App.Tests.csproj new file mode 100644 index 00000000..43859d50 --- /dev/null +++ b/tests/Titano.App.Tests/Titano.App.Tests.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0-windows + true + Titano.App.Tests + + + + + + + diff --git a/tests/Titano.Core.Tests/Branding/BrandMarkTests.cs b/tests/Titano.Core.Tests/Branding/BrandMarkTests.cs new file mode 100644 index 00000000..2116fd20 --- /dev/null +++ b/tests/Titano.Core.Tests/Branding/BrandMarkTests.cs @@ -0,0 +1,62 @@ +using Titano.Core.Branding; +using Titano.Core.Codecs.Ico; +using Titano.Testing; + +namespace Titano.Core.Tests.Branding; + +public sealed class BrandMarkTests +{ + [Test] + public void TickOpacityRampsFromDimToFull() + { + Assert.Approximately(0.14, BrandMark.TickOpacity(0), 1e-9); + Assert.Approximately(1.0, BrandMark.TickOpacity(11), 1e-9); + Assert.Monotonic(Enumerable.Range(0, 12).Select(BrandMark.TickOpacity), strict: true); + } + + [Test] + public void SunPixelIsSunColour() + { + var rgba = BrandMark.Render(BrandVariant.App, 256); + var o = (104 * 256 + 152) * 4; + Assert.Equal(BrandMark.Sun.R, rgba[o]); + Assert.Equal(BrandMark.Sun.G, rgba[o + 1]); + Assert.Equal(BrandMark.Sun.B, rgba[o + 2]); + Assert.Equal((byte)255, rgba[o + 3]); + } + + [Test] + public void CornersOutsideRoundedPlateAreTransparent() + { + var rgba = BrandMark.Render(BrandVariant.App, 64); + Assert.Equal((byte)0, rgba[3]); + Assert.Equal((byte)255, rgba[(32 * 64 + 32) * 4 + 3]); + } + + [Test] + public void MonoHasNoPlate() + { + var rgba = BrandMark.Render(BrandVariant.Mono, 64); + Assert.Equal((byte)0, rgba[(4 * 64 + 32) * 4 + 3]); + } + + [Test] + public void SvgMatchesDesignMaster() + { + var master = File.ReadAllText(Path.Combine(TestContext.RepositoryRoot, "branding", "titano.svg")).Replace("\r", "", StringComparison.Ordinal); + Assert.Equal(master.Trim(), BrandMark.ToSvg(BrandVariant.App).Trim()); + } + + [Test] + public void IcoHasAllSizes() + { + var sizes = new[] { 16, 32, 48, 256 }; + var ico = IcoWriter.Write(sizes.Select(s => (s, BrandMark.Render(BrandVariant.App, s))).ToList()); + Assert.Equal((byte)0, ico[0]); + Assert.Equal((byte)1, ico[2]); + Assert.Equal(sizes.Length, ico[4] | ico[5] << 8); + // 256 px entry stored as PNG. + var lastOffset = BitConverter.ToInt32(ico, 6 + 16 * 3 + 12); + Assert.Equal((byte)0x89, ico[lastOffset]); + } +} diff --git a/tests/Titano.Core.Tests/Foundation/AtomicFileTests.cs b/tests/Titano.Core.Tests/Foundation/AtomicFileTests.cs new file mode 100644 index 00000000..62d1d6fb --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/AtomicFileTests.cs @@ -0,0 +1,33 @@ +using Titano.Core.IO; +using Titano.Testing; + +namespace Titano.Core.Tests.Foundation; + +public sealed class AtomicFileTests(TestContext context) +{ + [Test] + public void ReplacesContentAndLeavesNoTemporaryFiles() + { + var dir = context.CreateTempDirectory(); + var path = Path.Combine(dir, "sequence.json"); + AtomicFile.WriteAllText(path, "one"); + AtomicFile.WriteAllText(path, "two"); + Assert.Equal("two", File.ReadAllText(path)); + Assert.Count(1, Directory.GetFiles(dir)); + } + + [Test] + public async Task FailedWriteKeepsPreviousContent() + { + var dir = context.CreateTempDirectory(); + var path = Path.Combine(dir, "project.json"); + AtomicFile.WriteAllText(path, "stable"); + await Assert.ThrowsAsync(() => AtomicFile.WriteAsync(path, async (s, ct) => + { + await s.WriteAsync("partial"u8.ToArray(), ct); + throw new InvalidOperationException("boom"); + })); + Assert.Equal("stable", File.ReadAllText(path)); + Assert.Count(1, Directory.GetFiles(dir)); + } +} diff --git a/tests/Titano.Core.Tests/Foundation/Crc32Tests.cs b/tests/Titano.Core.Tests/Foundation/Crc32Tests.cs new file mode 100644 index 00000000..fb77be68 --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/Crc32Tests.cs @@ -0,0 +1,25 @@ +using System.Text; +using Titano.Core.Hashing; +using Titano.Testing; + +namespace Titano.Core.Tests.Foundation; + +public sealed class Crc32Tests +{ + [Test] + public void CheckValueMatchesStandard() => Assert.Equal(0xCBF43926u, Crc32.Compute("123456789"u8)); + + [Test] + public void IncrementalEqualsOneShot() + { + var data = Encoding.ASCII.GetBytes(new string('x', 1000) + "titano"); + var crc = new Crc32(); + crc.Append(data.AsSpan(0, 7)); + crc.Append(data.AsSpan(7, 500)); + crc.Append(data.AsSpan(507)); + Assert.Equal(Crc32.Compute(data), crc.GetCurrentHashAsUInt32()); + } + + [Test] + public void EmptyInputIsZero() => Assert.Equal(0u, Crc32.Compute([])); +} diff --git a/tests/Titano.Core.Tests/Foundation/ImageBufferTests.cs b/tests/Titano.Core.Tests/Foundation/ImageBufferTests.cs new file mode 100644 index 00000000..4a922ef6 --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/ImageBufferTests.cs @@ -0,0 +1,44 @@ +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Foundation; + +public sealed class ImageBufferTests +{ + [Test] + public void PlanesAreIndependentAndClearedByDefault() + { + using var image = new ImageBuffer(4, 3); + Assert.Equal(12, image.PlaneLength); + Assert.True(image.Data.ToArray().All(v => v == 0)); + image[1, 2, 1] = 0.5f; + Assert.Equal(0.5f, image.Plane(1)[1 * 4 + 2]); + Assert.Equal(0f, image.Plane(0)[1 * 4 + 2]); + } + + [Test] + public void CloneCopiesPixels() + { + using var image = new ImageBuffer(2, 2, 1); + image[0, 1, 1] = 3f; + using var clone = image.Clone(); + image[0, 1, 1] = 0f; + Assert.Equal(3f, clone[0, 1, 1]); + } + + [Test] + public void DisposedBufferThrows() + { + var image = new ImageBuffer(1, 1); + image.Dispose(); + Assert.Throws(() => _ = image.Storage); + } + + [Theory] + [Case("IMG_0001.CR2", ImageFileFormat.Cr2)] + [Case("a.jpeg", ImageFileFormat.Jpeg)] + [Case("photo.HEIC", ImageFileFormat.Heif)] + [Case("notes.txt", ImageFileFormat.Unknown)] + public void FormatFromExtension(string name, ImageFileFormat expected) => + Assert.Equal(expected, ImageFormatInfo.FromPath(name).Format); +} diff --git a/tests/Titano.Core.Tests/Localization/PluralRulesTests.cs b/tests/Titano.Core.Tests/Localization/PluralRulesTests.cs new file mode 100644 index 00000000..e14bfcd4 --- /dev/null +++ b/tests/Titano.Core.Tests/Localization/PluralRulesTests.cs @@ -0,0 +1,38 @@ +using System.Globalization; +using Titano.Core.Localization; +using Titano.Testing; + +namespace Titano.Core.Tests.Localization; + +public sealed class PluralRulesTests +{ + [Theory] + [Case("en", 1L, PluralCategory.One)] + [Case("en", 0L, PluralCategory.Other)] + [Case("fr", 0L, PluralCategory.One)] + [Case("ru", 21L, PluralCategory.One)] + [Case("ru", 22L, PluralCategory.Few)] + [Case("ru", 11L, PluralCategory.Many)] + [Case("ru", 25L, PluralCategory.Many)] + [Case("pl", 12L, PluralCategory.Many)] + [Case("pl", 23L, PluralCategory.Few)] + [Case("cs", 3L, PluralCategory.Few)] + [Case("ja", 1L, PluralCategory.Other)] + [Case("ar", 11L, PluralCategory.Many)] + public void SelectsCldrCategory(string culture, long count, PluralCategory expected) => + Assert.Equal(expected, PluralRules.Select(CultureInfo.GetCultureInfo(culture), count)); + + [Test] + public void BestMatchFallsBackToEnglish() + { + Assert.Equal("it", Languages.BestMatch(CultureInfo.GetCultureInfo("it-CH")).Name); + Assert.Equal("pt-BR", Languages.BestMatch(CultureInfo.GetCultureInfo("pt-BR")).Name); + Assert.Equal("en", Languages.BestMatch(CultureInfo.GetCultureInfo("sw")).Name); + } + + [Test] + public void EveryShippedLanguageIsAKnownCulture() + { + foreach (var code in Languages.Shipped) Assert.NotNull(CultureInfo.GetCultureInfo(code)); + } +} diff --git a/tests/Titano.Core.Tests/Program.cs b/tests/Titano.Core.Tests/Program.cs new file mode 100644 index 00000000..905d7a45 --- /dev/null +++ b/tests/Titano.Core.Tests/Program.cs @@ -0,0 +1,8 @@ +using Titano.Testing; + +namespace Titano.Core.Tests; + +internal static class TestMain +{ + public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); +} diff --git a/tests/Titano.Core.Tests/Titano.Core.Tests.csproj b/tests/Titano.Core.Tests/Titano.Core.Tests.csproj new file mode 100644 index 00000000..2a01ce7b --- /dev/null +++ b/tests/Titano.Core.Tests/Titano.Core.Tests.csproj @@ -0,0 +1,12 @@ + + + Exe + net10.0 + Titano.Core.Tests + + + + + + + diff --git a/tests/Titano.Core.Windows.Tests/Program.cs b/tests/Titano.Core.Windows.Tests/Program.cs new file mode 100644 index 00000000..09bb9745 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Program.cs @@ -0,0 +1,8 @@ +using Titano.Testing; + +namespace Titano.Core.Windows.Tests; + +internal static class TestMain +{ + public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); +} diff --git a/tests/Titano.Core.Windows.Tests/Titano.Core.Windows.Tests.csproj b/tests/Titano.Core.Windows.Tests/Titano.Core.Windows.Tests.csproj new file mode 100644 index 00000000..0da39c1c --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Titano.Core.Windows.Tests.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0-windows + Titano.Core.Windows.Tests + + + + + + diff --git a/tests/Titano.Data.Tests/Program.cs b/tests/Titano.Data.Tests/Program.cs new file mode 100644 index 00000000..92339124 --- /dev/null +++ b/tests/Titano.Data.Tests/Program.cs @@ -0,0 +1,8 @@ +using Titano.Testing; + +namespace Titano.Data.Tests; + +internal static class TestMain +{ + public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); +} diff --git a/tests/Titano.Data.Tests/Titano.Data.Tests.csproj b/tests/Titano.Data.Tests/Titano.Data.Tests.csproj new file mode 100644 index 00000000..7d259b6f --- /dev/null +++ b/tests/Titano.Data.Tests/Titano.Data.Tests.csproj @@ -0,0 +1,12 @@ + + + Exe + net10.0 + Titano.Data.Tests + + + + + + + diff --git a/tests/Titano.Server.Tests/Program.cs b/tests/Titano.Server.Tests/Program.cs new file mode 100644 index 00000000..58b57f8d --- /dev/null +++ b/tests/Titano.Server.Tests/Program.cs @@ -0,0 +1,8 @@ +using Titano.Testing; + +namespace Titano.Server.Tests; + +internal static class TestMain +{ + public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); +} diff --git a/tests/Titano.Server.Tests/Titano.Server.Tests.csproj b/tests/Titano.Server.Tests/Titano.Server.Tests.csproj new file mode 100644 index 00000000..5bbe584c --- /dev/null +++ b/tests/Titano.Server.Tests/Titano.Server.Tests.csproj @@ -0,0 +1,12 @@ + + + Exe + net10.0 + Titano.Server.Tests + + + + + + + diff --git a/tests/Titano.Testing/Assert.cs b/tests/Titano.Testing/Assert.cs new file mode 100644 index 00000000..8530989f --- /dev/null +++ b/tests/Titano.Testing/Assert.cs @@ -0,0 +1,251 @@ +using System.Collections; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Titano.Testing; + +/// Assertions with messages that state expected and actual values. +public static class Assert +{ + public static void True(bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) + { + if (!condition) Fail(message ?? $"Expected true: {expression}"); + } + + public static void False(bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) + { + if (condition) Fail(message ?? $"Expected false: {expression}"); + } + + public static void Null(object? value, [CallerArgumentExpression(nameof(value))] string? expression = null) + { + if (value is not null) Fail($"Expected null: {expression} was {Format(value)}"); + } + + public static T NotNull(T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : class + { + if (value is null) Fail($"Expected non-null: {expression}"); + return value!; + } + + public static T NotNull(T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : struct + { + if (value is null) Fail($"Expected non-null: {expression}"); + return value!.Value; + } + + public static void Equal(T expected, T actual, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!EqualityComparer.Default.Equals(expected, actual)) + Fail(Prefix(message) + $"{expression}: expected {Format(expected)}, actual {Format(actual)}"); + } + + public static void NotEqual(T unexpected, T actual, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (EqualityComparer.Default.Equals(unexpected, actual)) + Fail(Prefix(message) + $"{expression}: did not expect {Format(unexpected)}"); + } + + public static void Same(object? expected, object? actual, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!ReferenceEquals(expected, actual)) Fail($"{expression}: expected the same instance"); + } + + /// |expected − actual| ≤ tolerance. + public static void Approximately(double expected, double actual, double tolerance, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (double.IsNaN(actual) || Math.Abs(expected - actual) > tolerance) + Fail(Prefix(message) + $"{expression}: expected {F(expected)} ± {F(tolerance)}, actual {F(actual)} (diff {F(Math.Abs(expected - actual))})"); + } + + /// Distance between two points ≤ . + public static void Within(double expectedX, double expectedY, double actualX, double actualY, double pixels, string? message = null) + { + var d = Math.Sqrt((expectedX - actualX) * (expectedX - actualX) + (expectedY - actualY) * (expectedY - actualY)); + if (!(d <= pixels)) + Fail(Prefix(message) + $"expected ({F(expectedX)}, {F(expectedY)}) within {F(pixels)} px, actual ({F(actualX)}, {F(actualY)}) at {F(d)} px"); + } + + public static void InRange(double actual, double min, double max, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!(actual >= min && actual <= max)) + Fail(Prefix(message) + $"{expression}: expected in [{F(min)}, {F(max)}], actual {F(actual)}"); + } + + public static void Greater(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!(actual > bound)) Fail(Prefix(message) + $"{expression}: expected > {F(bound)}, actual {F(actual)}"); + } + + public static void GreaterOrEqual(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!(actual >= bound)) Fail(Prefix(message) + $"{expression}: expected ≥ {F(bound)}, actual {F(actual)}"); + } + + public static void Less(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!(actual < bound)) Fail(Prefix(message) + $"{expression}: expected < {F(bound)}, actual {F(actual)}"); + } + + public static void LessOrEqual(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!(actual <= bound)) Fail(Prefix(message) + $"{expression}: expected ≤ {F(bound)}, actual {F(actual)}"); + } + + public static void SequenceEqual(IEnumerable expected, IEnumerable actual, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + var e = expected.ToList(); + var a = actual.ToList(); + var n = Math.Min(e.Count, a.Count); + for (var i = 0; i < n; i++) + { + if (!EqualityComparer.Default.Equals(e[i], a[i])) + Fail(Prefix(message) + $"{expression}: first difference at [{i}]: expected {Format(e[i])}, actual {Format(a[i])}"); + } + if (e.Count != a.Count) + Fail(Prefix(message) + $"{expression}: expected {e.Count} items, actual {a.Count}"); + } + + public static void BytesEqual(ReadOnlySpan expected, ReadOnlySpan actual, string? message = null) + { + var n = Math.Min(expected.Length, actual.Length); + for (var i = 0; i < n; i++) + { + if (expected[i] != actual[i]) + Fail(Prefix(message) + $"bytes differ at offset {i}: expected 0x{expected[i]:X2}, actual 0x{actual[i]:X2}"); + } + if (expected.Length != actual.Length) + Fail(Prefix(message) + $"expected {expected.Length} bytes, actual {actual.Length}"); + } + + /// Every element is ≥ (or > when strict) the previous one. + public static void Monotonic(IEnumerable values, bool strict = false, bool decreasing = false, string? message = null) + { + var i = 0; + double? previous = null; + foreach (var v in values) + { + if (previous is { } p) + { + var ok = decreasing + ? (strict ? v < p : v <= p) + : (strict ? v > p : v >= p); + if (!ok) Fail(Prefix(message) + $"not monotonic at [{i}]: {F(p)} then {F(v)}"); + } + previous = v; + i++; + } + } + + public static void Contains(T expected, IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) + { + if (!collection.Contains(expected)) Fail($"{expression}: does not contain {Format(expected)}"); + } + + public static void DoesNotContain(T unexpected, IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) + { + if (collection.Contains(unexpected)) Fail($"{expression}: unexpectedly contains {Format(unexpected)}"); + } + + public static void Contains(string expected, string? actual, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (actual is null || !actual.Contains(expected, StringComparison.Ordinal)) + Fail($"{expression}: expected to contain \"{expected}\", actual {Format(actual)}"); + } + + public static void Empty(IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) + { + foreach (var item in collection) Fail($"{expression}: expected empty, first item {Format(item)}"); + } + + public static void NotEmpty(IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) + { + foreach (var _ in collection) return; + Fail($"{expression}: expected at least one item"); + } + + public static void Count(int expected, IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) + { + var n = 0; + foreach (var _ in collection) n++; + if (n != expected) Fail($"{expression}: expected {expected} items, actual {n}"); + } + + public static TException Throws(Action action, [CallerArgumentExpression(nameof(action))] string? expression = null) where TException : Exception + { + try + { + action(); + } + catch (TException ex) + { + return ex; + } + catch (Exception ex) + { + Fail($"{expression}: expected {typeof(TException).Name}, got {ex.GetType().Name}: {ex.Message}"); + } + Fail($"{expression}: expected {typeof(TException).Name}, nothing was thrown"); + return null!; + } + + public static async Task ThrowsAsync(Func action, [CallerArgumentExpression(nameof(action))] string? expression = null) where TException : Exception + { + try + { + await action().ConfigureAwait(false); + } + catch (TException ex) + { + return ex; + } + catch (Exception ex) + { + Fail($"{expression}: expected {typeof(TException).Name}, got {ex.GetType().Name}: {ex.Message}"); + } + Fail($"{expression}: expected {typeof(TException).Name}, nothing was thrown"); + return null!; + } + + public static void DoesNotThrow(Action action, [CallerArgumentExpression(nameof(action))] string? expression = null) + { + try + { + action(); + } + catch (Exception ex) + { + Fail($"{expression}: unexpected {ex.GetType().Name}: {ex.Message}"); + } + } + + public static void FileExists(string path) + { + if (!File.Exists(path)) Fail($"File not found: {path}"); + } + + public static void FileMissing(string path) + { + if (File.Exists(path)) Fail($"File should not exist: {path}"); + } + + [System.Diagnostics.CodeAnalysis.DoesNotReturn] + public static void Fail(string message) => throw new AssertionException(message); + + [System.Diagnostics.CodeAnalysis.DoesNotReturn] + public static void Inconclusive(string reason) => throw new SkipException(reason); + + private static string Prefix(string? message) => string.IsNullOrEmpty(message) ? string.Empty : message + ": "; + + private static string F(double v) => v.ToString("G6", CultureInfo.InvariantCulture); + + internal static string Format(object? value) => value switch + { + null => "null", + string s => "\"" + s + "\"", + double d => F(d), + float f => F(f), + IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), + _ => value.ToString() ?? value.GetType().Name, + }; +} diff --git a/tests/Titano.Testing/AssertionException.cs b/tests/Titano.Testing/AssertionException.cs new file mode 100644 index 00000000..b2a951c0 --- /dev/null +++ b/tests/Titano.Testing/AssertionException.cs @@ -0,0 +1,7 @@ +namespace Titano.Testing; + +/// Raised by when an expectation is not met. +public sealed class AssertionException(string message) : Exception(message); + +/// Raised by or to skip at run time. +public sealed class SkipException(string reason) : Exception(reason); diff --git a/tests/Titano.Testing/Attributes.cs b/tests/Titano.Testing/Attributes.cs new file mode 100644 index 00000000..a87e0a30 --- /dev/null +++ b/tests/Titano.Testing/Attributes.cs @@ -0,0 +1,55 @@ +namespace Titano.Testing; + +/// Marks a public method as a test. The method may be sync or return /. +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] +public sealed class TestAttribute : Attribute; + +/// Marks a parameterised test; each is one execution. +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] +public sealed class TheoryAttribute : Attribute; + +/// One set of arguments for a test. +[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] +public sealed class CaseAttribute(params object?[] arguments) : Attribute +{ + public object?[] Arguments { get; } = arguments ?? [null]; + + /// Optional display name for the case. + public string? Name { get; init; } +} + +/// Skips a test (or every test of a class) with a reason. +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] +public sealed class SkipAttribute(string reason) : Attribute +{ + public string Reason { get; } = reason; +} + +/// Fails the test when it runs longer than the given number of milliseconds. +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] +public sealed class TimeoutAttribute(int milliseconds) : Attribute +{ + public int Milliseconds { get; } = milliseconds; +} + +/// Tags a test or class; filters accept category:name. +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] +public sealed class CategoryAttribute(string name) : Attribute +{ + public string Name { get; } = name; +} + +/// Runs only on Windows; skipped elsewhere. +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] +public sealed class WindowsOnlyAttribute : Attribute; + +/// Runs only when the environment variable is set and non-empty; skipped otherwise. +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] +public sealed class RequiresEnvironmentAttribute(string variable) : Attribute +{ + public string Variable { get; } = variable; +} + +/// Tests of this class never run concurrently with any other test. +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] +public sealed class SerialAttribute : Attribute; diff --git a/tests/Titano.Testing/ConsoleReporter.cs b/tests/Titano.Testing/ConsoleReporter.cs new file mode 100644 index 00000000..d9828784 --- /dev/null +++ b/tests/Titano.Testing/ConsoleReporter.cs @@ -0,0 +1,64 @@ +using System.Globalization; + +namespace Titano.Testing; + +internal sealed class ConsoleReporter(bool verbose) : IDisposable +{ + private readonly Lock _gate = new(); + + public void Report(TestResult r) + { + lock (_gate) + { + switch (r.Outcome) + { + case TestOutcome.Failed: + Write(ConsoleColor.Red, "FAIL "); + Console.WriteLine($"{r.Test.FullName} ({Ms(r.Duration)})"); + Console.WriteLine(" " + r.Message); + if (r.StackTrace is not null) Console.WriteLine(Indent(r.StackTrace)); + if (r.Log.Length > 0) Console.WriteLine(Indent(r.Log)); + break; + case TestOutcome.Skipped when verbose: + Write(ConsoleColor.Yellow, "SKIP "); + Console.WriteLine($"{r.Test.FullName} — {r.Message}"); + break; + case TestOutcome.Passed when verbose: + Write(ConsoleColor.Green, "PASS "); + Console.WriteLine($"{r.Test.FullName} ({Ms(r.Duration)})"); + if (r.Log.Length > 0) Console.WriteLine(Indent(r.Log)); + break; + } + } + } + + public void Summary(string suite, int passed, int failed, int skipped, TimeSpan elapsed, IReadOnlyList results) + { + lock (_gate) + { + Console.WriteLine(); + var slowest = results.Where(r => r.Outcome == TestOutcome.Passed).OrderByDescending(r => r.Duration).Take(3).ToList(); + if (verbose && slowest.Count > 0) + { + Console.WriteLine("Slowest:"); + foreach (var r in slowest) Console.WriteLine($" {Ms(r.Duration),9} {r.Test.FullName}"); + } + Write(failed > 0 ? ConsoleColor.Red : ConsoleColor.Green, failed > 0 ? "FAILED" : "PASSED"); + Console.WriteLine($" {suite}: {passed} passed, {failed} failed, {skipped} skipped in {elapsed.TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)} s"); + } + } + + public void Dispose() => Console.Out.Flush(); + + private static string Ms(TimeSpan t) => t.TotalMilliseconds.ToString("F0", CultureInfo.InvariantCulture) + " ms"; + + private static string Indent(string s) => string.Join(Environment.NewLine, s.TrimEnd().Split('\n').Select(l => " " + l.TrimEnd('\r'))); + + private static void Write(ConsoleColor color, string text) + { + var redirected = Console.IsOutputRedirected; + if (!redirected) Console.ForegroundColor = color; + Console.Write(text); + if (!redirected) Console.ResetColor(); + } +} diff --git a/tests/Titano.Testing/TestCase.cs b/tests/Titano.Testing/TestCase.cs new file mode 100644 index 00000000..3b079725 --- /dev/null +++ b/tests/Titano.Testing/TestCase.cs @@ -0,0 +1,59 @@ +using System.Reflection; + +namespace Titano.Testing; + +/// One discovered executable test (a method, or one case of a theory). +public sealed class TestCase +{ + internal TestCase(Type type, MethodInfo method, object?[]? arguments, string? caseName) + { + Type = type; + Method = method; + Arguments = arguments; + var suffix = arguments is null ? string.Empty : "(" + (caseName ?? string.Join(", ", arguments.Select(Assert.Format))) + ")"; + FullName = $"{type.FullName}.{method.Name}{suffix}"; + Categories = type.GetCustomAttributes() + .Concat(method.GetCustomAttributes()) + .Select(c => c.Name) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + TimeoutMs = method.GetCustomAttribute()?.Milliseconds + ?? type.GetCustomAttribute()?.Milliseconds + ?? 300_000; + Serial = type.GetCustomAttribute() is not null; + StaticSkipReason = ComputeSkipReason(type, method); + } + + public Type Type { get; } + public MethodInfo Method { get; } + public object?[]? Arguments { get; } + public string FullName { get; } + public IReadOnlyList Categories { get; } + public int TimeoutMs { get; } + public bool Serial { get; } + public string? StaticSkipReason { get; } + + private static string? ComputeSkipReason(Type type, MethodInfo method) + { + var skip = method.GetCustomAttribute() ?? type.GetCustomAttribute(); + if (skip is not null) return skip.Reason; + if ((method.GetCustomAttribute() ?? type.GetCustomAttribute()) is not null + && !OperatingSystem.IsWindows()) + return "Windows only"; + foreach (var env in type.GetCustomAttributes().Concat(method.GetCustomAttributes())) + { + if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(env.Variable))) + return $"{env.Variable} not set"; + } + return null; + } +} + +public enum TestOutcome +{ + Passed, + Failed, + Skipped, +} + +public sealed record TestResult(TestCase Test, TestOutcome Outcome, TimeSpan Duration, string? Message, string? StackTrace, string Log); diff --git a/tests/Titano.Testing/TestContext.cs b/tests/Titano.Testing/TestContext.cs new file mode 100644 index 00000000..3c31cc3d --- /dev/null +++ b/tests/Titano.Testing/TestContext.cs @@ -0,0 +1,96 @@ +using System.Collections.Concurrent; +using System.Text; + +namespace Titano.Testing; + +/// +/// Per-test services. A test class may take a in its constructor; +/// one context is created for every test execution and disposed after it. +/// +public sealed class TestContext : IDisposable +{ + private readonly ConcurrentQueue _log = new(); + private readonly List _tempDirectories = []; + private readonly Lock _gate = new(); + + internal TestContext(string testName, CancellationToken cancellation) + { + TestName = testName; + Cancellation = cancellation; + } + + public string TestName { get; } + + /// Signalled when the test times out or the run is aborted. + public CancellationToken Cancellation { get; } + + /// Repository root (the directory that holds Titano.slnx), or the working directory. + public static string RepositoryRoot { get; } = FindRepositoryRoot(); + + /// tests/fixtures under the repository root. + public static string FixturesDirectory => Path.Combine(RepositoryRoot, "tests", "fixtures"); + + /// Creates an empty directory that is deleted when the test ends. + public string CreateTempDirectory(string? hint = null) + { + var path = Path.Combine(Path.GetTempPath(), "titano-tests", $"{Sanitize(hint ?? TestName)}-{Guid.NewGuid():N}"); + Directory.CreateDirectory(path); + lock (_gate) _tempDirectories.Add(path); + return path; + } + + /// Lines written here are printed only when the test fails or in verbose mode. + public void Log(string message) => _log.Enqueue(message); + + public string LogText + { + get + { + var sb = new StringBuilder(); + foreach (var line in _log) sb.AppendLine(line); + return sb.ToString(); + } + } + + [System.Diagnostics.CodeAnalysis.DoesNotReturn] + public static void Skip(string reason) => throw new SkipException(reason); + + public void Dispose() + { + lock (_gate) + { + foreach (var dir in _tempDirectories) + { + try + { + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + } + catch (IOException) + { + // Best effort: a file still open by the OS indexer must not fail the test. + } + catch (UnauthorizedAccessException) + { + } + } + _tempDirectories.Clear(); + } + } + + private static string Sanitize(string s) + { + var chars = s.Select(c => char.IsLetterOrDigit(c) ? c : '-').Take(48).ToArray(); + return new string(chars); + } + + private static string FindRepositoryRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null) + { + if (File.Exists(Path.Combine(dir.FullName, "Titano.slnx"))) return dir.FullName; + dir = dir.Parent; + } + return Directory.GetCurrentDirectory(); + } +} diff --git a/tests/Titano.Testing/TestRunner.cs b/tests/Titano.Testing/TestRunner.cs new file mode 100644 index 00000000..1745aad5 --- /dev/null +++ b/tests/Titano.Testing/TestRunner.cs @@ -0,0 +1,319 @@ +using System.Diagnostics; +using System.Globalization; +using System.Reflection; +using System.Runtime.ExceptionServices; +using System.Text; +using System.Xml; + +namespace Titano.Testing; + +/// +/// Discovers and runs tests in an assembly. Test projects are console apps whose entry point is +/// return await TestRunner.RunAsync(args, typeof(Program).Assembly);. +/// +/// +/// Arguments: --filter text (substring of the full name, or category:name; repeatable, OR-combined), +/// --exclude text, --junit path, --parallel n, --list, --verbose. +/// Exit codes: 0 all passed, 1 failures, 2 usage error or no tests matched. +/// +public static class TestRunner +{ + public static async Task RunAsync(string[] args, Assembly assembly) + { + CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; + CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; + + Options options; + try + { + options = Options.Parse(args); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine(ex.Message); + return 2; + } + + var all = Discover(assembly); + var selected = all.Where(options.Matches).ToList(); + if (options.List) + { + foreach (var t in selected) Console.WriteLine(t.FullName); + return 0; + } + if (selected.Count == 0) + { + Console.Error.WriteLine("No tests matched."); + return 2; + } + + var stopwatch = Stopwatch.StartNew(); + var results = new List(selected.Count); + var resultsGate = new Lock(); + using var console = new ConsoleReporter(options.Verbose); + + void Record(TestResult r) + { + lock (resultsGate) results.Add(r); + console.Report(r); + } + + var parallel = selected.Where(t => !t.Serial).GroupBy(t => t.Type).ToList(); + var serial = selected.Where(t => t.Serial).ToList(); + + // Classes run in parallel; tests inside a class run in declaration order. + await Parallel.ForEachAsync( + parallel, + new ParallelOptions { MaxDegreeOfParallelism = options.Parallelism }, + async (group, _) => + { + foreach (var test in group) Record(await ExecuteAsync(test).ConfigureAwait(false)); + }).ConfigureAwait(false); + + foreach (var test in serial) Record(await ExecuteAsync(test).ConfigureAwait(false)); + + stopwatch.Stop(); + var passed = results.Count(r => r.Outcome == TestOutcome.Passed); + var failed = results.Count(r => r.Outcome == TestOutcome.Failed); + var skipped = results.Count(r => r.Outcome == TestOutcome.Skipped); + console.Summary(assembly.GetName().Name ?? "tests", passed, failed, skipped, stopwatch.Elapsed, results); + + if (options.JUnitPath is { } junit) + WriteJUnit(junit, assembly.GetName().Name ?? "tests", results, stopwatch.Elapsed); + + return failed > 0 ? 1 : 0; + } + + public static IReadOnlyList Discover(Assembly assembly) + { + var list = new List(); + Type[] types; + try + { + types = assembly.GetTypes(); + } + catch (ReflectionTypeLoadException ex) + { + types = ex.Types.Where(t => t is not null).ToArray()!; + } + + foreach (var type in types.Where(t => t is { IsClass: true, IsPublic: true } && !t.IsAbstract).OrderBy(t => t.FullName, StringComparer.Ordinal)) + { + foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).OrderBy(m => m.MetadataToken)) + { + if (method.GetCustomAttribute() is not null) + { + list.Add(new TestCase(type, method, null, null)); + } + else if (method.GetCustomAttribute() is not null) + { + foreach (var c in method.GetCustomAttributes()) + list.Add(new TestCase(type, method, c.Arguments, c.Name)); + } + } + } + return list; + } + + private static async Task ExecuteAsync(TestCase test) + { + if (test.StaticSkipReason is { } reason) + return new TestResult(test, TestOutcome.Skipped, TimeSpan.Zero, reason, null, string.Empty); + + using var cts = new CancellationTokenSource(); + using var context = new TestContext(test.FullName, cts.Token); + var sw = Stopwatch.StartNew(); + try + { + var run = Task.Run(() => InvokeAsync(test, context), CancellationToken.None); + var finished = await Task.WhenAny(run, Task.Delay(test.TimeoutMs, CancellationToken.None)).ConfigureAwait(false); + if (finished != run) + { + await cts.CancelAsync().ConfigureAwait(false); + // Give cooperative code a moment to observe cancellation before reporting. + await Task.WhenAny(run, Task.Delay(2000, CancellationToken.None)).ConfigureAwait(false); + return new TestResult(test, TestOutcome.Failed, sw.Elapsed, $"Timed out after {test.TimeoutMs} ms", null, context.LogText); + } + await run.ConfigureAwait(false); + return new TestResult(test, TestOutcome.Passed, sw.Elapsed, null, null, context.LogText); + } + catch (SkipException ex) + { + return new TestResult(test, TestOutcome.Skipped, sw.Elapsed, ex.Message, null, context.LogText); + } + catch (Exception ex) + { + var message = ex is AssertionException ? ex.Message : $"{ex.GetType().FullName}: {ex.Message}"; + return new TestResult(test, TestOutcome.Failed, sw.Elapsed, message, ex.StackTrace, context.LogText); + } + } + + private static async Task InvokeAsync(TestCase test, TestContext context) + { + object? instance = null; + try + { + if (!test.Method.IsStatic) + { + var ctor = test.Type.GetConstructor([typeof(TestContext)]); + instance = ctor is not null + ? ctor.Invoke([context]) + : Activator.CreateInstance(test.Type); + } + + var parameters = test.Method.GetParameters(); + var args = BuildArguments(test, parameters, context); + object? returned; + try + { + returned = test.Method.Invoke(instance, args); + } + catch (TargetInvocationException tie) when (tie.InnerException is not null) + { + ExceptionDispatchInfo.Capture(tie.InnerException).Throw(); + throw; + } + + switch (returned) + { + case Task task: + await task.ConfigureAwait(false); + break; + case ValueTask valueTask: + await valueTask.ConfigureAwait(false); + break; + } + } + finally + { + switch (instance) + { + case IAsyncDisposable ad: + await ad.DisposeAsync().ConfigureAwait(false); + break; + case IDisposable d: + d.Dispose(); + break; + } + } + } + + private static object?[] BuildArguments(TestCase test, ParameterInfo[] parameters, TestContext context) + { + var supplied = test.Arguments ?? []; + var result = new object?[parameters.Length]; + var next = 0; + for (var i = 0; i < parameters.Length; i++) + { + var p = parameters[i]; + if (p.ParameterType == typeof(TestContext)) + { + result[i] = context; + continue; + } + if (p.ParameterType == typeof(CancellationToken)) + { + result[i] = context.Cancellation; + continue; + } + if (next >= supplied.Length) + throw new InvalidOperationException($"{test.FullName}: missing argument for parameter '{p.Name}'"); + result[i] = Convert(supplied[next++], p.ParameterType); + } + if (next != supplied.Length) + throw new InvalidOperationException($"{test.FullName}: {supplied.Length - next} unused case argument(s)"); + return result; + } + + private static object? Convert(object? value, Type target) + { + if (value is null) return null; + var underlying = Nullable.GetUnderlyingType(target) ?? target; + if (underlying.IsInstanceOfType(value)) return value; + if (underlying.IsEnum) return Enum.ToObject(underlying, value); + return System.Convert.ChangeType(value, underlying, CultureInfo.InvariantCulture); + } + + private static void WriteJUnit(string path, string suiteName, IReadOnlyList results, TimeSpan elapsed) + { + var dir = Path.GetDirectoryName(Path.GetFullPath(path)); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + var settings = new XmlWriterSettings { Indent = true, Encoding = new UTF8Encoding(false) }; + using var w = XmlWriter.Create(path, settings); + w.WriteStartDocument(); + w.WriteStartElement("testsuites"); + w.WriteStartElement("testsuite"); + w.WriteAttributeString("name", suiteName); + w.WriteAttributeString("tests", results.Count.ToString(CultureInfo.InvariantCulture)); + w.WriteAttributeString("failures", results.Count(r => r.Outcome == TestOutcome.Failed).ToString(CultureInfo.InvariantCulture)); + w.WriteAttributeString("skipped", results.Count(r => r.Outcome == TestOutcome.Skipped).ToString(CultureInfo.InvariantCulture)); + w.WriteAttributeString("time", elapsed.TotalSeconds.ToString("F3", CultureInfo.InvariantCulture)); + foreach (var r in results.OrderBy(r => r.Test.FullName, StringComparer.Ordinal)) + { + w.WriteStartElement("testcase"); + w.WriteAttributeString("classname", r.Test.Type.FullName); + w.WriteAttributeString("name", r.Test.FullName[(r.Test.Type.FullName!.Length + 1)..]); + w.WriteAttributeString("time", r.Duration.TotalSeconds.ToString("F3", CultureInfo.InvariantCulture)); + if (r.Outcome == TestOutcome.Failed) + { + w.WriteStartElement("failure"); + w.WriteAttributeString("message", Clean(r.Message ?? "failed")); + w.WriteString(Clean((r.StackTrace ?? string.Empty) + Environment.NewLine + r.Log)); + w.WriteEndElement(); + } + else if (r.Outcome == TestOutcome.Skipped) + { + w.WriteStartElement("skipped"); + w.WriteAttributeString("message", Clean(r.Message ?? string.Empty)); + w.WriteEndElement(); + } + w.WriteEndElement(); + } + w.WriteEndElement(); + w.WriteEndElement(); + w.WriteEndDocument(); + } + + private static string Clean(string s) => new(s.Where(XmlConvert.IsXmlChar).ToArray()); + + private sealed class Options + { + public List Filters { get; } = []; + public List Excludes { get; } = []; + public string? JUnitPath { get; private set; } + public int Parallelism { get; private set; } = Math.Max(1, Environment.ProcessorCount); + public bool List { get; private set; } + public bool Verbose { get; private set; } + + public static Options Parse(string[] args) + { + var o = new Options(); + for (var i = 0; i < args.Length; i++) + { + string Next() => i + 1 < args.Length ? args[++i] : throw new ArgumentException($"Missing value after {args[i]}"); + switch (args[i]) + { + case "--filter": o.Filters.Add(Next()); break; + case "--exclude": o.Excludes.Add(Next()); break; + case "--junit": o.JUnitPath = Next(); break; + case "--parallel": o.Parallelism = Math.Max(1, int.Parse(Next(), CultureInfo.InvariantCulture)); break; + case "--list": o.List = true; break; + case "--verbose": o.Verbose = true; break; + default: throw new ArgumentException($"Unknown argument {args[i]}. Use --filter, --exclude, --junit, --parallel, --list, --verbose."); + } + } + return o; + } + + public bool Matches(TestCase t) + { + if (Excludes.Any(f => Match(t, f))) return false; + return Filters.Count == 0 || Filters.Any(f => Match(t, f)); + } + + private static bool Match(TestCase t, string filter) => + filter.StartsWith("category:", StringComparison.OrdinalIgnoreCase) + ? t.Categories.Contains(filter["category:".Length..], StringComparer.OrdinalIgnoreCase) + : t.FullName.Contains(filter, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/Titano.Testing/Titano.Testing.csproj b/tests/Titano.Testing/Titano.Testing.csproj new file mode 100644 index 00000000..3feaef79 --- /dev/null +++ b/tests/Titano.Testing/Titano.Testing.csproj @@ -0,0 +1,6 @@ + + + net10.0 + Titano.Testing + +