Files
Chronos/docs/ARCHITECTURE.md
T
Alby96andClaude Opus 5.5 43b6871cdc feat: jobs run one at a time, parallelism per photo and a priority queue
Owner review 1, phase 2 (docs/requests/2026-10-15-owner-review-1.md, R2).

Jobs now run one at a time on the desktop and on the server. Parallelism
(Settings > Rendering, TITANO_PARALLELISM) is how many photos the running
job processes at once: thumbnail and proxy passes draw that many photos
together and still write the pack and checkpoints in frame order, decode
tiers are probed that many at a time, the deep analysis measures that many
frames and a render decodes that many ahead. Wherever originals are
developed whole (TIFF, PNG, RAW without a usable preview), fewer run at
once within the memory budget, which the running job now has whole; the
server's frame window is sized to the host instead of 1 GiB.

A new job waits its turn and pausing the running job starts the next one.
An optional priority queue gives each job kind a level (renders, imports
and downloads high, verifies and proxies low by default): a queued job of
a higher level pauses the running one without asking, and that job goes
back to the queue with its checkpoint and resumes by itself afterwards.
Jobs of the same level, and a job's own follow-ups, never interrupt it.
The Jobs screen and the admin panel show the parallelism and the queue;
Settings > Rendering and the admin panel's Settings set them, at once.

TITANO_WORKERS and the Workers key of server.json still set the
parallelism (1 to 64, with a warning at start for the variable).
Titano.Tools gains i18n prune, which removed the renamed keys from the 36
machine-translated languages; the new strings are translated in all 38.

Found while testing: uploads and imports failed when a pass read the
sidecar while they wrote it (atomic writes now retry the rename while a
reader holds the file, and never for a read-only one), and taking a lease
just released while another process read it failed on Windows (the create
now waits for the reader). Five adversarial review rounds checked the
phase before this commit.

Also updates BRIEF (12.8, 14.6, 14.8, 14.9, 24), DECISIONS, CHANGELOG,
ARCHITECTURE, STATUS, the request file and the compose/Unraid templates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:56:24 +02:00

283 lines
29 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Titano — Architecture and code conventions
Companion to `docs/BRIEF.md` (scope, behaviour) and `docs/ui/DESIGN.md` (looks). This file says *where code goes*,
*how data moves* and *how it is written*. Decisions behind the shapes described here are in `docs/DECISIONS.md`.
## 1. Projects
| Project | TFM | Purpose |
|---|---|---|
| `src/Titano.Core` | net10.0 | Engine shared by every program: metadata, codecs, imaging, analysis, advisor, motion, render, video containers and managed encoders, archive format, naming, import planning, packaging, localization runtime, diagnostics, brand mark |
| `src/Titano.Core.Windows` | net10.0-windows | WIC decoders and codec inventory, Media Foundation encoders, DXGI adapters, removable devices, DPAPI, shell launcher, window chrome, power (P/Invoke/COM only) |
| `src/Titano.Data` | net10.0 | `IDatabase`, SQLite binding, PostgreSQL wire client, migrations, repositories, the job engine, the archive engine (`Archiving`), the analysis/render engine (`Processing`) and the client sync engine (`Sync`) |
| `src/Titano.Protocol` | net10.0 | API v1 DTOs, source-generated JSON context, typed `TitanoClient` with certificate pinning and bandwidth limiting |
| `src/Titano.Server` | net10.0 (Web SDK) | ASP.NET Core minimal API, auth, uploads, sync, jobs, render nodes, events, embedded admin panel, Windows service host |
| `src/Titano.Ui` | net10.0-windows (WPF) | Theme (DESIGN tokens), icons, standard and custom controls, visuals (charts, filmstrip, preview, curve editor, virtualizing grid), `Loc` markup extension, MVVM helpers, notification-area icon |
| `src/Titano.App` | WPF exe `Titano.exe` | Desktop client |
| `src/Titano.Uploader` | WPF exe | Uploader (tray, watch folders, resumable queue) |
| `src/Titano.Setup` | WPF exe | In-house installer/uninstaller (TPK1 payload) |
| `src/Titano.Tools` | net10.0 exe | CLI: `make-icon`, `i18n` (check, export, missing, import), `xaml-lint`, `package-guard`, `changelog`, `pack-installer`, `selftest`, `diagnose`, `fixtures`, `screenshots` (diff, accept) |
| `tests/Titano.Testing` | net10.0 | In-house test framework (`[Test]`, `[Theory]`+`[Case]`, `[Category]`, `[RequiresEnvironment]`, `[WindowsOnly]`, `[Serial]`, `Assert`, `TestContext`, JUnit) |
| `tests/Titano.*.Tests` | exe | One test program per area; `dotnet run --project tests/X -- --junit out.xml` |
Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `Server`; `Ui` ← `App`, `Uploader`, `Setup`.
`Core`, `Data`, `Protocol` and `Server` never reference Windows-only code (Linux CI builds and tests them).
## 2. Module map
### 2.1 Titano.Core namespaces
| Folder / namespace | Content |
|---|---|
| `Imaging` (+ `Decoders`, `Geometry`, `Thumbnails`) | `ImageBuffer` (planar float, linear light), `IImageDecoderProvider`, `DecoderFactory` (decode tiers: native → embedded preview; `ImageDecoder.Probe` names a file's tier without decoding it; `DecodeRequest.PreferPreview` takes an adequate RAW preview by choice for analyses and previews, `DecodedImage.ByChoice`), `ManagedDecoderProvider`, `FrameWindow` (read-ahead, memory budget, float32 spill), resampler, thumbnail cache |
| `Metadata` (+ `Tiff`, `Jpeg`, `Bmff`, `Raf`, `Riff`, `Png`, `Xmp`, `MakerNotes`) | Signature sniffing, Exif/GPS/XMP/MakerNotes, ISO-BMFF (HEIF, CR3), `MetadataReader`, `MetadataBuilder` (all fallback chains), `ExifWriter` |
| `Codecs` (`Jpeg`, `Png`, `Tiff`, `Dng`, `Raw`, `Gif`, `Apng`, `Ico`) | Pure managed codecs; native RAW development (DNG, CR2, NEF, ARW, PEF, RAF) |
| `Analysis` (+ `Deep`) | Luminance statistics, deflicker, regions, holy grail, white balance, colour temperature, light analysis, streaming deep analysis with checkpoints |
| `Advice` | `Advisor`: recommendations with localisable reasons, apply/optimise, sequence presets |
| `Motion` | FFT, phase correlation, pyramids, optical flow, motion blur, stabiliser, virtual camera, interpolation, stacking |
| `Math` (namespace `Titano.Core.Mathematics`) | Splines, LOWESS, statistics, solar position, 3×3 colour matrices |
| `Project` | `ProjectSettings` (Auto/manual values), export presets, `ProjectBundle` (the `.titano` project file: sequence reference and settings) |
| `Render` | Render plan (timing modes), preparation pass, geometry, `RenderPipeline`, self-test suite |
| `Export` | Preset resolution, encoder selection with fallbacks, output naming |
| `Video` (+ `Mp4`, `Avi`, `Bitstream`, `Yuv`, `Managed`) | `IVideoEncoderProvider`, MP4 muxer and inspector, AVI-MJPEG, NV12/P010, managed encoders (MJPEG-AVI, GIF, APNG, image sequences) |
| `Archiving` | Archive layout and paths, sidecars (`sequence.json`, `project.json`), scanner, index snapshot, leases, thumbnail packs, verify, adopt, rename plans |
| `Import` | Card scan, session detection, import plan, hash-verified copy, card eraser (re-hash before delete) |
| `Naming` | Folder/file templates and tokens |
| `Model` | Domain entities and enums (§5) shared by Data, Server and clients |
| `Packaging` | TPK1 installer payload writer/reader, staged install transaction |
| `Diagnostics` | `Log`, file sink, synthetic sequences, `SecretScrubber`, `DiagnosticsArchive` (scrubbed diagnostics zip) |
| `Localization`, `IO`, `Hashing`, `Branding` | `Loc`/plural rules, `AtomicFile`, `StartupCommand` (sign-in entries of the programs, moved or removed by setup), CRC-32/SHA helpers, brand mark geometry |
### 2.2 Titano.Data
| Folder | Content |
|---|---|
| `Sqlite`, `Postgres` | SQLite P/Invoke binding (winsqlite3 / libsqlite3), in-house PostgreSQL wire protocol v3 client with pool and LISTEN |
| `Migrations/{sqlite,postgres}/NNNN_name.sql` | Embedded, applied in one transaction at open (`MigrationRunner`) |
| `Repositories` | `TitanoDatabase` facade: archives, sequences, frames, tags, renders, jobs, cards, users, tokens, uploads, render nodes, settings, audit; `DatabaseBackups` (daily `VACUUM INTO` copies of an SQLite index kept ×3, restore staged for the next start and carried out before the index opens, so it also recovers one that no longer opens) |
| `Jobs` | `JobEngine` (one job at a time; reviews the priority queue and makes a lower running job yield, requeued with its checkpoint), `JobPriorityQueue` (a level per job kind, the claim order, settings round trip), `IJobHandler`, `IJobHandlerProvider`, `JobContext` (progress, checkpoints, follow-up jobs that never interrupt their parent), `JobThroughput`/`JobEta` (rate and bounded time left) |
| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index), `ArchiveIndexer` (scan, rebuild), `ArchiveIngest` (uploads and imports), `ImportService`, `ArchiveVerifier`, `ArchiveImages` (thumbnail and proxy passes, several photos at once through `OrderedWork`, which hands results back in frame order), `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance`, `MassRenamer`, `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails), job handlers |
| `Processing` | `ProcessingService`, `SequenceAnalyser`, `DeepReports` (a saved deep report while it still describes the frames), `SequenceRender`, `ProjectStore`, `ProjectBundles` (a `.titano` file for a sequence, and the sequence a file names), `RenderNodeClient`, job handlers |
| `Sync` | `SyncService` (sync table of one server: compare, link by content, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, no I/O), `SyncPositions` (the settings' frame positions translated by photo to the frames of the copy they go to), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest), `SyncAgent` (background comparison, server events, backoff, offline proxies), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `TitanoSyncRemote` over `TitanoClient`) |
### 2.3 Titano.App areas
| Folder | Content |
|---|---|
| `Shell` | `MainWindow` (rail and its shortcuts, taskbar progress), `ShellViewModel` (rail, sections, first run), `OsNotifications` (toasts as Windows notifications while the window is minimised or in the background), dialogs, `ErrorText` (the sentence of an error toast), `ScreenCapture` (`--capture` scenes), `SectionTemplates.xaml` (view model → view) |
| `Sections` | One `XxxView.xaml` + `XxxViewModel` per screen: Welcome, Library, Sequence (editor), Import, Archive, Jobs, Server, Settings, About |
| `Library` | Filter, facets, pager, timeline, saved views, quick and mass actions, remote cards and thumbnails, thumbnail cache, list export |
| `Editor` | `EditorSession` (project, undo/redo, saving, merges), `ISequenceSource` (`LocalSequenceSource`, `RemoteSequenceSource`), tabs (Frames, Exposure, Camera, Motion, Export), `PreviewRenderer`, `ExportPlanner`, `ExportSync`, `SavedCopies`, `SequenceJobs`, `ProjectFiles` (save and open `.titano` project files) |
| `Import` | `CardPool` (inserted cards, remembered cards, folders), camera profiles, plans and choices, destinations (archive, folder, server through `ServerImportSink`), card actions (verified delete, format, eject) |
| `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, mass rename and move, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`), `ArchiveFailures` |
| `Server` | `ServerSession`, `ConnectFlow` (trust on first use), `SyncHost` (sync engine, agent, metered hold, editor connections, Export Sync), sync table, `RemoteSequenceApi` |
| `Jobs`, `Settings`, `About` | Job list and buffering, `JobNotices` (which job endings raise a toast; `JobEndings` lets a batch speak once); settings rows, encoder and format inventories, `ProcessingTuning` (Settings › Rendering and Analysis applied to each job: parallelism, memory budget, quality), `InterfacePriority`, language catalog, naming preview; update check and download |
| `Infrastructure` | `AppServices` (composition root), `AppSettings`, `AppEnvironment` (installed or portable), `AppClock` (today's date, frozen by `--capture`), `StartWithWindows` (this copy's sign-in entry), `UiLanguage`, `LiveRegion`, `RenderNodeHost`, `DiagnosticsBundle`, `ShellActions` (BRIEF §8.6), `SingleInstance` (one Titano per data folder; a later launch hands its file over a named pipe, or waits for a closing one to exit and starts in its place), device monitor |
| `DesignTime` | `SampleData`: the archive, jobs and server the screenshots and smoke tests run on, dated from the fixed `SampleData.Now` |
### 2.4 Titano.Ui and Titano.Server
| Folder | Content |
|---|---|
| `Ui/Themes`, `Ui/Theming` | DESIGN tokens (light, dark), typography, control styles, `ThemeManager` |
| `Ui/Controls` | `TitanoWindow` (chrome, language direction), `NavRail`, `JobBar`, `ToastHost`, `Field` (placeholder, icon, error), `Chip`, `AutoSlider`, `StatusGlyph`, `EmptyState`, `Icon`, `Bidi` (right-to-left rules), `Motion` (animations off for screenshots) |
| `Ui/Interop` | DWM calls of the window chrome; `TrayIcon` (`Shell_NotifyIconW`: the Uploader's tray, the client's Windows notifications) |
| `Ui/Visuals` | `DrawingElement` (hover readout, item keyboard and activation) and its charts (`BarChart`, `SeriesChart`, `StackedBar`, `HeatmapStrip`, `TimelineBands`), `Filmstrip`, `PreviewViewport`, `CurveEditor`, `SequenceCard`, `VirtualizingWrapPanel`, `SegmentedControl`, `SplitButton` |
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`), API errors, the WebSocket `EventHub` |
| `Server/Security` | Accounts, password hashing, tokens, session cookies, login guard, access rules, audit log |
| `Server/Storage`, `Server/Jobs` | Archive and processing modules, uploads, render store; `JobEngineHost`, render node service, monitor and availability |
| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, certificates, discovery beacon, embedded static files, Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page) |
### 2.5 Hosts
| Host | Composition root | What it runs |
|---|---|---|
| Titano (desktop) | `App/Infrastructure/AppServices` | SQLite index in `%LOCALAPPDATA%\Titano` (or `.\data` when portable, unless the copy is in a OneDrive folder); `ArchiveService` with WIC first, then managed decoders; `ProcessingService` with Media Foundation, then managed encoders; one `JobEngine` with the handlers of both; thumbnails; `ServerSession`; `SyncHost` while signed in (sync engine and agent, upload and download handlers, metered hold, editors of server sequences); the render node while opted in and signed in; update check and download (`About/UpdateCheck`, `About/UpdateDownload`, `About/UpdateFlow`: the setup, or the portable zip for a portable copy, verified against `SHA256SUMS`, resumable, cancellable, failing after 60 s without data); diagnostics bundle; daily index backups and the restore staged in Settings › Advanced (`DatabaseBackups`) |
| Titano Server | `Server/Hosting/ServerHost.Build` | Options from `server.json` + `TITANO_*`; PostgreSQL (or SQLite on Windows); `ArchiveModule` then `ProcessingModule` register job handler providers; `JobEngineHost` (renders only managed formats and MP4 jobs no render node can take, BRIEF §14.7); `RenderNodeService`/`RenderNodeMonitor`; `UploadService`; `EventHub` (WebSocket); embedded admin panel; LAN discovery beacon; Windows service host; daily backups of an SQLite index (`DatabaseBackupService`) |
| Titano Uploader | `Uploader/App.xaml.cs` | `TitanoClient`, persisted queue, watch folders; no database |
| Titano Setup | `Setup/Program` | TPK1 payload extraction, registry, shortcuts, file types named in setup's language, silent mode, uninstaller; only what starts a program its log or payload lists is changed: Windows services of those programs stopped once the programs have closed, started again (also after a failure) or deleted through the Service Control Manager (an elevated `/SERVICES … /NAMES` step when needed), sign-in entries of those programs moved to the program an upgrade renamed or removed, shared shortcuts handed to the product that keeps the program; the Server only for all users inside Program Files; "Remove my data" limited to the programs no other installed product uses |
### 2.6 Job kinds and their handlers
| `JobKind` | Handler (Titano.Data) | Desktop | Server |
|---|---|---|---|
| `Scan`, `Rebuild` | `Archiving/Jobs/ScanJobHandler` (via `ArchiveService.CreateJobHandlers`) | yes | yes |
| `Verify` | `Archiving/Jobs/VerifyJobHandler` | yes | yes |
| `Import` | `Archiving/Jobs/ImportJobHandler` | yes | yes |
| `Thumbs`, `Proxies` | `Archiving/Jobs/ImageJobHandler` | yes | yes |
| `Maintenance` | `Archiving/Jobs/MaintenanceJobHandler` | yes | yes |
| `LightAnalyse`, `DeepAnalyse` | `Processing/Jobs/AnalyseJobHandler` (via `ProcessingService.CreateJobHandlers`) | yes | yes |
| `Render` | `Processing/Jobs/RenderJobHandler` | yes | managed formats, and MP4 jobs no render node can take (`RenderNodeAvailability`); render nodes claim the others (`Server/Jobs/RenderNodeService`) |
| `UploadCommit`, `Download` | `Sync/SyncJobHandler` (via `SyncService.CreateJobHandlers`): this PC's uploads to and downloads from its server | yes | no: an upload completes synchronously on the server |
| `Duplicates`, `Orphans`, `Adopt`, `Move` | none: done synchronously (`ArchiveService` queries and actions) | — | — |
A job engine claims only kinds it has handlers for. Light analysis is queued by the engine (`JobContext` follow-up)
after an import or a scan that indexed something; screens never queue it again.
## 3. Data flow
```
card / folder ──► Core.Import (plan, sessions) ──► ImportService ─┐
Uploader / client ──► POST /uploads, chunks ──► UploadService ────┤ hash verified
▼
ArchiveIngest: temp → fsync → rename into originals/,
sidecar (sequence.json, journalled) → index rows
│
┌────────────────────────────────────────────────────┼─────────────────────────┐
▼ ▼ ▼
LightAnalyse (metadata) Thumbs / Proxies (thumbs.pack) events: sequenceChanged
DeepAnalyse (pixels, checkpoints)
│
▼
Advice.Advisor → ProjectSettings (Auto values with reasons) → project.json
│
▼
Render job: RenderPlan → RenderPipeline (FrameWindow, motion, deflicker…) → IVideoEncoderProvider
│ desktop: Media Foundation → managed; server: render node (GPU PC) → managed
▼
output file (temp → rename) + renders row
```
The sidecars are the truth; the index is derived and can always be rebuilt (`ScanMode.Rebuild`, using the index
snapshot when fresh). Writers coordinate through lease files, so a desktop and a server may share an archive.
Sync (desktop ↔ server, BRIEF §14.5) reuses the same paths: `SyncService` compares the local index with the server's
listing (settings and tags carry version counters), uploads go through the chunked protocol into the server's
`ArchiveIngest`, downloaded originals are verified and committed through the local `ArchiveIngest`, and proxies land
in the `ProxyCache`. A server sequence opens in the editor as a `RemoteSequence` through `RemoteSequenceSource`:
settings are saved with the version they were made from, a 409 merges or asks the user, and analyses and renders
run as server jobs whose progress comes from the events.
## 4. Extension points
| To add | Implement / register |
|---|---|
| An image format or decoder | `IImageDecoderProvider` (managed in `Core/Imaging/Decoders` or `Codecs`, WIC in `Core.Windows`: a RAW only through the Raw Image Extension, checked per file); chained by `DecoderFactory` |
| A video encoder | `IVideoEncoderProvider` (`Core/Video/Managed`, `Core.Windows/MediaFoundation`); list it in the host's `ProcessingOptions.Encoders` |
| A background operation | a `JobKind`, an `IJobHandler` (in `Data/Archiving/Jobs` or `Data/Processing/Jobs`) returned by the service's `CreateJobHandlers`; the job engine, Jobs screen, admin and API pick it up |
| A server feature | a static `XxxEndpoints.Map(api)` in `Server/Api` with `.Requires(Permissions…)`, called from `ServerHost.ConfigurePipeline`; DTOs in `Titano.Protocol` with the JSON context |
| A server storage backend | `IArchiveIngest`, `IFrameAssetLocator` through the `ServerHost.Build` registration callback |
| A schema change | `Data/Migrations/{sqlite,postgres}/NNNN_topic.sql` (never edit an applied one) |
| An advisor rule | `Core/Advice` with a localised reason key in `Advisor` |
| A UI string | `i18n/en/<Area>.resx` + `i18n/it/<Area>.it.resx` (other languages via `i18n missing`/`import`) |
| An admin page | ES module in `Server/Admin/web/pages`, strings in the `Admin` area |
| A CLI command | `ICommand` in `Tools/Commands`, listed in `Tools/Program.cs` |
| A desktop screen | `Sections/XxxView.xaml` + `XxxViewModel`, its `DataTemplate` in `Shell/SectionTemplates.xaml`, the property and rail entry in `ShellViewModel`, a scene in `Shell/ScreenCapture` with sample data, a smoke test in `Titano.App.Tests/Windows` |
## 5. 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.
- Never name a namespace `Archive` (it would shadow the entity): the archive code lives in `Archiving`. Inside
Titano.Core never write an unqualified `Math.`: use `System.Math` or `double.Max`.
- 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<T>`, `System.Numerics.Vector<T>`/`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<T>` or the `JobContext`.
- Libraries use `ConfigureAwait(false)`. No `async void` except WPF event handlers. Heavy work and I/O never run on
the UI thread.
- Logging through `Titano.Core.Diagnostics.Log` in Core and Data; `ILogger` on the server. Anything that leaves the
machine (diagnostics bundles) passes through `SecretScrubber`.
- 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); originals are never modified.
- IDs are UUIDv7 (`Guid.CreateVersion7()`); timestamps UTC; capture times are camera wall-clock with an optional
offset.
- The only OS actions the programs perform are those of BRIEF §8.6: open a URL and show a folder or file in Explorer
(`ShellActions` in the App), the format-volume dialog (`Core.Windows/Devices`). Downloaded updates (the setup, or
the portable zip for a portable copy) are shown in Explorer, never started.
### 5.1 Desktop UI (WPF)
- Every string comes from the catalog (`Loc.L`, `{l:Loc}`); labels ≤ 3 words, explanations only in tooltips. Every
actionable control has a tooltip, and an icon-only one a two-word accessible name: the screen smoke tests check
both on every screen.
- Windows derive from `TitanoWindow`, which takes the UI language's direction at creation and on every switch;
screens never set `FlowDirection` for the language. Photos, charts, numbers, paths and templates are left-to-right
islands on the smallest element holding them; directional icons mirror by themselves (`IconData.IsDirectional`,
overridden per subtree with `Bidi.IsDirectional`); left-to-right fragments inside a right-to-left sentence go
through `BidiText`. Fields of a meta line are joined with `Loc.Separator`, never a literal " · ": in a
right-to-left language it holds right-to-left marks, so a number after a Latin field keeps to its own field. Fields
shown inside a left-to-right island (the frame data over the preview) use `Loc.IslandSeparator`, which holds
left-to-right marks instead. Charts draw digits as European ones, like every text block.
- The language switches without restart: computed properties re-read through `LocalizedViewModel`, and a view model
that keeps texts in objects (chart series and legends, rows, cached sentences) makes them again in
`OnLanguageChanged`.
- Radio buttons group by their parent panel. `GroupName` is shared by every window whose visual root is not known
yet, so it is used only where the bindings are one-way (chips generated by item templates, the rail).
- Content a control presents through its template from a dependency property other than `Content` is made a logical
child of the control (`AddLogicalChild` and `LogicalChildren`), so it inherits the data context and resolves
`ElementName` and ancestor bindings (`PreviewViewport.ToolsContent`).
- Status lines that change are live regions (`LiveRegion.Text` with `AutomationProperties.LiveSetting`); inputs
without a validating binding show errors with `Field.Error`; failure toasts set `Toast.IsError`, which screen
readers hear as important. Charts expose their items to automation and take the keyboard only when an item can
be activated.
- Failures reach the user as one sentence chosen by cause (`ErrorText`, `ArchiveFailures`, `ImportFailures`) with
one action; the exception text goes to the tooltip and the log only.
- Destructive actions show their dry run first; irreversible ones ask for a typed confirmation and keep Cancel as
the default button. An explicit dry run stops any debounced one still pending.
## 6. Tests
- Framework: `Titano.Testing`. Test classes are `public sealed`; constructor may take `TestContext` (temp
directories, cancellation, log). `[WindowsOnly]` for OS-specific tests, `[RequiresEnvironment("TITANO_TEST_PG")]`
for PostgreSQL integration tests.
- Classes run in parallel. A test that changes or observes process-wide state (the UI language, unobserved task
exceptions, the managed heap) belongs in a `[Serial]` class; the App and Core test programs fail a test outside one
that switches the language away from English, after switching it back (`TestContext.Current`).
- Put tests under `tests/Titano.<Area>.Tests/<Folder>/<Thing>Tests.cs`, mirroring the source folder.
- `Titano.App.Tests` targets net10.0-windows and runs on Windows CI only: keep logic in plain classes.
- Fixtures are synthetic and generated in code wherever possible; tiny binary fixtures may go in `tests/fixtures/`
(< 50 KB each). CC0 RAW samples are fetched by `Titano.Tools fixtures` into `tests/fixtures/external/` (not
committed); tests depending on them skip when absent and CI shows a warning per missing sample.
- Fuzz tests: truncate and corrupt valid inputs at many offsets; assert no exception escapes.
- Performance gates (`tests/Titano.Data.Tests/Perf`, `[Category("perf")]`, run only with `TITANO_PERF=1`): the
500,000-photo library (Library open < 1 s on a new connection pool, filters < 200 ms; the OS cache is warm from
building it) and the 100,000-frame rebuild from sidecars (400 sequences of 250 real photos, every column compared,
< 120 s), each on SQLite and PostgreSQL. `.github/workflows/perf.yml` runs them weekly against PostgreSQL 17.
- `Titano.Tools.Tests` covers the tools whose output CI relies on (fixtures annotations and exit codes, the screenshot
diff) and the test runner's outcomes.
- Visual regression: CI compares the `--capture` screenshots with `tests/visual/baselines` (`Titano.Tools screenshots
diff`; its README says how baselines are added). Once any baseline is committed, a screen without one fails too;
before that the step warns that it compared nothing. The capture draws the same pixels on any day: the sample's
clock is fixed, formats are English and nothing animates.
- Media Foundation output plays back (`Titano.Core.Windows.Tests`): MediaPlayer opens it where Windows Media Player
is installed (skipped, with the reason, where it is not) and a source reader decodes its first frame everywhere.
- PostgreSQL: CI prepares the service containers with `.github/scripts/postgres-ci-setup.sh` (MD5, cleartext and
trust roles, TLS), so every authentication method and TLS mode of BRIEF §6.3 runs; `TITANO_TEST_PG_TLS=1` makes a
server without TLS fail the TLS tests.
## 7. Localization
- Keys: `Area.Group.Name`; area = file name. Areas: About, Admin, Advisor, Archive, Common, Editor, Errors, Export,
Import, Jobs, Library, Server, Settings, Setup, Shell, Tooltips, Uploader.
- `en` is the source (`i18n/en/<Area>.resx`), `it` is mandatory (`i18n/it/<Area>.it.resx`); other languages are
machine-translated through `i18n missing` / `i18n import` with `i18n/GLOSSARY.md` and a per-language glossary.
- 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)`; keys that travel as
data (analysis findings, advisor reasons) by `Loc.Text(key, args)`, with the count as their first argument. A text
with two or more counts reads as labels ("Frames: 300, warnings: 2", "Copied: 40 · failed: 2"). `i18n check` fails on
an English text that puts a number before a counted noun without plural forms, or that tallies two or more counts
with participles or adjectives ("40 copied · 2 failed"), which agree with the number in other languages.
## 8. Build, checks and CI
```
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
dotnet format whitespace Titano.slnx --verify-no-changes
```
| Workflow | Trigger | Does |
|---|---|---|
| `ci.yml` | push to `main`, pull requests | Windows + Linux build and tests, guards, i18n, XAML lint, format, fixtures (warnings when missing), screenshots and their pixel diff, installer test (install, run, upgrade, uninstall), PostgreSQL 16/17 (every authentication method, TLS), Docker smoke test |
| `release.yml` | tag `v*` (or manual re-publish) | Tests, self-contained publish, optional signing, installers, portable and server zips, SHA256SUMS, release notes, multi-arch GHCR image, public releases repository update and GitHub release |
| `docker.yml` | nightly | `ghcr.io/<owner>/titano-server:nightly` |
| `perf.yml` | weekly, manual | Performance gates (SQLite, PostgreSQL 17) with timings in the job summary |